Skip to content

Commit

Permalink
[XLA:CPU] Factor out constant allocation utilities from cpu compiler.
Browse files Browse the repository at this point in the history
Future plans are to remove AOT compilation results from cpu compiler, this will enable both modules to share the code.

PiperOrigin-RevId: 731715948
  • Loading branch information
Google-ML-Automation committed Feb 27, 2025
1 parent f72c7b8 commit b362969
Show file tree
Hide file tree
Showing 4 changed files with 176 additions and 81 deletions.
21 changes: 21 additions & 0 deletions xla/service/cpu/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -195,13 +195,34 @@ cc_library(
],
)

cc_library(
name = "constant_allocation_util",
srcs = ["constant_allocation_util.cc"],
hdrs = ["constant_allocation_util.h"],
deps = [
":cpu_executable",
"//xla:literal",
"//xla:shape_util",
"//xla:util",
"//xla/hlo/ir:hlo",
"//xla/service:buffer_assignment",
"//xla/tsl/platform:statusor",
"@com_google_absl//absl/log",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:span",
],
)

cc_library(
name = "cpu_compiler_pure",
srcs = ["cpu_compiler.cc"],
hdrs = ["cpu_compiler.h"],
copts = tsl_copts(),
deps = [
":buffer_info_util",
":constant_allocation_util",
":conv_canonicalization",
":cpu_executable",
":cpu_float_support",
Expand Down
121 changes: 121 additions & 0 deletions xla/service/cpu/constant_allocation_util.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/* Copyright 2025 The OpenXLA Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "xla/service/cpu/constant_allocation_util.h"

#include <cstdint>
#include <memory>
#include <utility>
#include <vector>

#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/literal.h"
#include "xla/primitive_util.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/cpu/cpu_executable.h"
#include "xla/shape_util.h"
#include "xla/tsl/platform/statusor.h"
#include "xla/util.h"

namespace xla::cpu {

static absl::StatusOr<CpuExecutable::ConstantAllocation>
LiteralToConstantAllocation(BufferAllocation::Index index,
const Literal& literal) {
// TODO(ezhulenev): This code is almost identical to code in XLA:GPU, we
// should standardize it. See `xla/service/gpu/ir_emission_utils.cc`.
PrimitiveType element_type = literal.shape().element_type();
if (!primitive_util::IsArrayType(element_type)) {
return absl::InternalError(
"Only array literals can be converted to constant allocations");
}

int64_t size_bytes = literal.size_bytes();
const void* untyped_data = literal.untyped_data();

// Pack sub-byte types into an XLA storage format.
if (primitive_util::IsSubByteNonPredType(element_type)) {
int bit_width = primitive_util::BitWidth(element_type);
int packed_size_bytes = CeilOfRatio<int64_t>(size_bytes, 8 / bit_width);

// Use Literal as a storage for packed data as it allocates underlying
// buffer with correct alignment. Keep it allocated on heap to avoid
// capturing stack address that will be invalidated by a move below.
auto packed = std::make_unique<Literal>(
ShapeUtil::MakeShape(U8, {packed_size_bytes}));

PackIntN(
bit_width,
absl::MakeSpan(reinterpret_cast<const char*>(untyped_data), size_bytes),
absl::MakeSpan(reinterpret_cast<char*>(packed->untyped_data()),
packed->size_bytes()));

return CpuExecutable::ConstantAllocation{index, std::move(packed)};
}

// Create a constant allocation from the literal's untyped data.
return CpuExecutable::ConstantAllocation{
index, absl::Span<const uint8_t>(
reinterpret_cast<const uint8_t*>(untyped_data), size_bytes)};
}

// Creates a vector of constant allocations from the given buffer assignment.
absl::StatusOr<std::vector<CpuExecutable::ConstantAllocation>>
CreateConstantAllocations(const BufferAssignment& assignment) {
std::vector<CpuExecutable::ConstantAllocation> constants;

for (const BufferAllocation& allocation : assignment.Allocations()) {
if (!allocation.is_constant()) {
continue;
}

// Find the constant instruction defining the value for allocation.
HloInstruction* const_instr = nullptr;
for (const auto& [value, _] : allocation.assigned_buffers()) {
// Multiple aliasing instructions can share the allocation, we need to
// find the original constant instruction that defines the value.
if (value->instruction()->opcode() == HloOpcode::kConstant) {
if (const_instr != nullptr) {
return absl::InternalError(
absl::StrCat("Multiple constant instructions define buffer ",
allocation.ToString()));
}
const_instr = value->instruction();
}
}
if (const_instr == nullptr) {
return absl::InternalError(
absl::StrCat("Could not find constant instruction defining buffer ",
allocation.ToString()));
}

VLOG(3) << "Create constant allocation for index " << allocation.index()
<< " from constant literal " << const_instr->name()
<< "; shape=" << const_instr->literal().shape();
TF_ASSIGN_OR_RETURN(constants.emplace_back(),
LiteralToConstantAllocation(allocation.index(),
const_instr->literal()));
}

return constants;
}

} // namespace xla::cpu
33 changes: 33 additions & 0 deletions xla/service/cpu/constant_allocation_util.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* Copyright 2025 The OpenXLA Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#ifndef XLA_SERVICE_CPU_CONSTANT_ALLOCATION_UTIL_H_
#define XLA_SERVICE_CPU_CONSTANT_ALLOCATION_UTIL_H_

#include <vector>

#include "absl/status/statusor.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/cpu/cpu_executable.h"

namespace xla::cpu {

// Creates a vector of constant allocations from the given buffer assignment.
absl::StatusOr<std::vector<CpuExecutable::ConstantAllocation>>
CreateConstantAllocations(const BufferAssignment& assignment);

} // namespace xla::cpu

#endif // XLA_SERVICE_CPU_CONSTANT_ALLOCATION_UTIL_H_
82 changes: 1 addition & 81 deletions xla/service/cpu/cpu_compiler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ limitations under the License.
#include "xla/service/conditional_to_select.h"
#include "xla/service/copy_insertion.h"
#include "xla/service/cpu/buffer_info_util.h"
#include "xla/service/cpu/constant_allocation_util.h"
#include "xla/service/cpu/conv_canonicalization.h"
#include "xla/service/cpu/cpu_executable.h"
#include "xla/service/cpu/cpu_instruction_fusion.h"
Expand Down Expand Up @@ -1115,87 +1116,6 @@ std::vector<ComputationToEmit> SubcomputationEmissionOrder(

} // namespace

static absl::StatusOr<CpuExecutable::ConstantAllocation>
LiteralToConstantAllocation(BufferAllocation::Index index,
const Literal& literal) {
// TODO(ezhulenev): This code is almost identical to code in XLA:GPU, we
// should standardize it. See `xla/service/gpu/ir_emission_utils.cc`.
PrimitiveType element_type = literal.shape().element_type();
if (!primitive_util::IsArrayType(element_type)) {
return absl::InternalError(
"Only array literals can be converted to constant allocations");
}

int64_t size_bytes = literal.size_bytes();
const void* untyped_data = literal.untyped_data();

// Pack sub-byte types into an XLA storage format.
if (primitive_util::IsSubByteNonPredType(element_type)) {
int bit_width = primitive_util::BitWidth(element_type);
int packed_size_bytes = CeilOfRatio<int64_t>(size_bytes, 8 / bit_width);

// Use Literal as a storage for packed data as it allocates underlying
// buffer with correct alignment. Keep it allocated on heap to avoid
// capturing stack address that will be invalidated by a move below.
auto packed = std::make_unique<Literal>(
ShapeUtil::MakeShape(U8, {packed_size_bytes}));

PackIntN(
bit_width,
absl::MakeSpan(reinterpret_cast<const char*>(untyped_data), size_bytes),
absl::MakeSpan(reinterpret_cast<char*>(packed->untyped_data()),
packed->size_bytes()));

return CpuExecutable::ConstantAllocation{index, std::move(packed)};
}

// Create a constant allocation from the literal's untyped data.
return CpuExecutable::ConstantAllocation{
index, absl::Span<const uint8_t>(
reinterpret_cast<const uint8_t*>(untyped_data), size_bytes)};
}

// Creates a vector of constant allocations from the given buffer assignment.
static absl::StatusOr<std::vector<CpuExecutable::ConstantAllocation>>
CreateConstantAllocations(const BufferAssignment& assignment) {
std::vector<CpuExecutable::ConstantAllocation> constants;

for (const BufferAllocation& allocation : assignment.Allocations()) {
if (!allocation.is_constant()) {
continue;
}

// Find the constant instruction defining the value for allocation.
HloInstruction* const_instr = nullptr;
for (const auto& [value, _] : allocation.assigned_buffers()) {
// Multiple aliasing instructions can share the allocation, we need to
// find the original constant instruction that defines the value.
if (value->instruction()->opcode() == HloOpcode::kConstant) {
if (const_instr != nullptr) {
return absl::InternalError(
absl::StrCat("Multiple constant instructions define buffer ",
allocation.ToString()));
}
const_instr = value->instruction();
}
}
if (const_instr == nullptr) {
return absl::InternalError(
absl::StrCat("Could not find constant instruction defining buffer ",
allocation.ToString()));
}

VLOG(3) << "Create constant allocation for index " << allocation.index()
<< " from constant literal " << const_instr->name()
<< "; shape=" << const_instr->literal().shape();
TF_ASSIGN_OR_RETURN(constants.emplace_back(),
LiteralToConstantAllocation(allocation.index(),
const_instr->literal()));
}

return constants;
}

// Removes unused globals and function declarations from the LLVM module.
//
// After splitting LLVM module into multiple parts, we end up with unused
Expand Down

0 comments on commit b362969

Please sign in to comment.