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 Mar 1, 2025
1 parent 92b05a5 commit 83765d3
Show file tree
Hide file tree
Showing 9 changed files with 218 additions and 118 deletions.
20 changes: 20 additions & 0 deletions xla/backends/cpu/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,23 @@ cc_library(
"@com_google_absl//absl/strings:string_view",
],
)

cc_library(
name = "constant_allocation",
srcs = ["constant_allocation.cc"],
hdrs = ["constant_allocation.h"],
deps = [
"//xla:literal",
"//xla:shape_util",
"//xla:util",
"//xla/hlo/ir:hlo",
"//xla/service:buffer_assignment",
"//xla/stream_executor:device_memory",
"//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",
],
)
137 changes: 137 additions & 0 deletions xla/backends/cpu/constant_allocation.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/* 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/backends/cpu/constant_allocation.h"

#include <cstdint>
#include <memory>
#include <utility>
#include <variant>
#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/shape_util.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/tsl/platform/statusor.h"
#include "xla/util.h"

namespace xla::cpu {

se::DeviceMemoryBase ConstantAllocation::AsDeviceMemoryBase() const {
if (auto* _ = std::get_if<std::monostate>(&data)) {
return se::DeviceMemoryBase();
}

if (auto* owned = std::get_if<std::unique_ptr<Literal>>(&data)) {
return se::DeviceMemoryBase((*owned)->untyped_data(),
(*owned)->size_bytes());
}

auto* view = std::get_if<absl::Span<const uint8_t>>(&data);
return se::DeviceMemoryBase(
const_cast<void*>(reinterpret_cast<const void*>(view->data())),
view->size());
}

static absl::StatusOr<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 ConstantAllocation{index, std::move(packed)};
}

// Create a constant allocation from the literal's untyped data.
return 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<ConstantAllocation>> CreateConstantAllocations(
const BufferAssignment& assignment) {
std::vector<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
48 changes: 48 additions & 0 deletions xla/backends/cpu/constant_allocation.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* 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_BACKENDS_CPU_CONSTANT_ALLOCATION_H_
#define XLA_BACKENDS_CPU_CONSTANT_ALLOCATION_H_

#include <cstdint>
#include <memory>
#include <variant>
#include <vector>

#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/literal.h"
#include "xla/service/buffer_assignment.h"
#include "xla/stream_executor/device_memory.h"

namespace xla::cpu {

// A storage (or an alias) for constant allocations data.
struct ConstantAllocation {
se::DeviceMemoryBase AsDeviceMemoryBase() const;

BufferAllocation::Index index = -1;
std::variant<std::monostate, std::unique_ptr<Literal>,
absl::Span<const uint8_t>>
data;
};

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

} // namespace xla::cpu

#endif // XLA_BACKENDS_CPU_CONSTANT_ALLOCATION_H_
1 change: 1 addition & 0 deletions xla/pjrt/cpu/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ cc_library(
"//xla:util",
"//xla:xla_data_proto_cc",
"//xla:xla_proto_cc",
"//xla/backends/cpu:constant_allocation",
"//xla/backends/cpu/codegen:cpu_features",
"//xla/backends/cpu/collectives:cpu_collectives",
"//xla/backends/cpu/runtime:buffer_allocations",
Expand Down
8 changes: 4 additions & 4 deletions xla/pjrt/cpu/cpu_client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ limitations under the License.

#include "xla/pjrt/cpu/cpu_client.h"

#include "xla/pjrt/plugin/xla_cpu/cpu_execute_options.h"

#define EIGEN_USE_THREADS

#include <algorithm>
Expand Down Expand Up @@ -52,6 +50,7 @@ limitations under the License.
#include "xla/array.h"
#include "xla/backends/cpu/codegen/cpu_features.h"
#include "xla/backends/cpu/collectives/cpu_collectives.h"
#include "xla/backends/cpu/constant_allocation.h"
#include "xla/backends/cpu/runtime/buffer_allocations.h"
#include "xla/backends/cpu/runtime/thread_pool_task_runner.h"
#include "xla/backends/cpu/runtime/thunk.h"
Expand Down Expand Up @@ -83,6 +82,7 @@ limitations under the License.
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/plugin/xla_cpu/cpu_client_options.h"
#include "xla/pjrt/plugin/xla_cpu/cpu_execute_options.h"
#include "xla/pjrt/plugin/xla_cpu/cpu_topology.h"
#include "xla/pjrt/plugin/xla_cpu/cpu_topology_description.h"
#include "xla/pjrt/semaphore.h"
Expand Down Expand Up @@ -1224,7 +1224,7 @@ struct BufferAllocAndCopy {
// and assemble the buffer pointers in order to call into CpuExecutable.
static absl::StatusOr<BufferInfo> MemoryForAllocation(
const BufferAllocation& allocation,
absl::Span<const cpu::CpuExecutable::ConstantAllocation> constants,
absl::Span<const cpu::ConstantAllocation> constants,
absl::Span<std::pair<bool, TrackedTfrtCpuDeviceBuffer*> const> arguments,
BufferAlloc& buffer_alloc, BufferAllocAndCopy& buffer_alloc_and_copy) {
BufferInfo buffer_info;
Expand Down Expand Up @@ -1289,7 +1289,7 @@ static absl::StatusOr<BufferInfo> MemoryForAllocation(

static absl::StatusOr<std::vector<BufferInfo>> CreateBufferTable(
const BufferAssignment& assignment,
absl::Span<const cpu::CpuExecutable::ConstantAllocation> constants,
absl::Span<const cpu::ConstantAllocation> constants,
absl::Span<std::pair<bool, TrackedTfrtCpuDeviceBuffer*> const> arguments,
BufferAlloc& buffer_alloc, BufferAllocAndCopy& buffer_alloc_and_copy) {
std::vector<BufferInfo> buffer_table(assignment.Allocations().size());
Expand Down
2 changes: 2 additions & 0 deletions xla/service/cpu/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ cc_library(
"//xla:util",
"//xla:xla_data_proto_cc",
"//xla:xla_proto_cc",
"//xla/backends/cpu:constant_allocation",
"//xla/backends/cpu/codegen:compiled_function_library",
"//xla/backends/cpu/codegen:cpu_features",
"//xla/backends/cpu/codegen:execution_engine",
Expand Down Expand Up @@ -586,6 +587,7 @@ cc_library(
"//xla:status_macros",
"//xla:util",
"//xla:xla_data_proto_cc",
"//xla/backends/cpu:constant_allocation",
"//xla/backends/cpu/runtime:buffer_allocations",
"//xla/backends/cpu/runtime:function_library",
"//xla/backends/cpu/runtime:thread_pool_task_runner",
Expand Down
92 changes: 5 additions & 87 deletions xla/service/cpu/cpu_compiler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ limitations under the License.
#include "xla/backends/cpu/codegen/jit_compiler.h"
#include "xla/backends/cpu/codegen/object_loader.h"
#include "xla/backends/cpu/codegen/target_machine_features.h"
#include "xla/backends/cpu/constant_allocation.h"
#include "xla/backends/cpu/runtime/function_library.h"
#include "xla/backends/cpu/runtime/thunk.h"
#include "xla/backends/cpu/runtime/thunk.pb.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 Expand Up @@ -1634,9 +1554,8 @@ CpuCompiler::CompileCpuExecutable(std::unique_ptr<HloModule> module) {
std::move(jit_compiler).Compile(compiled_symbols));

// Create constant allocations from the buffer assignment.
TF_ASSIGN_OR_RETURN(
std::vector<CpuExecutable::ConstantAllocation> constants,
CreateConstantAllocations(*assignment));
TF_ASSIGN_OR_RETURN(std::vector<ConstantAllocation> constants,
CreateConstantAllocations(*assignment));

TF_ASSIGN_OR_RETURN(
auto cpu_executable,
Expand Down Expand Up @@ -2229,9 +2148,8 @@ CpuExecutableAotCompilationResult::LoadExecutable(
std::move(object_loader).Load(compiled_symbols));

// Create constant allocations from the buffer assignment.
TF_ASSIGN_OR_RETURN(
std::vector<CpuExecutable::ConstantAllocation> constants,
CreateConstantAllocations(*buffer_assignment));
TF_ASSIGN_OR_RETURN(std::vector<ConstantAllocation> constants,
CreateConstantAllocations(*buffer_assignment));

TF_ASSIGN_OR_RETURN(
cpu_executable,
Expand Down
Loading

0 comments on commit 83765d3

Please sign in to comment.