ID
stringlengths 36
36
| Language
stringclasses 1
value | Repository Name
stringclasses 13
values | File Name
stringlengths 2
44
| File Path in Repository
stringlengths 11
111
| File Path for Unit Test
stringlengths 16
116
| Code
stringlengths 0
278k
| Unit Test - (Ground Truth)
stringlengths 127
663k
| Code Url
stringlengths 91
198
| Test Code Url
stringlengths 96
203
| Commit Hash
stringclasses 13
values |
---|---|---|---|---|---|---|---|---|---|---|
0147930e-0d97-4677-8292-daa6da3d7261 | cpp | tensorflow/tensorflow | matmul_utils | third_party/xla/xla/service/gpu/matmul_utils.cc | third_party/xla/xla/service/gpu/matmul_utils_test.cc | #include "xla/service/gpu/matmul_utils.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "xla/autotuning.pb.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/primitive_util.h"
#include "xla/service/algorithm_util.h"
#include "xla/service/gpu/backend_configs.pb.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/stream_executor/blas.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/gpu/gpu_blas_lt.h"
#include "xla/stream_executor/numeric_options.h"
#include "xla/stream_executor/stream_executor.h"
#include "xla/types.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
absl::StatusOr<std::vector<int64_t>> GetNonContractingDims(
const Shape& shape, absl::Span<const int64_t> batch_dims,
absl::Span<const int64_t> contracting_dims) {
std::vector<int64_t> non_contracting_dims;
for (int64_t dim = 0; dim < shape.rank(); ++dim) {
bool is_batch = absl::c_count(batch_dims, dim) != 0;
bool is_contracting = absl::c_count(contracting_dims, dim) != 0;
TF_RET_CHECK(!(is_batch && is_contracting));
if (!(is_batch || is_contracting)) non_contracting_dims.push_back(dim);
}
TF_RET_CHECK(batch_dims.size() + contracting_dims.size() +
non_contracting_dims.size() ==
shape.rank());
return non_contracting_dims;
}
const tsl::protobuf::RepeatedField<int64_t>& BatchDimensionsForOperand(
const HloInstruction& dot, const int operand_number) {
const DotDimensionNumbers& dimension_numbers = dot.dot_dimension_numbers();
if (operand_number == 0) {
return dimension_numbers.lhs_batch_dimensions();
}
return dimension_numbers.rhs_batch_dimensions();
}
absl::StatusOr<int64_t> ContractingDimensionIndex(const HloInstruction& dot,
const int operand_number) {
const DotDimensionNumbers& dimension_numbers = dot.dot_dimension_numbers();
if (operand_number == 0) {
TF_RET_CHECK(dimension_numbers.lhs_contracting_dimensions().size() == 1);
return dimension_numbers.lhs_contracting_dimensions(0);
}
TF_RET_CHECK(dimension_numbers.rhs_contracting_dimensions().size() == 1);
return dimension_numbers.rhs_contracting_dimensions(0);
}
absl::StatusOr<int64_t> NonContractingDimensionIndex(const HloInstruction& dot,
const int operand_number) {
TF_ASSIGN_OR_RETURN(int64_t contracting_dim,
ContractingDimensionIndex(dot, operand_number));
TF_ASSIGN_OR_RETURN(
std::vector<int64_t> non_contracting_dims,
GetNonContractingDims(dot.operand(operand_number)->shape(),
BatchDimensionsForOperand(dot, operand_number),
{contracting_dim}));
TF_RET_CHECK(non_contracting_dims.size() == 1);
return non_contracting_dims.front();
}
absl::StatusOr<Shape> GetBatchRowColumnShape(
const Shape& shape, absl::Span<const int64_t> batch_dims,
absl::Span<const int64_t> row_dims, absl::Span<const int64_t> col_dims) {
TF_RET_CHECK(shape.has_layout());
std::vector<int64_t> minor_to_major;
for (size_t i = 0; i < shape.rank();) {
auto check_physically_sequential =
[&](absl::Span<const int64_t> dims) -> absl::Status {
for (auto it = dims.rbegin(); it != dims.rend(); ++it) {
if (*it != shape.layout().minor_to_major()[i++])
return InvalidArgument("dims not physically_sequential");
}
return absl::OkStatus();
};
int64_t dim = shape.layout().minor_to_major()[i];
if (!row_dims.empty() && dim == row_dims.back()) {
minor_to_major.push_back(1);
TF_RETURN_IF_ERROR(check_physically_sequential(row_dims));
} else if (!col_dims.empty() && dim == col_dims.back()) {
minor_to_major.push_back(2);
TF_RETURN_IF_ERROR(check_physically_sequential(col_dims));
} else if (!batch_dims.empty() && (dim == batch_dims.back())) {
minor_to_major.push_back(0);
TF_RETURN_IF_ERROR(check_physically_sequential(batch_dims));
} else {
return InvalidArgument("dims not physically sequential");
}
}
if (col_dims.empty()) minor_to_major.push_back(2);
if (row_dims.empty()) minor_to_major.push_back(1);
if (batch_dims.empty()) minor_to_major.push_back(0);
auto dim_size = [&](absl::Span<const int64_t> dims) {
return absl::c_accumulate(dims, 1, [&](int64_t size, int64_t dim) {
return size * shape.dimensions(dim);
});
};
return ShapeUtil::MakeShapeWithDenseLayout(
shape.element_type(),
{dim_size(batch_dims), dim_size(row_dims), dim_size(col_dims)},
minor_to_major);
}
absl::StatusOr<MatrixLayout> MatrixLayout::For(const Shape& shape) {
TF_RET_CHECK(shape.rank() == 3);
TF_RET_CHECK(shape.has_layout());
int64_t batch_size = shape.dimensions(0);
int64_t num_rows = shape.dimensions(1);
int64_t num_cols = shape.dimensions(2);
Order order{Order::kRowMajor};
int64_t leading_dim_stride = num_cols;
int64_t batch_stride = num_rows * num_cols;
absl::Span<const int64_t> minor_to_major = shape.layout().minor_to_major();
switch (64 * minor_to_major[2] + 8 * minor_to_major[1] + minor_to_major[0]) {
case 012:
break;
case 021:
order = Order::kColumnMajor;
leading_dim_stride = num_rows;
break;
case 0102:
leading_dim_stride = batch_size * num_cols;
batch_stride = num_cols;
break;
case 0201:
order = Order::kColumnMajor;
leading_dim_stride = batch_size * num_rows;
batch_stride = num_rows;
break;
default:
return Unimplemented("batch in most minor dimension");
}
if (batch_size == 1) {
batch_stride = 0;
}
return MatrixLayout{se::gpu::MatrixLayout{shape.element_type(), num_rows,
num_cols, order, batch_size,
leading_dim_stride, batch_stride}};
}
absl::StatusOr<MatrixLayout> MatrixLayout::For(
const Shape& shape, absl::Span<const int64_t> batch_dims,
absl::Span<const int64_t> row_dims, absl::Span<const int64_t> col_dims) {
TF_ASSIGN_OR_RETURN(
Shape batch_row_col_shape,
GetBatchRowColumnShape(shape, batch_dims, row_dims, col_dims));
return MatrixLayout::For(batch_row_col_shape);
}
absl::StatusOr<MatrixLayout> MatrixLayout::For(
const Shape& shape, size_t lhs_num_batch_dims, size_t lhs_num_row_dims,
size_t rhs_num_batch_dims, size_t rhs_num_col_dims) {
size_t num_batch_dims = std::max(lhs_num_batch_dims, rhs_num_batch_dims);
TF_RET_CHECK(shape.rank() ==
num_batch_dims + lhs_num_row_dims + rhs_num_col_dims);
std::vector<int64_t> dims(shape.rank());
absl::c_iota(dims, 0);
auto batch_dims = absl::Span<const int64_t>(dims).first(num_batch_dims);
auto row_dims =
absl::Span<const int64_t>(dims).subspan(num_batch_dims, lhs_num_row_dims);
auto col_dims = absl::Span<const int64_t>(dims).last(rhs_num_col_dims);
return MatrixLayout::For(shape, batch_dims, row_dims, col_dims);
}
namespace {
std::vector<int64_t> NormalizedRelativeOrder(absl::Span<const int64_t> dims) {
std::vector<int64_t> indices(dims.size());
absl::c_iota(indices, 0);
absl::c_sort(indices,
[&](int64_t a, int64_t b) { return dims[a] < dims[b]; });
return indices;
}
}
absl::StatusOr<bool> CanFoldTransposeOperandIntoDot(const HloInstruction& dot,
int64_t operand_idx) {
if (Cast<HloDotInstruction>(&dot)->sparse_operands()) {
return false;
}
TF_RET_CHECK(dot.opcode() == HloOpcode::kDot);
TF_RET_CHECK(dot.operand_count() > operand_idx);
const HloInstruction& transpose = *dot.operand(operand_idx);
TF_RET_CHECK(transpose.opcode() == HloOpcode::kTranspose);
const DotDimensionNumbers& dot_dims = dot.dot_dimension_numbers();
auto transposed = [&](const auto& dims) {
std::vector<int64_t> transposed_dims;
transposed_dims.reserve(dims.size());
for (int64_t dim : dims) {
transposed_dims.push_back(transpose.dimensions(dim));
}
return transposed_dims;
};
auto batch_dims = (operand_idx == 0) ? dot_dims.lhs_batch_dimensions()
: dot_dims.rhs_batch_dimensions();
auto contracting_dims = (operand_idx == 0)
? dot_dims.lhs_contracting_dimensions()
: dot_dims.rhs_contracting_dimensions();
TF_ASSIGN_OR_RETURN(
std::vector<int64_t> non_contracting_dims,
GetNonContractingDims(transpose.shape(), batch_dims, contracting_dims));
auto transposed_non_contracting_dims = transposed(non_contracting_dims);
if (NormalizedRelativeOrder(non_contracting_dims) !=
NormalizedRelativeOrder(transposed_non_contracting_dims)) {
return false;
}
return MatrixLayout::For(transpose.operand(0)->shape(),
transposed(batch_dims), transposed(contracting_dims),
transposed_non_contracting_dims)
.ok();
}
absl::StatusOr<GemmConfig> GemmConfig::For(
const Shape& lhs_shape, absl::Span<const int64_t> lhs_batch_dims,
absl::Span<const int64_t> lhs_contracting_dims, const Shape& rhs_shape,
absl::Span<const int64_t> rhs_batch_dims,
absl::Span<const int64_t> rhs_contracting_dims, const Shape& output_shape,
double alpha_real, double alpha_imag, double beta,
PrecisionConfig::Algorithm precision_algorithm,
std::optional<int64_t> algorithm, int64_t compute_precision, bool grad_x,
bool grad_y) {
return GemmConfig::For(lhs_shape, lhs_batch_dims, lhs_contracting_dims,
rhs_shape, rhs_batch_dims, rhs_contracting_dims,
output_shape, nullptr,
output_shape, alpha_real, alpha_imag, beta,
precision_algorithm, algorithm, compute_precision,
grad_x, grad_y);
}
absl::StatusOr<GemmConfig> GemmConfig::For(
const Shape& lhs_shape, absl::Span<const int64_t> lhs_batch_dims,
absl::Span<const int64_t> lhs_contracting_dims, const Shape& rhs_shape,
absl::Span<const int64_t> rhs_batch_dims,
absl::Span<const int64_t> rhs_contracting_dims, const Shape& c_shape,
const Shape* bias_shape_ptr, const Shape& output_shape, double alpha_real,
double alpha_imag, double beta,
PrecisionConfig::Algorithm precision_algorithm,
std::optional<int64_t> algorithm, int64_t compute_precision, bool grad_x,
bool grad_y) {
absl::Span<const int64_t> lhs_col_dims = lhs_contracting_dims;
TF_ASSIGN_OR_RETURN(
std::vector<int64_t> lhs_row_dims,
GetNonContractingDims(lhs_shape, lhs_batch_dims, lhs_col_dims));
TF_ASSIGN_OR_RETURN(
MatrixLayout lhs_layout,
MatrixLayout::For(lhs_shape, lhs_batch_dims, lhs_row_dims, lhs_col_dims));
absl::Span<const int64_t> rhs_row_dims = rhs_contracting_dims;
TF_ASSIGN_OR_RETURN(
std::vector<int64_t> rhs_col_dims,
GetNonContractingDims(rhs_shape, rhs_batch_dims, rhs_row_dims));
TF_ASSIGN_OR_RETURN(
MatrixLayout rhs_layout,
MatrixLayout::For(rhs_shape, rhs_batch_dims, rhs_row_dims, rhs_col_dims));
int64_t num_batch_dims =
std::max(lhs_batch_dims.size(), rhs_batch_dims.size());
TF_RET_CHECK(output_shape.rank() ==
num_batch_dims + lhs_row_dims.size() + rhs_col_dims.size());
std::vector<int64_t> output_dims(output_shape.rank());
absl::c_iota(output_dims, 0);
auto output_batch_dims =
absl::Span<const int64_t>(output_dims).first(num_batch_dims);
auto output_row_dims = absl::Span<const int64_t>(output_dims)
.subspan(num_batch_dims, lhs_row_dims.size());
auto output_col_dims =
absl::Span<const int64_t>(output_dims).last(rhs_col_dims.size());
TF_ASSIGN_OR_RETURN(MatrixLayout output_layout,
MatrixLayout::For(output_shape, output_batch_dims,
output_row_dims, output_col_dims));
Shape c_matrix_shape = c_shape;
if (primitive_util::IsF8Type(lhs_shape.element_type()) &&
primitive_util::IsF8Type(output_shape.element_type()) && beta == 0.0) {
#if GOOGLE_CUDA
c_matrix_shape.set_element_type(
bias_shape_ptr != nullptr ? bias_shape_ptr->element_type() : BF16);
#endif
}
TF_ASSIGN_OR_RETURN(MatrixLayout c_layout,
MatrixLayout::For(c_matrix_shape, output_batch_dims,
output_row_dims, output_col_dims));
if (lhs_shape.element_type() != F8E4M3FN &&
lhs_shape.element_type() != F8E5M2) {
TF_RET_CHECK(lhs_layout.num_cols == rhs_layout.num_rows);
TF_RET_CHECK(output_layout.num_rows == lhs_layout.num_rows);
TF_RET_CHECK(output_layout.num_cols == rhs_layout.num_cols);
}
TF_RET_CHECK(c_layout.num_rows == output_layout.num_rows);
TF_RET_CHECK(c_layout.num_cols == output_layout.num_cols);
TF_RET_CHECK((lhs_layout.batch_size == output_layout.batch_size) ||
(lhs_layout.batch_size == 1));
TF_RET_CHECK((rhs_layout.batch_size == output_layout.batch_size) ||
(rhs_layout.batch_size == 1));
switch (output_shape.element_type()) {
case F8E4M3FN:
case F8E5M2:
case F8E4M3FNUZ:
case F8E5M2FNUZ:
case F16:
case BF16:
case F32:
case F64:
TF_RET_CHECK(alpha_imag == 0);
break;
case C64:
case C128:
break;
case S32:
TF_RET_CHECK(alpha_imag == 0);
if (lhs_layout.dtype != PrimitiveType::S8 ||
rhs_layout.dtype != PrimitiveType::S8) {
return Internal(
"For int32 gemm output only int8 input is supported, got input: "
"%s, %s",
primitive_util::LowercasePrimitiveTypeName(lhs_layout.dtype),
primitive_util::LowercasePrimitiveTypeName(rhs_layout.dtype));
}
break;
default:
return Internal("Unexpected GEMM datatype: %s",
primitive_util::LowercasePrimitiveTypeName(
output_shape.element_type()));
}
return GemmConfig{lhs_layout,
rhs_layout,
c_layout,
output_layout,
{alpha_real, alpha_imag},
beta,
compute_precision,
precision_algorithm,
algorithm,
grad_x,
grad_y};
}
namespace {
bool IsTf32Allowed(PrecisionConfig::Algorithm algorithm,
int64_t compute_precision) {
if (algorithm == PrecisionConfig::ALG_UNSET) {
return compute_precision <= 1;
}
return algorithm_util::HasTf32InputType(algorithm);
}
}
absl::StatusOr<GemmConfig> GemmConfig::For(
const HloInstruction* gemm) {
TF_ASSIGN_OR_RETURN(GpuBackendConfig gpu_config,
gemm->backend_config<GpuBackendConfig>());
return For(gemm, gpu_config.gemm_backend_config());
}
absl::StatusOr<GemmConfig> GemmConfig::For(
const HloInstruction* gemm, const GemmBackendConfig& config) {
std::optional<int64_t> algorithm;
if (config.algorithm_case() != GemmBackendConfig::ALGORITHM_NOT_SET) {
algorithm = config.selected_algorithm();
} else {
algorithm = se::blas::kDefaultAlgorithm;
}
const Shape& lhs_shape = gemm->operand(0)->shape();
const Shape& rhs_shape = gemm->operand(1)->shape();
const DotDimensionNumbers& dot_dims = config.dot_dimension_numbers();
const Shape& output_shape =
gemm->shape().IsTuple() ? gemm->shape().tuple_shapes(0) : gemm->shape();
bool has_matrix_bias = config.beta() != 0.;
Shape c_shape = has_matrix_bias ? gemm->operand(2)->shape() : output_shape;
std::optional<Shape> vector_bias_shape;
TF_ASSIGN_OR_RETURN(
bool has_vector_bias,
xla::gpu::gpublas_lt::EpilogueAddsVectorBias(config.epilogue()));
if (has_vector_bias) {
int vector_bias_index = has_matrix_bias ? 3 : 2;
if (primitive_util::IsF8Type(lhs_shape.element_type())) {
vector_bias_index += 2;
}
vector_bias_shape = gemm->operand(vector_bias_index)->shape();
}
auto attributes = gemm->frontend_attributes().map();
bool grad_x = (attributes["grad_x"] == "true");
bool grad_y = (attributes["grad_y"] == "true");
int64_t precision = se::blas::kDefaultComputePrecision;
for (auto operand_precision : config.precision_config().operand_precision()) {
precision = std::max(precision, static_cast<int64_t>(operand_precision));
}
const PrecisionConfig::Algorithm precision_algorithm =
config.precision_config().algorithm();
return GemmConfig::For(
lhs_shape, dot_dims.lhs_batch_dimensions(),
dot_dims.lhs_contracting_dimensions(), rhs_shape,
dot_dims.rhs_batch_dimensions(), dot_dims.rhs_contracting_dimensions(),
c_shape,
vector_bias_shape ? &vector_bias_shape.value() : nullptr, output_shape,
config.alpha_real(), config.alpha_imag(), config.beta(),
precision_algorithm, algorithm, precision, grad_x, grad_y);
}
absl::StatusOr<GemmConfig::DescriptorsTuple> GemmConfig::GetMatrixDescriptors(
se::DeviceMemoryBase lhs_buf, se::DeviceMemoryBase rhs_buf,
se::DeviceMemoryBase out_buf) const {
auto create_matrix_desc = [](const se::gpu::MatrixLayout& layout,
se::DeviceMemoryBase data)
-> absl::StatusOr<se::gpu::MatrixDescriptor> {
TF_ASSIGN_OR_RETURN(se::blas::DataType type,
se::gpu::AsBlasDataType(layout.dtype));
return se::gpu::MatrixDescriptor{
data, layout.leading_dim_stride, layout.batch_stride, type,
(layout.order == se::gpu::MatrixLayout::Order::kColumnMajor
? se::blas::Transpose::kNoTranspose
: se::blas::Transpose::kTranspose)};
};
se::gpu::MatrixLayout lhs = lhs_layout, rhs = rhs_layout, out = output_layout;
bool must_swap_operands = MakeOutputColumnMajor(lhs, rhs, out);
if (must_swap_operands) {
std::swap(lhs_buf, rhs_buf);
}
TF_ASSIGN_OR_RETURN(se::gpu::OutputMatrixDescriptor out_desc,
create_matrix_desc(out, out_buf));
out_desc.batch_size = out.batch_size;
out_desc.m = out.num_rows;
out_desc.n = out.num_cols;
out_desc.k = lhs.num_cols;
TF_ASSIGN_OR_RETURN(out_desc.compute_type,
se::gpu::GetBlasComputationType(
PrecisionConfig::ALG_UNSET, lhs.dtype, out.dtype,
se::blas::kDefaultComputePrecision));
TF_ASSIGN_OR_RETURN(se::gpu::MatrixDescriptor lhs_desc,
create_matrix_desc(lhs, lhs_buf));
TF_ASSIGN_OR_RETURN(se::gpu::MatrixDescriptor rhs_desc,
create_matrix_desc(rhs, rhs_buf));
return DescriptorsTuple{lhs_desc, rhs_desc, out_desc, must_swap_operands};
}
namespace {
template <typename Scale, typename Input, typename Output>
absl::Status DoGemmWithAlgorithm(const se::gpu::MatrixDescriptor& lhs,
const se::gpu::MatrixDescriptor& rhs,
const se::gpu::OutputMatrixDescriptor& output,
se::DeviceMemoryBase workspace, Scale alpha,
Scale beta, se::Stream* stream,
PrecisionConfig::Algorithm precision_algorithm,
se::blas::AlgorithmType algorithm,
se::blas::ComputePrecision compute_precision,
const se::NumericOptions& numeric_options,
se::blas::ProfileResult* profile_result,
se::blas::CallContext context) {
CHECK(output.transpose == se::blas::Transpose::kNoTranspose);
PrimitiveType lhs_type = primitive_util::NativeToPrimitiveType<Input>();
PrimitiveType output_type = primitive_util::NativeToPrimitiveType<Output>();
TF_ASSIGN_OR_RETURN(
se::blas::ComputationType computation_type,
se::gpu::GetBlasComputationType(precision_algorithm, lhs_type,
output_type, compute_precision));
se::DeviceMemory<Output> output_data(output.data);
auto* blas = stream->parent()->AsBlas();
if (blas == nullptr) {
return absl::InternalError("No Blas support for stream");
}
se::blas::BlasSupport::ScopedWorkspace scoped_workspace(blas, &workspace);
if (output.batch_size != 1) {
return blas->BlasGemmStridedBatchedWithAlgorithm(
stream, lhs.transpose, rhs.transpose, output.m, output.n, output.k,
alpha, lhs.cast<Input>(), lhs.leading_dim_stride, lhs.batch_stride,
rhs.cast<Input>(), rhs.leading_dim_stride, rhs.batch_stride, beta,
&output_data, output.leading_dim_stride, output.batch_stride,
output.batch_size, computation_type, algorithm, numeric_options,
profile_result, context);
} else {
return blas->BlasGemmWithAlgorithm(
stream, lhs.transpose, rhs.transpose, output.m, output.n, output.k,
alpha, lhs.cast<Input>(), lhs.leading_dim_stride, rhs.cast<Input>(),
rhs.leading_dim_stride, beta, &output_data, output.leading_dim_stride,
computation_type, algorithm, numeric_options, profile_result, context);
}
}
template <typename Scale, typename Input, typename Output>
absl::Status DoGemm(const se::gpu::MatrixDescriptor& lhs,
const se::gpu::MatrixDescriptor& rhs,
const se::gpu::OutputMatrixDescriptor& output,
se::DeviceMemoryBase workspace, Scale alpha, Scale beta,
se::Stream* stream,
PrecisionConfig::Algorithm precision_algorithm,
std::optional<se::blas::AlgorithmType> algorithm,
se::blas::ComputePrecision compute_precision,
const se::NumericOptions& numeric_options,
se::blas::ProfileResult* profile_result,
se::blas::CallContext context) {
CHECK(output.transpose == se::blas::Transpose::kNoTranspose);
se::DeviceMemory<Output> output_data(output.data);
auto* blas = stream->parent()->AsBlas();
if (blas == nullptr) {
return absl::InternalError("No Blas support for stream");
}
if (algorithm) {
return DoGemmWithAlgorithm<Scale, Input, Output>(
lhs, rhs, output, workspace, alpha, beta, stream, precision_algorithm,
*algorithm, compute_precision, numeric_options, profile_result,
context);
}
se::blas::BlasSupport::ScopedWorkspace scoped_workspace(blas, &workspace);
if (output.batch_size != 1) {
return blas->BlasGemmStridedBatched(
stream, lhs.transpose, rhs.transpose, output.m, output.n, output.k,
alpha, lhs.cast<Input>(), lhs.leading_dim_stride, lhs.batch_stride,
rhs.cast<Input>(), rhs.leading_dim_stride, rhs.batch_stride, beta,
&output_data, output.leading_dim_stride, output.batch_stride,
output.batch_size, numeric_options, context);
}
return blas->BlasGemm(stream, lhs.transpose, rhs.transpose, output.m,
output.n, output.k, alpha, lhs.cast<Input>(),
lhs.leading_dim_stride, rhs.cast<Input>(),
rhs.leading_dim_stride, beta, &output_data,
output.leading_dim_stride, numeric_options, context);
}
}
absl::Status RunGemm(const GemmConfig& config, se::DeviceMemoryBase lhs_buffer,
se::DeviceMemoryBase rhs_buffer,
se::DeviceMemoryBase output_buffer,
se::DeviceMemoryBase workspace_buffer,
bool deterministic_ops, se::Stream* stream,
std::optional<se::blas::AlgorithmType> algorithm,
se::blas::ProfileResult* profile_result) {
VLOG(2) << "Executing a GemmThunk";
TF_ASSIGN_OR_RETURN(
GemmConfig::DescriptorsTuple desc,
config.GetMatrixDescriptors(lhs_buffer, rhs_buffer, output_buffer));
se::NumericOptions numeric_options{
deterministic_ops,
IsTf32Allowed(config.precision_algorithm,
config.compute_precision)};
if (!algorithm) algorithm = config.algorithm;
se::blas::CallContext context = se::blas::CallContext::kNone;
if (config.grad_x) {
context = desc.operands_swapped ? se::blas::CallContext::kBackpropInput2
: se::blas::CallContext::kBackpropInput1;
}
if (config.grad_y) {
context = desc.operands_swapped ? se::blas::CallContext::kBackpropInput1
: se::blas::CallContext::kBackpropInput2;
}
std::tuple operand_types{config.lhs_layout.dtype, config.rhs_layout.dtype,
config.output_layout.dtype};
if (config.alpha.real() == 0.0 && config.alpha.imag() == 0.0 &&
config.beta == 0.0) {
return stream->MemZero(&output_buffer, output_buffer.size());
}
#define TYPED_GEMM(SCALENTYPE, ATYPE, BTYPE, CTYPE) \
if (operand_types == std::make_tuple(ATYPE, BTYPE, CTYPE)) { \
using NativeScaleType = \
primitive_util::PrimitiveTypeToNative<SCALENTYPE>::type; \
using NativeAType = primitive_util::PrimitiveTypeToNative<ATYPE>::type; \
using NativeCType = primitive_util::PrimitiveTypeToNative<CTYPE>::type; \
return DoGemm<NativeScaleType, NativeAType, NativeCType>( \
desc.lhs, desc.rhs, desc.output, workspace_buffer, \
static_cast<NativeScaleType>(config.alpha.real()), \
static_cast<NativeScaleType>(config.beta), stream, \
config.precision_algorithm, algorithm, config.compute_precision, \
numeric_options, profile_result, context); \
}
#define TYPED_GEMM_COMPLEX(SCALENTYPE, ATYPE, BTYPE, CTYPE) \
if (operand_types == std::make_tuple(ATYPE, BTYPE, CTYPE)) { \
using NativeScaleType = \
primitive_util::PrimitiveTypeToNative<SCALENTYPE>::type; \
using NativeAType = primitive_util::PrimitiveTypeToNative<ATYPE>::type; \
using NativeCType = primitive_util::PrimitiveTypeToNative<CTYPE>::type; \
return DoGemm<NativeScaleType, NativeAType, NativeCType>( \
desc.lhs, desc.rhs, desc.output, workspace_buffer, \
static_cast<NativeScaleType>(config.alpha), \
static_cast<NativeScaleType>(config.beta), stream, \
config.precision_algorithm, algorithm, config.compute_precision, \
numeric_options, profile_result, context); \
}
if (config.output_layout.dtype == S32) {
if (!algorithm) algorithm = se::blas::kDefaultGemmAlgo;
return DoGemmWithAlgorithm<int32_t, int8_t, int32_t>(
desc.lhs, desc.rhs, desc.output, workspace_buffer,
static_cast<int32_t>(config.alpha.real()),
static_cast<int32_t>(config.beta), stream, PrecisionConfig::ALG_UNSET,
*algorithm, se::blas::kDefaultComputePrecision, numeric_options,
profile_result, context);
}
TYPED_GEMM(F32, BF16, BF16, BF16)
TYPED_GEMM(F32, F16, F16, F16)
TYPED_GEMM(F32, S8, S8, F32)
TYPED_GEMM(F32, BF16, BF16, F32)
TYPED_GEMM(F32, F16, F16, F32)
TYPED_GEMM(F32, F32, F32, F32)
TYPED_GEMM(F64, F64, F64, F64)
TYPED_GEMM_COMPLEX(C64, C64, C64, C64)
TYPED_GEMM_COMPLEX(C128, C128, C128, C128)
#undef TYPED_GEMM
#undef TYPED_GEMM_COMPLEX
return Internal(
"Unexpected GEMM dtype: %s %s %s",
primitive_util::LowercasePrimitiveTypeName(config.lhs_layout.dtype),
primitive_util::LowercasePrimitiveTypeName(config.rhs_layout.dtype),
primitive_util::LowercasePrimitiveTypeName(config.output_layout.dtype));
}
namespace gpublas_lt {
absl::StatusOr<bool> EpilogueAddsVectorBias(
GemmBackendConfig_Epilogue epilogue) {
switch (epilogue) {
case GemmBackendConfig::DEFAULT:
case GemmBackendConfig::RELU:
case GemmBackendConfig::GELU:
case GemmBackendConfig::GELU_AUX:
return false;
case GemmBackendConfig::BIAS:
case GemmBackendConfig::BIAS_RELU:
case GemmBackendConfig::BIAS_GELU:
case GemmBackendConfig::BIAS_GELU_AUX:
return true;
default:
return Internal("Unknown Epilogue.");
}
}
absl::StatusOr<bool> EpilogueHasAuxiliaryOutput(
GemmBackendConfig_Epilogue epilogue) {
switch (epilogue) {
case GemmBackendConfig::DEFAULT:
case GemmBackendConfig::RELU:
case GemmBackendConfig::GELU:
case GemmBackendConfig::BIAS:
case GemmBackendConfig::BIAS_RELU:
case GemmBackendConfig::BIAS_GELU:
return false;
case GemmBackendConfig::GELU_AUX:
case GemmBackendConfig::BIAS_GELU_AUX:
return true;
default:
return Internal("Unknown Epilogue.");
}
}
absl::StatusOr<se::gpu::BlasLt::Epilogue> AsBlasLtEpilogue(
GemmBackendConfig_Epilogue epilogue) {
switch (epilogue) {
case GemmBackendConfig::DEFAULT:
return se::gpu::BlasLt::Epilogue::kDefault;
case GemmBackendConfig::RELU:
return se::gpu::BlasLt::Epilogue::kReLU;
case GemmBackendConfig::GELU:
return se::gpu::BlasLt::Epilogue::kGELU;
case GemmBackendConfig::GELU_AUX:
return se::gpu::BlasLt::Epilogue::kGELUWithAux;
case GemmBackendConfig::BIAS:
return se::gpu::BlasLt::Epilogue::kBias;
case GemmBackendConfig::BIAS_RELU:
return se::gpu::BlasLt::Epilogue::kBiasThenReLU;
case GemmBackendConfig::BIAS_GELU:
return se::gpu::BlasLt::Epilogue::kBiasThenGELU;
case GemmBackendConfig::BIAS_GELU_AUX:
return se::gpu::BlasLt::Epilogue::kBiasThenGELUWithAux;
default:
return Internal("unexpected epilogue value");
}
}
}
absl::StatusOr<TritonGemmConfig> TritonGemmConfig::FromProto(
const AutotuneResult::TritonGemmKey& proto) {
TF_RET_CHECK(proto.block_m() > 0);
TF_RET_CHECK(proto.block_n() > 0);
TF_RET_CHECK(proto.block_k() > 0);
TF_RET_CHECK(proto.split_k() > 0);
TF_RET_CHECK(proto.num_stages() > 0);
TF_RET_CHECK(proto.num_warps() > 0);
TF_RET_CHECK(proto.num_ctas() > 0);
return TritonGemmConfig(proto.block_m(), proto.block_n(), proto.block_k(),
proto.split_k(), proto.num_stages(),
proto.num_warps(), proto.num_ctas());
}
AutotuneResult::TritonGemmKey TritonGemmConfig::ToProto() const {
AutotuneResult::TritonGemmKey key;
key.set_block_m(block_m);
key.set_block_n(block_n);
key.set_block_k(block_k);
key.set_split_k(split_k);
key.set_num_stages(num_stages);
key.set_num_warps(num_warps);
key.set_num_ctas(num_ctas);
return key;
}
std::string TritonGemmConfig::ToString() const {
return absl::StrCat("{block_m:", block_m, ",block_n:", block_n,
",block_k:", block_k, ",split_k:", split_k,
",num_stages:", num_stages, ",num_warps:", num_warps,
",num_ctas:", num_ctas, "}");
}
absl::StatusOr<bool> IsMatrixMultiplicationTooSmallForRewriting(
const HloInstruction& dot, int64_t threshold) {
CHECK_EQ(dot.opcode(), HloOpcode::kDot);
const Shape& lhs_shape = dot.operand(0)->shape();
const Shape& rhs_shape = dot.operand(1)->shape();
const DotDimensionNumbers& dot_dims = dot.dot_dimension_numbers();
int64_t contracting_size = 1;
for (int64_t dim : dot_dims.lhs_contracting_dimensions()) {
contracting_size *= lhs_shape.dimensions(dim);
}
TF_ASSIGN_OR_RETURN(
std::vector<int64_t> lhs_non_contracting_dims,
GetNonContractingDims(lhs_shape, dot_dims.lhs_batch_dimensions(),
dot_dims.lhs_contracting_dimensions()));
int64_t lhs_non_contracting_size = 1;
for (int64_t dim : lhs_non_contracting_dims) {
lhs_non_contracting_size *= lhs_shape.dimensions(dim);
}
TF_ASSIGN_OR_RETURN(
std::vector<int64_t> rhs_non_contracting_dims,
GetNonContractingDims(rhs_shape, dot_dims.rhs_batch_dimensions(),
dot_dims.rhs_contracting_dimensions()));
int64_t rhs_non_contracting_size = 1;
for (int64_t dim : rhs_non_contracting_dims) {
rhs_non_contracting_size *= rhs_shape.dimensions(dim);
}
return (rhs_non_contracting_size + lhs_non_contracting_size) *
contracting_size <
threshold;
}
bool IsDotSupportedByClassicalEmitters(const HloInstruction& dot) {
if (!algorithm_util::IsSupportedByElementalIrEmitter(
dot.precision_config().algorithm())) {
return false;
}
switch (dot.shape().element_type()) {
case F16:
case F32:
case BF16:
return true;
default:
return false;
}
}
}
} | #include "xla/service/gpu/matmul_utils.h"
#include <cstdint>
#include <memory>
#include <vector>
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/hlo_parser.h"
#include "xla/shape.h"
#include "xla/test.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
namespace {
using ::testing::ElementsAre;
using ::tsl::testing::IsOkAndHolds;
TEST(GetNonContractingDimsTest, Valid) {
Shape shape = ParseShape("f32[1,2,3,4,5,6]").value();
EXPECT_THAT(GetNonContractingDims(shape, {4},
{1, 5}),
IsOkAndHolds(ElementsAre(0, 2, 3)));
}
using CanFoldTransposeOperandIntoDotTest = HloTestBase;
TEST_F(CanFoldTransposeOperandIntoDotTest, ArgTransposeFoldGemm) {
const char* hlo_text = R"(
HloModule ArgTransposeFoldGemm
ENTRY AddDotsFunc {
x = f32[3,2] parameter(0)
y = f32[3,4] parameter(1)
x_transposed = f32[2,3] transpose(x), dimensions={1, 0}
ROOT dot_a = f32[2,4] dot(x_transposed, y), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(CanFoldTransposeOperandIntoDot(*dot, 0), IsOkAndHolds(true));
}
TEST_F(CanFoldTransposeOperandIntoDotTest, BatchedArgRowColTransposeFoldGemm) {
const char* hlo_text = R"(
HloModule BatchedArgRowColTransposeFoldGemm
ENTRY AddDotsFunc {
x = f32[5,3,2] parameter(0)
y = f32[5,3,4] parameter(1)
x_transposed = f32[5,2,3] transpose(x), dimensions={0, 2, 1}
ROOT dot_a = f32[5,2,4] dot(x_transposed, y), lhs_contracting_dims={2}, rhs_contracting_dims={1}, lhs_batch_dims={0}, rhs_batch_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(CanFoldTransposeOperandIntoDot(*dot, 0), IsOkAndHolds(true));
}
TEST_F(CanFoldTransposeOperandIntoDotTest, BatchRowTransposeFoldGemm) {
const char* hlo_text = R"(
HloModule BatchRowTransposeFoldCheck
ENTRY AddDotsFunc {
x = f32[2,5,3] parameter(0)
y = f32[5,3,4] parameter(1)
x_transposed = f32[5,2,3] transpose(x), dimensions={1, 0, 2}
ROOT dot_a = f32[5,2,4] dot(x_transposed, y), lhs_contracting_dims={2}, rhs_contracting_dims={1}, lhs_batch_dims={0}, rhs_batch_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(CanFoldTransposeOperandIntoDot(*dot, 0), IsOkAndHolds(true));
}
TEST_F(CanFoldTransposeOperandIntoDotTest,
BatchFromMinorDimTransposeDoesntFold) {
const char* hlo_text = R"(
HloModule BatchFromMinorDimTransposeDoesntFold
ENTRY AddDotsFunc {
x = f32[3,2,5] parameter(0)
y = f32[5,3,4] parameter(1)
x_transposed = f32[5,2,3] transpose(x), dimensions={2, 1, 0}
ROOT dot_a = f32[5,2,4] dot(x_transposed, y), lhs_contracting_dims={2}, rhs_contracting_dims={1}, lhs_batch_dims={0}, rhs_batch_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(CanFoldTransposeOperandIntoDot(*dot, 0), IsOkAndHolds(false));
}
TEST_F(CanFoldTransposeOperandIntoDotTest,
TransposedNonContractingDimsDontFold) {
const char* hlo_text = R"(
HloModule TransposedNonContractingDimsDontFold
ENTRY AddDotsFunc {
x = f32[5,3,4]{2,1,0} parameter(1)
y = f32[5,2,6,3]{3,1,2,0} parameter(0)
y_transposed = f32[5,6,2,3]{3,2,1,0} transpose(y), dimensions={0, 2, 1, 3}
ROOT dot_a = f32[5,4,6,2]{3,2,1,0} dot(x, y_transposed), lhs_contracting_dims={1}, rhs_contracting_dims={3}, lhs_batch_dims={0}, rhs_batch_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(CanFoldTransposeOperandIntoDot(*dot, 1), IsOkAndHolds(false));
}
struct GetBatchRowColumnShapeTestParams {
absl::string_view shape;
std::vector<int64_t> batch_dims;
std::vector<int64_t> row_dims;
std::vector<int64_t> col_dims;
absl::string_view expected_shape;
};
using GetBatchRowColumnShapeTest =
::testing::TestWithParam<GetBatchRowColumnShapeTestParams>;
TEST_P(GetBatchRowColumnShapeTest, ValidShape) {
const GetBatchRowColumnShapeTestParams& params = GetParam();
Shape shape = ParseShape(params.shape).value();
EXPECT_THAT(GetBatchRowColumnShape(shape, params.batch_dims, params.row_dims,
params.col_dims),
IsOkAndHolds(ParseShape(params.expected_shape).value()));
}
INSTANTIATE_TEST_SUITE_P(
GetBatchRowColumnShapeTests, GetBatchRowColumnShapeTest,
::testing::ValuesIn<GetBatchRowColumnShapeTestParams>({
{"f32[3,4]{1,0}", {}, {0}, {1},
"f32[1,3,4]{2,1,0}"},
{"f32[3,4]{0,1}", {}, {0}, {1}, "f32[1,3,4]{1,2,0}"},
{"f32[3,4]{1,0}", {}, {1}, {0}, "f32[1,4,3]{1,2,0}"},
{"f32[3,4,5]{2,1,0}", {0}, {1}, {2}, "f32[3,4,5]{2,1,0}"},
{"f32[3,4,5]{2,1,0}", {2}, {1}, {0}, "f32[5,4,3]{0,1,2}"},
{"f32[3,4,5,6,7,8]{5,2,4,1,3,0}",
{0, 3},
{1, 4},
{2, 5},
"f32[18,28,40]{2,1,0}"},
}));
TEST(GetBatchRowColumnShapeTest, BatchRowsColsInterleaved) {
Shape shape = ParseShape("f32[3,4,5,6,7,8]{5,4,3,2,1,0}").value();
auto result =
GetBatchRowColumnShape(shape, {0, 3},
{1, 4}, {2, 5});
EXPECT_FALSE(result.ok());
}
TEST(GetBatchRowColumnShapeTest, WrongPhysicalOrder) {
Shape shape = ParseShape("f32[3,4,5,6]{3,2,0,1}").value();
auto result = GetBatchRowColumnShape(shape, {0, 1},
{2}, {3});
EXPECT_FALSE(result.ok());
}
using Order = MatrixLayout::Order;
struct GetMatrixLayoutTestParams {
absl::string_view shape;
int64_t batch_size;
int64_t num_rows;
int64_t num_cols;
Order order;
int64_t leading_dim_stride;
int64_t batch_stride;
};
using GetMatrixLayoutTest = ::testing::TestWithParam<GetMatrixLayoutTestParams>;
TEST_P(GetMatrixLayoutTest, ValidShape) {
const GetMatrixLayoutTestParams& params = GetParam();
Shape shape = ParseShape(params.shape).value();
MatrixLayout result = MatrixLayout::For(shape).value();
EXPECT_EQ(result.batch_size, params.batch_size);
EXPECT_EQ(result.num_rows, params.num_rows);
EXPECT_EQ(result.num_cols, params.num_cols);
EXPECT_EQ(result.order, params.order);
EXPECT_EQ(result.leading_dim_stride, params.leading_dim_stride);
EXPECT_EQ(result.batch_stride, params.batch_stride);
}
INSTANTIATE_TEST_SUITE_P(
GetMatrixLayoutTests, GetMatrixLayoutTest,
::testing::ValuesIn<GetMatrixLayoutTestParams>({
{"f32[3,4,5]{2,1,0}", 3, 4, 5,
Order::kRowMajor, 5,
20},
{"f32[3,4,5]{1,2,0}", 3, 4, 5, Order::kColumnMajor, 4, 20},
{"f32[3,4,5]{2,0,1}", 3, 4, 5, Order::kRowMajor, 15, 5},
{"f32[3,4,5]{1,0,2}", 3, 4, 5, Order::kColumnMajor, 12, 4},
}));
TEST(GetMatrixLayoutTest, BatchInMostMinorPhysicalDimension) {
Shape shape = ParseShape("f32[3,4,5]{0,2,1}").value();
EXPECT_FALSE(MatrixLayout::For(shape).ok());
}
using GetMatrixSizeRewriteThresholdTest = HloTestBase;
TEST_F(GetMatrixSizeRewriteThresholdTest, MatMulTooSmallForRewrite) {
const char* hlo_text = R"(
HloModule DotFuncModule
ENTRY DotFunc {
x = f32[100,30,3] parameter(0)
y = f32[100,3,3] parameter(1)
ROOT dot = f32[100,30,3] dot(x, y), lhs_contracting_dims={2}, rhs_contracting_dims={1}, lhs_batch_dims={0}, rhs_batch_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(IsMatrixMultiplicationTooSmallForRewriting(*dot, 100),
IsOkAndHolds(true));
}
TEST_F(GetMatrixSizeRewriteThresholdTest, MatMulSupportedByClassicalEmitters) {
const char* hlo_text = R"(
HloModule DotFuncModule
ENTRY DotFunc {
x = f32[100,30,3] parameter(0)
y = f32[100,3,3] parameter(1)
ROOT dot = f32[100,30,3] dot(x, y), lhs_contracting_dims={2}, rhs_contracting_dims={1}, lhs_batch_dims={0}, rhs_batch_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_TRUE(IsDotSupportedByClassicalEmitters(*dot));
}
TEST_F(GetMatrixSizeRewriteThresholdTest,
MatMulUnsupportedByClassicalEmitters) {
const char* hlo_text = R"(
HloModule DotFuncModule
ENTRY DotFunc {
x = s8[100,30,3] parameter(0)
y = s8[100,3,3] parameter(1)
ROOT dot = s32[100,30,3] dot(x, y), lhs_contracting_dims={2}, rhs_contracting_dims={1}, lhs_batch_dims={0}, rhs_batch_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_FALSE(IsDotSupportedByClassicalEmitters(*dot));
}
TEST_F(GetMatrixSizeRewriteThresholdTest, MatMulLeftLargeEnoughForRewrite) {
const char* hlo_text = R"(
HloModule DotFuncModule
ENTRY DotFunc {
x = f32[50,2] parameter(0)
y = f32[2,2] parameter(1)
ROOT dot = f32[50,2] dot(x, y), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(IsMatrixMultiplicationTooSmallForRewriting(*dot, 100),
IsOkAndHolds(false));
}
TEST_F(GetMatrixSizeRewriteThresholdTest, MatMulRightLargeEnoughForRewrite) {
const char* hlo_text = R"(
HloModule DotFuncModule
ENTRY DotFunc {
x = f32[2,2] parameter(0)
y = f32[2,50] parameter(1)
ROOT dot = f32[2,50] dot(x, y), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(IsMatrixMultiplicationTooSmallForRewriting(*dot, 100),
IsOkAndHolds(false));
}
TEST_F(GetMatrixSizeRewriteThresholdTest, MatMulTogetherLargeEnoughForRewrite) {
const char* hlo_text = R"(
HloModule DotFuncModule
ENTRY DotFunc {
x = f32[4,16] parameter(0)
y = f32[16,4] parameter(1)
ROOT dot = f32[4,4] dot(x, y), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_text));
auto dot = module->entry_computation()->root_instruction();
EXPECT_THAT(IsMatrixMultiplicationTooSmallForRewriting(*dot, 100),
IsOkAndHolds(false));
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/matmul_utils.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/matmul_utils_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
c06ee53d-22e7-4329-98c3-c4268f794d6d | cpp | tensorflow/tensorflow | resize_area_op | tensorflow/core/kernels/image/resize_area_op.cc | tensorflow/core/kernels/image/resize_area_op_test.cc | #define EIGEN_USE_THREADS
#include <algorithm>
#include <memory>
#include "unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/image_resizer_state.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
namespace {
struct CachedInterpolation {
int64_t start;
int64_t end;
float start_scale;
float end_minus_one_scale;
bool needs_bounding;
};
}
template <typename Device, typename T>
class ResizeAreaOp : public OpKernel {
public:
explicit ResizeAreaOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("align_corners", &align_corners_));
}
template <bool NeedsXBounding>
static void ComputePatchSumOf3Channels(float scale,
const ImageResizerState& st,
const std::vector<const T*>& y_ptrs,
const std::vector<float>& y_scales,
const CachedInterpolation& x_interp,
float* output_ptr) {
#define BOUND_IF_NEEDED(x, y) (NeedsXBounding ? Bound(x, y) : (x))
float sum_0 = 0;
float sum_1 = 0;
float sum_2 = 0;
for (int i = 0; i < y_ptrs.size(); ++i) {
const T* ptr = y_ptrs[i];
float scale_x = x_interp.start_scale;
int64_t offset = 3 * BOUND_IF_NEEDED(x_interp.start, st.in_width);
float sum_y_0 = static_cast<float>(ptr[offset + 0]) * scale_x;
float sum_y_1 = static_cast<float>(ptr[offset + 1]) * scale_x;
float sum_y_2 = static_cast<float>(ptr[offset + 2]) * scale_x;
if (x_interp.start + 1 != x_interp.end) {
for (int64_t x = x_interp.start + 1; x < x_interp.end - 1; ++x) {
int64_t offset = 3 * BOUND_IF_NEEDED(x, st.in_width);
sum_y_0 += static_cast<float>(ptr[offset + 0]);
sum_y_1 += static_cast<float>(ptr[offset + 1]);
sum_y_2 += static_cast<float>(ptr[offset + 2]);
}
scale_x = x_interp.end_minus_one_scale;
offset = 3 * BOUND_IF_NEEDED(x_interp.end - 1, st.in_width);
sum_y_0 += static_cast<float>(ptr[offset + 0]) * scale_x;
sum_y_1 += static_cast<float>(ptr[offset + 1]) * scale_x;
sum_y_2 += static_cast<float>(ptr[offset + 2]) * scale_x;
}
sum_0 += sum_y_0 * y_scales[i];
sum_1 += sum_y_1 * y_scales[i];
sum_2 += sum_y_2 * y_scales[i];
}
output_ptr[0] = sum_0 * scale;
output_ptr[1] = sum_1 * scale;
output_ptr[2] = sum_2 * scale;
#undef BOUND_IF_NEEDED
}
template <bool NeedsXBounding>
static void ComputePatchSum(float scale, const ImageResizerState& st,
const std::vector<const T*>& y_ptrs,
const std::vector<float>& y_scales,
const CachedInterpolation& x_interp,
float* output_ptr) {
#define BOUND_IF_NEEDED(x, y) (NeedsXBounding ? Bound(x, y) : (x))
const auto num_channels = st.channels;
for (int64_t c = 0; c < num_channels; ++c) {
float sum = 0;
for (int i = 0; i < y_ptrs.size(); ++i) {
const T* ptr = y_ptrs[i];
float scale_x = x_interp.start_scale;
float sum_y = static_cast<float>(
ptr[num_channels *
BOUND_IF_NEEDED(x_interp.start, st.in_width) +
c]) *
scale_x;
if (x_interp.start + 1 != x_interp.end) {
for (int64_t x = x_interp.start + 1; x < x_interp.end - 1; ++x) {
sum_y += static_cast<float>(
ptr[num_channels * BOUND_IF_NEEDED(x, st.in_width) + c]);
}
scale_x = x_interp.end_minus_one_scale;
sum_y += static_cast<float>(
ptr[num_channels *
BOUND_IF_NEEDED(x_interp.end - 1, st.in_width) +
c]) *
scale_x;
}
sum += sum_y * y_scales[i];
}
output_ptr[c] = sum * scale;
}
#undef BOUND_IF_NEEDED
}
void Compute(OpKernelContext* context) override {
ImageResizerState st(align_corners_, false);
st.ValidateAndCreateOutput(context);
if (!context->status().ok()) return;
typename TTypes<T, 4>::ConstTensor input_data(
context->input(0).tensor<T, 4>());
std::vector<CachedInterpolation> x_interps(st.out_width);
for (int64_t x = 0; x < st.out_width; ++x) {
auto& x_interp = x_interps[x];
const float in_x = x * st.width_scale;
const float in_x1 = (x + 1) * st.width_scale;
int64_t v = std::floor(in_x);
x_interp.start = v;
x_interp.start_scale =
v < in_x ? (v + 1 > in_x1 ? st.width_scale : v + 1 - in_x)
: (v + 1 > in_x1 ? in_x1 - v : 1.0);
v = std::ceil(in_x1);
x_interp.end = v;
v = x_interp.end - 1;
x_interp.end_minus_one_scale =
v < in_x ? (v + 1 > in_x1 ? st.width_scale : v + 1 - in_x)
: (v + 1 > in_x1 ? in_x1 - v : 1.0);
x_interp.needs_bounding =
Bound(x_interp.start, st.in_width) != x_interp.start ||
Bound(x_interp.end - 1, st.in_width) != (x_interp.end - 1);
}
if (st.channels == 3) {
ComputeLoop<3>(st, x_interps, input_data);
} else {
ComputeLoop<-1>(st, x_interps, input_data);
}
}
template <int64_t kKnownNumChannels>
void ComputeLoop(const ImageResizerState& st,
const std::vector<CachedInterpolation>& x_interps,
typename TTypes<T, 4>::ConstTensor input_data) {
TTypes<float, 4>::Tensor output_data = st.output->tensor<float, 4>();
const T* const input_ptr = input_data.data();
std::vector<float> y_scales;
std::vector<const T*> y_ptrs;
float scale = 1.0 / (st.height_scale * st.width_scale);
float* output_ptr = output_data.data();
for (int64_t b = 0; b < st.batch_size; ++b) {
for (int64_t y = 0; y < st.out_height; ++y) {
const float in_y = y * st.height_scale;
const float in_y1 = (y + 1) * st.height_scale;
const int64_t y_start = std::floor(in_y);
const int64_t y_end = std::ceil(in_y1);
y_scales.clear();
y_ptrs.clear();
for (int64_t i = y_start; i < y_end; ++i) {
float scale_y;
if (i < in_y) {
scale_y = (i + 1 > in_y1 ? st.height_scale : i + 1 - in_y);
} else {
scale_y = (i + 1 > in_y1 ? in_y1 - i : 1.0);
}
y_scales.push_back(scale_y);
y_ptrs.push_back(
input_ptr + (b * st.in_height * st.in_width * st.channels +
Bound(i, st.in_height) * st.in_width * st.channels));
}
if (kKnownNumChannels == 3) {
for (int64_t x = 0; x < st.out_width; ++x) {
const CachedInterpolation& x_interp = x_interps[x];
if (x_interp.needs_bounding) {
ComputePatchSumOf3Channels<true>(scale, st, y_ptrs, y_scales,
x_interp, output_ptr);
} else {
ComputePatchSumOf3Channels<false>(scale, st, y_ptrs, y_scales,
x_interp, output_ptr);
}
output_ptr += 3;
}
} else {
for (int64_t x = 0; x < st.out_width; ++x) {
const CachedInterpolation& x_interp = x_interps[x];
if (x_interp.needs_bounding) {
ComputePatchSum<true>(scale, st, y_ptrs, y_scales, x_interp,
output_ptr);
} else {
ComputePatchSum<false>(scale, st, y_ptrs, y_scales, x_interp,
output_ptr);
}
output_ptr += st.channels;
}
}
}
}
}
private:
static EIGEN_ALWAYS_INLINE int64_t Bound(int64_t val, int64_t limit) {
return std::min(limit - 1, std::max(int64_t{0}, val));
}
bool align_corners_;
};
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER(Name("ResizeArea") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("size"), \
ResizeAreaOp<CPUDevice, T>);
TF_CALL_REAL_NUMBER_TYPES(REGISTER_KERNEL);
#undef REGISTER_KERNEL
} | #include <cmath>
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
class ResizeAreaOpTest : public OpsTestBase {
protected:
ResizeAreaOpTest() = default;
void CreateOp(bool align_corners) {
TF_EXPECT_OK(NodeDefBuilder("resize_area_op", "ResizeArea")
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_INT32))
.Attr("align_corners", align_corners)
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
}
const Tensor* SetRandomImageInput(const TensorShape& shape) {
inputs_.clear();
CHECK_EQ(shape.dims(), 4) << "All images must have 4 dimensions.";
bool is_ref = IsRefType(input_types_[inputs_.size()]);
Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
DataTypeToEnum<float>::v(), shape);
input->flat<float>().setRandom();
tensors_.push_back(input);
if (is_ref) {
CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
DataTypeToEnum<float>::v());
inputs_.push_back({&lock_for_refs_, input});
} else {
CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<float>::v());
inputs_.push_back({nullptr, input});
}
return input;
}
private:
void ResizeAreaBaseline(TTypes<float, 4>::ConstTensor input_data,
TTypes<float, 4>::Tensor output_data) {
const int batch_size = input_data.dimension(0);
const int64_t in_height = input_data.dimension(1);
const int64_t in_width = input_data.dimension(2);
const int channels = input_data.dimension(3);
ASSERT_EQ(batch_size, output_data.dimension(0));
ASSERT_EQ(channels, output_data.dimension(3));
const int64_t out_height = output_data.dimension(1);
const int64_t out_width = output_data.dimension(2);
const float height_scale = in_height / static_cast<float>(out_height);
const float width_scale = in_width / static_cast<float>(out_width);
Tensor sum_tensor(DT_FLOAT, TensorShape({channels}));
typename TTypes<float, 1>::Tensor sum_data = sum_tensor.vec<float>();
float scale = 1.0 / (height_scale * width_scale);
for (int64_t b = 0; b < batch_size; ++b) {
for (int64_t y = 0; y < out_height; ++y) {
const float in_y = y * height_scale;
const float in_y1 = (y + 1) * height_scale;
int64_t y_start = std::floor(in_y);
int64_t y_end = std::ceil(in_y1);
for (int64_t x = 0; x < out_width; ++x) {
const float in_x = x * width_scale;
const float in_x1 = (x + 1) * width_scale;
int64_t x_start = std::floor(in_x);
int64_t x_end = std::ceil(in_x1);
sum_data.setConstant(0.0);
for (int64_t i = y_start; i < y_end; ++i) {
float scale_y = i < in_y
? (i + 1 > in_y1 ? height_scale : i + 1 - in_y)
: (i + 1 > in_y1 ? in_y1 - i : 1.0);
for (int64_t j = x_start; j < x_end; ++j) {
float scale_x = j < in_x
? (j + 1 > in_x1 ? width_scale : j + 1 - in_x)
: (j + 1 > in_x1 ? in_x1 - j : 1.0);
for (int64_t c = 0; c < channels; ++c) {
#define BOUND(val, limit) \
std::min(((limit)-int64_t{1}), (std::max(int64_t{0}, (val))))
sum_data(c) +=
static_cast<float>(input_data(b, BOUND(i, in_height),
BOUND(j, in_width), c)) *
scale_y * scale_x * scale;
#undef BOUND
}
}
}
for (int64_t c = 0; c < channels; ++c) {
output_data(b, y, x, c) = sum_data(c);
}
}
}
}
}
protected:
void RunRandomTest(int in_height, int in_width, int target_height,
int target_width, int channels) {
const Tensor* input =
SetRandomImageInput(TensorShape({1, in_height, in_width, channels}));
AddInputFromArray<int32>(TensorShape({2}), {target_height, target_width});
TF_ASSERT_OK(RunOpKernel());
std::unique_ptr<Tensor> expected(
new Tensor(device_->GetAllocator(AllocatorAttributes()),
DataTypeToEnum<float>::v(),
TensorShape({1, target_height, target_width, channels})));
ResizeAreaBaseline(input->tensor<float, 4>(), expected->tensor<float, 4>());
test::ExpectTensorNear<float>(*expected, *GetOutput(0), 0.00001);
}
void RunManyRandomTests(int channels) {
for (int in_w : {2, 4, 7, 20, 165}) {
for (int in_h : {1, 3, 5, 8, 100, 233}) {
for (int target_height : {1, 2, 3, 50, 113}) {
for (int target_width : {target_height, target_height / 2 + 1}) {
RunRandomTest(in_h, in_w, target_height, target_width, channels);
}
}
}
}
}
};
TEST_F(ResizeAreaOpTest, TestAreaRandom141x186) {
CreateOp(false);
RunRandomTest(141, 186, 299, 299, 3 );
}
TEST_F(ResizeAreaOpTest, TestAreaRandom183x229) {
CreateOp(false);
RunRandomTest(183, 229, 299, 299, 3 );
}
TEST_F(ResizeAreaOpTest, TestAreaRandom749x603) {
CreateOp(false);
RunRandomTest(749, 603, 299, 299, 3 );
}
TEST_F(ResizeAreaOpTest, TestAreaRandom1x1) {
CreateOp(false);
RunRandomTest(1, 1, 8, 8, 3 );
}
TEST_F(ResizeAreaOpTest, TestAreaRandom1x1AlignCorners) {
CreateOp(true);
RunRandomTest(1, 1, 8, 8, 3 );
}
TEST_F(ResizeAreaOpTest, TestAreaRandomDataSeveralInputsSizes1Channel) {
CreateOp(false);
RunManyRandomTests(1);
}
TEST_F(ResizeAreaOpTest, TestAreaRandomDataSeveralInputsSizes3Channels) {
CreateOp(false);
RunManyRandomTests(3);
}
TEST_F(ResizeAreaOpTest, TestAreaRandomDataSeveralInputsSizes4Channels) {
CreateOp(false);
RunManyRandomTests(4);
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/image/resize_area_op.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/image/resize_area_op_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
f984bfc5-570a-4e15-a5fa-d3f2a282abf0 | cpp | abseil/abseil-cpp | iostream_state_saver | absl/random/internal/iostream_state_saver.h | absl/random/internal/iostream_state_saver_test.cc | #ifndef ABSL_RANDOM_INTERNAL_IOSTREAM_STATE_SAVER_H_
#define ABSL_RANDOM_INTERNAL_IOSTREAM_STATE_SAVER_H_
#include <cmath>
#include <iostream>
#include <limits>
#include <type_traits>
#include "absl/meta/type_traits.h"
#include "absl/numeric/int128.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
template <typename T>
class null_state_saver {
public:
using stream_type = T;
using flags_type = std::ios_base::fmtflags;
null_state_saver(T&, flags_type) {}
~null_state_saver() {}
};
template <typename OStream>
class ostream_state_saver {
public:
using ostream_type = OStream;
using flags_type = std::ios_base::fmtflags;
using fill_type = typename ostream_type::char_type;
using precision_type = std::streamsize;
ostream_state_saver(ostream_type& os,
flags_type flags, fill_type fill)
: os_(os),
flags_(os.flags(flags)),
fill_(os.fill(fill)),
precision_(os.precision()) {
}
~ostream_state_saver() {
os_.precision(precision_);
os_.fill(fill_);
os_.flags(flags_);
}
private:
ostream_type& os_;
const flags_type flags_;
const fill_type fill_;
const precision_type precision_;
};
#if defined(__NDK_MAJOR__) && __NDK_MAJOR__ < 16
#define ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT 1
#else
#define ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT 0
#endif
template <typename CharT, typename Traits>
ostream_state_saver<std::basic_ostream<CharT, Traits>> make_ostream_state_saver(
std::basic_ostream<CharT, Traits>& os,
std::ios_base::fmtflags flags = std::ios_base::dec | std::ios_base::left |
#if ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT
std::ios_base::fixed |
#endif
std::ios_base::scientific) {
using result_type = ostream_state_saver<std::basic_ostream<CharT, Traits>>;
return result_type(os, flags, os.widen(' '));
}
template <typename T>
typename absl::enable_if_t<!std::is_base_of<std::ios_base, T>::value,
null_state_saver<T>>
make_ostream_state_saver(T& is,
std::ios_base::fmtflags flags = std::ios_base::dec) {
std::cerr << "null_state_saver";
using result_type = null_state_saver<T>;
return result_type(is, flags);
}
template <typename T>
struct stream_precision_helper {
static constexpr int kPrecision =
(std::numeric_limits<T>::max_digits10 > std::numeric_limits<T>::digits10)
? std::numeric_limits<T>::max_digits10
: (std::numeric_limits<T>::digits10 + 3);
};
template <>
struct stream_precision_helper<float> {
static constexpr int kPrecision = 9;
};
template <>
struct stream_precision_helper<double> {
static constexpr int kPrecision = 17;
};
template <>
struct stream_precision_helper<long double> {
static constexpr int kPrecision = 36;
};
template <typename IStream>
class istream_state_saver {
public:
using istream_type = IStream;
using flags_type = std::ios_base::fmtflags;
istream_state_saver(istream_type& is,
flags_type flags)
: is_(is), flags_(is.flags(flags)) {}
~istream_state_saver() { is_.flags(flags_); }
private:
istream_type& is_;
flags_type flags_;
};
template <typename CharT, typename Traits>
istream_state_saver<std::basic_istream<CharT, Traits>> make_istream_state_saver(
std::basic_istream<CharT, Traits>& is,
std::ios_base::fmtflags flags = std::ios_base::dec |
std::ios_base::scientific |
std::ios_base::skipws) {
using result_type = istream_state_saver<std::basic_istream<CharT, Traits>>;
return result_type(is, flags);
}
template <typename T>
typename absl::enable_if_t<!std::is_base_of<std::ios_base, T>::value,
null_state_saver<T>>
make_istream_state_saver(T& is,
std::ios_base::fmtflags flags = std::ios_base::dec) {
using result_type = null_state_saver<T>;
return result_type(is, flags);
}
template <typename T>
struct stream_format_type
: public std::conditional<(sizeof(T) == sizeof(char)), int, T> {};
template <typename T>
struct stream_u128_helper;
template <>
struct stream_u128_helper<absl::uint128> {
template <typename IStream>
inline absl::uint128 read(IStream& in) {
uint64_t h = 0;
uint64_t l = 0;
in >> h >> l;
return absl::MakeUint128(h, l);
}
template <typename OStream>
inline void write(absl::uint128 val, OStream& out) {
uint64_t h = absl::Uint128High64(val);
uint64_t l = absl::Uint128Low64(val);
out << h << out.fill() << l;
}
};
#ifdef ABSL_HAVE_INTRINSIC_INT128
template <>
struct stream_u128_helper<__uint128_t> {
template <typename IStream>
inline __uint128_t read(IStream& in) {
uint64_t h = 0;
uint64_t l = 0;
in >> h >> l;
return (static_cast<__uint128_t>(h) << 64) | l;
}
template <typename OStream>
inline void write(__uint128_t val, OStream& out) {
uint64_t h = static_cast<uint64_t>(val >> 64u);
uint64_t l = static_cast<uint64_t>(val);
out << h << out.fill() << l;
}
};
#endif
template <typename FloatType, typename IStream>
inline FloatType read_floating_point(IStream& is) {
static_assert(std::is_floating_point<FloatType>::value, "");
FloatType dest;
is >> dest;
if (is.fail() &&
(std::fabs(dest) == (std::numeric_limits<FloatType>::min)() ||
std::fpclassify(dest) == FP_SUBNORMAL)) {
is.clear(is.rdstate() & (~std::ios_base::failbit));
}
return dest;
}
}
ABSL_NAMESPACE_END
}
#endif | #include "absl/random/internal/iostream_state_saver.h"
#include <errno.h>
#include <stdio.h>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
namespace {
using absl::random_internal::make_istream_state_saver;
using absl::random_internal::make_ostream_state_saver;
using absl::random_internal::stream_precision_helper;
template <typename T>
typename absl::enable_if_t<std::is_integral<T>::value, T>
StreamRoundTrip(T t) {
std::stringstream ss;
{
auto saver = make_ostream_state_saver(ss);
ss.precision(stream_precision_helper<T>::kPrecision);
ss << t;
}
T result = 0;
{
auto saver = make_istream_state_saver(ss);
ss >> result;
}
EXPECT_FALSE(ss.fail())
<< ss.str() << " "
<< (ss.good() ? "good " : "")
<< (ss.bad() ? "bad " : "")
<< (ss.eof() ? "eof " : "")
<< (ss.fail() ? "fail " : "");
return result;
}
template <typename T>
typename absl::enable_if_t<std::is_floating_point<T>::value, T>
StreamRoundTrip(T t) {
std::stringstream ss;
{
auto saver = make_ostream_state_saver(ss);
ss.precision(stream_precision_helper<T>::kPrecision);
ss << t;
}
T result = 0;
{
auto saver = make_istream_state_saver(ss);
result = absl::random_internal::read_floating_point<T>(ss);
}
EXPECT_FALSE(ss.fail())
<< ss.str() << " "
<< (ss.good() ? "good " : "")
<< (ss.bad() ? "bad " : "")
<< (ss.eof() ? "eof " : "")
<< (ss.fail() ? "fail " : "");
return result;
}
TEST(IOStreamStateSaver, BasicSaverState) {
std::stringstream ss;
ss.precision(2);
ss.fill('x');
ss.flags(std::ios_base::dec | std::ios_base::right);
{
auto saver = make_ostream_state_saver(ss);
ss.precision(10);
EXPECT_NE('x', ss.fill());
EXPECT_EQ(10, ss.precision());
EXPECT_NE(std::ios_base::dec | std::ios_base::right, ss.flags());
ss << 1.23;
}
EXPECT_EQ('x', ss.fill());
EXPECT_EQ(2, ss.precision());
EXPECT_EQ(std::ios_base::dec | std::ios_base::right, ss.flags());
}
TEST(IOStreamStateSaver, RoundTripInts) {
const uint64_t kUintValues[] = {
0,
1,
static_cast<uint64_t>(-1),
2,
static_cast<uint64_t>(-2),
1 << 7,
1 << 8,
1 << 16,
1ull << 32,
1ull << 50,
1ull << 62,
1ull << 63,
(1 << 7) - 1,
(1 << 8) - 1,
(1 << 16) - 1,
(1ull << 32) - 1,
(1ull << 50) - 1,
(1ull << 62) - 1,
(1ull << 63) - 1,
static_cast<uint64_t>(-(1 << 8)),
static_cast<uint64_t>(-(1 << 16)),
static_cast<uint64_t>(-(1ll << 32)),
static_cast<uint64_t>(-(1ll << 50)),
static_cast<uint64_t>(-(1ll << 62)),
static_cast<uint64_t>(-(1 << 8) - 1),
static_cast<uint64_t>(-(1 << 16) - 1),
static_cast<uint64_t>(-(1ll << 32) - 1),
static_cast<uint64_t>(-(1ll << 50) - 1),
static_cast<uint64_t>(-(1ll << 62) - 1),
};
for (const uint64_t u : kUintValues) {
EXPECT_EQ(u, StreamRoundTrip<uint64_t>(u));
int64_t x = static_cast<int64_t>(u);
EXPECT_EQ(x, StreamRoundTrip<int64_t>(x));
double d = static_cast<double>(x);
EXPECT_EQ(d, StreamRoundTrip<double>(d));
float f = d;
EXPECT_EQ(f, StreamRoundTrip<float>(f));
}
}
TEST(IOStreamStateSaver, RoundTripFloats) {
static_assert(
stream_precision_helper<float>::kPrecision >= 9,
"stream_precision_helper<float>::kPrecision should be at least 9");
const float kValues[] = {
1,
std::nextafter(1.0f, 0.0f),
std::nextafter(1.0f, 2.0f),
1.0e+1f,
1.0e-1f,
1.0e+2f,
1.0e-2f,
1.0e+10f,
1.0e-10f,
0.00000051110000111311111111f,
-0.00000051110000111211111111f,
1.234678912345678912345e+6f,
1.234678912345678912345e-6f,
1.234678912345678912345e+30f,
1.234678912345678912345e-30f,
1.234678912345678912345e+38f,
1.0234678912345678912345e-38f,
std::numeric_limits<float>::max(),
std::numeric_limits<float>::lowest(),
std::numeric_limits<float>::epsilon(),
std::nextafter(std::numeric_limits<float>::min(),
1.0f),
std::numeric_limits<float>::min(),
std::numeric_limits<float>::denorm_min(),
std::numeric_limits<float>::min() / 2,
std::nextafter(std::numeric_limits<float>::min(),
0.0f),
std::nextafter(std::numeric_limits<float>::denorm_min(), 1.0f),
};
for (const float f : kValues) {
EXPECT_EQ(f, StreamRoundTrip<float>(f));
EXPECT_EQ(-f, StreamRoundTrip<float>(-f));
double d = f;
EXPECT_EQ(d, StreamRoundTrip<double>(d));
EXPECT_EQ(-d, StreamRoundTrip<double>(-d));
if (f <= static_cast<float>(std::numeric_limits<int64_t>::max()) &&
f >= static_cast<float>(std::numeric_limits<int64_t>::lowest())) {
int64_t x = static_cast<int64_t>(f);
EXPECT_EQ(x, StreamRoundTrip<int64_t>(x));
}
}
}
TEST(IOStreamStateSaver, RoundTripDoubles) {
static_assert(
stream_precision_helper<double>::kPrecision >= 17,
"stream_precision_helper<double>::kPrecision should be at least 17");
const double kValues[] = {
1,
std::nextafter(1.0, 0.0),
std::nextafter(1.0, 2.0),
1.0e+1,
1.0e-1,
1.0e+2,
1.0e-2,
1.0e+10,
1.0e-10,
0.00000051110000111311111111,
-0.00000051110000111211111111,
1.234678912345678912345e+6,
1.234678912345678912345e-6,
1.234678912345678912345e+30,
1.234678912345678912345e-30,
1.234678912345678912345e+38,
1.0234678912345678912345e-38,
1.0e+100,
1.0e-100,
1.234678912345678912345e+308,
1.0234678912345678912345e-308,
2.22507385850720138e-308,
std::numeric_limits<double>::max(),
std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::epsilon(),
std::nextafter(std::numeric_limits<double>::min(),
1.0),
std::numeric_limits<double>::min(),
std::numeric_limits<double>::denorm_min(),
std::numeric_limits<double>::min() / 2,
std::nextafter(std::numeric_limits<double>::min(),
0.0),
std::nextafter(std::numeric_limits<double>::denorm_min(), 1.0f),
};
for (const double d : kValues) {
EXPECT_EQ(d, StreamRoundTrip<double>(d));
EXPECT_EQ(-d, StreamRoundTrip<double>(-d));
if (d <= std::numeric_limits<float>::max() &&
d >= std::numeric_limits<float>::lowest()) {
float f = static_cast<float>(d);
EXPECT_EQ(f, StreamRoundTrip<float>(f));
}
if (d <= static_cast<double>(std::numeric_limits<int64_t>::max()) &&
d >= static_cast<double>(std::numeric_limits<int64_t>::lowest())) {
int64_t x = static_cast<int64_t>(d);
EXPECT_EQ(x, StreamRoundTrip<int64_t>(x));
}
}
}
TEST(IOStreamStateSaver, RoundTripLongDoubles) {
static_assert(
stream_precision_helper<long double>::kPrecision >= 36,
"stream_precision_helper<long double>::kPrecision should be at least 36");
using real_type = long double;
const real_type kValues[] = {
1,
std::nextafter(1.0, 0.0),
std::nextafter(1.0, 2.0),
1.0e+1,
1.0e-1,
1.0e+2,
1.0e-2,
1.0e+10,
1.0e-10,
0.00000051110000111311111111,
-0.00000051110000111211111111,
1.2346789123456789123456789123456789e+6,
1.2346789123456789123456789123456789e-6,
1.2346789123456789123456789123456789e+30,
1.2346789123456789123456789123456789e-30,
1.2346789123456789123456789123456789e+38,
1.2346789123456789123456789123456789e-38,
1.2346789123456789123456789123456789e+308,
1.2346789123456789123456789123456789e-308,
1.0e+100,
1.0e-100,
1.234678912345678912345e+308,
1.0234678912345678912345e-308,
std::numeric_limits<real_type>::max(),
std::numeric_limits<real_type>::lowest(),
std::numeric_limits<real_type>::epsilon(),
std::nextafter(std::numeric_limits<real_type>::min(),
real_type(1)),
std::numeric_limits<real_type>::min(),
std::numeric_limits<real_type>::denorm_min(),
std::numeric_limits<real_type>::min() / 2,
std::nextafter(std::numeric_limits<real_type>::min(),
0.0),
std::nextafter(std::numeric_limits<real_type>::denorm_min(), 1.0f),
};
int index = -1;
for (const long double dd : kValues) {
index++;
EXPECT_EQ(dd, StreamRoundTrip<real_type>(dd)) << index;
EXPECT_EQ(-dd, StreamRoundTrip<real_type>(-dd)) << index;
if (dd <= std::numeric_limits<double>::max() &&
dd >= std::numeric_limits<double>::lowest()) {
double d = static_cast<double>(dd);
EXPECT_EQ(d, StreamRoundTrip<double>(d));
}
if (dd <= static_cast<long double>(std::numeric_limits<int64_t>::max()) &&
dd >=
static_cast<long double>(std::numeric_limits<int64_t>::lowest())) {
int64_t x = static_cast<int64_t>(dd);
EXPECT_EQ(x, StreamRoundTrip<int64_t>(x));
}
}
}
TEST(StrToDTest, DoubleMin) {
const char kV[] = "2.22507385850720138e-308";
char* end;
double x = std::strtod(kV, &end);
EXPECT_EQ(std::numeric_limits<double>::min(), x);
}
TEST(StrToDTest, DoubleDenormMin) {
const char kV[] = "4.94065645841246544e-324";
char* end;
double x = std::strtod(kV, &end);
EXPECT_EQ(std::numeric_limits<double>::denorm_min(), x);
}
} | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/iostream_state_saver.h | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/iostream_state_saver_test.cc | 03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4 |
43adc7c9-b886-457c-a5e5-6eed4f63e185 | cpp | tensorflow/tensorflow | atan2_custom | tensorflow/lite/kernels/atan2_custom.cc | tensorflow/lite/kernels/atan2_custom_test.cc | #include <cmath>
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/custom_ops_register.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace custom {
namespace atan2 {
TfLiteStatus EnsureSameShape(TfLiteContext* context, const TfLiteTensor* a,
const TfLiteTensor* b) {
TF_LITE_ENSURE_EQ(context, tflite::NumDimensions(a),
tflite::NumDimensions(b));
return TfLiteStatus::kTfLiteOk;
}
TfLiteStatus Atan2Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, tflite::NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, tflite::NumOutputs(node), 1);
const TfLiteTensor* input_y = tflite::GetInput(context, node, 0);
const TfLiteTensor* input_x = tflite::GetInput(context, node, 1);
TfLiteTensor* output = tflite::GetOutput(context, node, 0);
TF_LITE_ENSURE_OK(context, EnsureSameShape(context, input_y, input_x));
TF_LITE_ENSURE_TYPES_EQ(context, input_y->type, input_x->type);
TF_LITE_ENSURE_TYPES_EQ(context, input_y->type, output->type);
TF_LITE_ENSURE(context, input_y->type == kTfLiteFloat32 ||
input_y->type == kTfLiteFloat64);
TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input_y->dims);
return context->ResizeTensor(context, output, output_shape);
}
template <typename Float>
TfLiteStatus Atan2(const TfLiteTensor* input_y, const TfLiteTensor* input_x,
TfLiteTensor* output) {
const Float* data_y = tflite::GetTensorData<Float>(input_y);
const Float* data_x = tflite::GetTensorData<Float>(input_x);
Float* data_output = tflite::GetTensorData<Float>(output);
const int64_t num_elements = NumElements(input_y);
for (int64_t i = 0; i < num_elements; ++i) {
data_output[i] = std::atan2(data_y[i], data_x[i]);
}
return TfLiteStatus::kTfLiteOk;
}
TfLiteStatus Atan2Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_y = tflite::GetInput(context, node, 0);
const TfLiteTensor* input_x = tflite::GetInput(context, node, 1);
TfLiteTensor* output = tflite::GetOutput(context, node, 0);
switch (output->type) {
case kTfLiteFloat32:
TF_LITE_ENSURE_OK(context, Atan2<float>(input_y, input_x, output));
break;
case kTfLiteFloat64:
TF_LITE_ENSURE_OK(context, Atan2<double>(input_y, input_x, output));
break;
default: {
TF_LITE_KERNEL_LOG(context, "Unsupported datatype for atan2 output: %s",
TfLiteTypeGetName(output->type));
return TfLiteStatus::kTfLiteError;
}
}
return TfLiteStatus::kTfLiteOk;
}
}
TfLiteRegistration* Register_ATAN2() {
static TfLiteRegistration r = {nullptr, nullptr, atan2::Atan2Prepare,
atan2::Atan2Eval};
return &r;
}
}
}
} | #include <cmath>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/kernels/custom_ops_register.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/testing/util.h"
namespace tflite {
namespace {
template <typename T>
tflite::TensorType GetTTEnum();
template <>
tflite::TensorType GetTTEnum<float>() {
return tflite::TensorType_FLOAT32;
}
template <>
tflite::TensorType GetTTEnum<double>() {
return tflite::TensorType_FLOAT64;
}
class Atan2Model : public tflite::SingleOpModel {
public:
Atan2Model(tflite::TensorData y, tflite::TensorData x,
tflite::TensorData output) {
y_ = AddInput(y);
x_ = AddInput(x);
output_ = AddOutput(output);
SetCustomOp("atan2", {}, ops::custom::Register_ATAN2);
BuildInterpreter({GetShape(y_), GetShape(x_)});
}
int y_;
int x_;
int output_;
template <typename T>
std::vector<T> GetOutput(const std::vector<T>& y, const std::vector<T>& x) {
PopulateTensor<T>(y_, y);
PopulateTensor<T>(x_, x);
Invoke();
return ExtractVector<T>(output_);
}
};
template <typename Float>
class Atan2CustomTest : public ::testing::Test {
public:
using FloatType = Float;
};
using TestTypes = ::testing::Types<float, double>;
TYPED_TEST_SUITE(Atan2CustomTest, TestTypes);
TYPED_TEST(Atan2CustomTest, TestScalar) {
using Float = typename TestFixture::FloatType;
tflite::TensorData y = {GetTTEnum<Float>(), {}};
tflite::TensorData x = {GetTTEnum<Float>(), {}};
tflite::TensorData output = {GetTTEnum<Float>(), {}};
Atan2Model m(y, x, output);
auto got = m.GetOutput<Float>({0.0}, {0.0});
ASSERT_EQ(got.size(), 1);
EXPECT_FLOAT_EQ(got[0], 0.0);
ASSERT_FLOAT_EQ(m.GetOutput<Float>({1.0}, {0.0})[0], M_PI / 2);
ASSERT_FLOAT_EQ(m.GetOutput<Float>({0.0}, {1.0})[0], 0.0);
ASSERT_FLOAT_EQ(m.GetOutput<Float>({-1.0}, {0.0})[0], -M_PI / 2);
}
TYPED_TEST(Atan2CustomTest, TestBatch) {
using Float = typename TestFixture::FloatType;
tflite::TensorData y = {GetTTEnum<Float>(), {4, 2, 1}};
tflite::TensorData x = {GetTTEnum<Float>(), {4, 2, 1}};
tflite::TensorData output = {GetTTEnum<Float>(), {4, 2, 1}};
Atan2Model m(y, x, output);
std::vector<Float> y_data = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
std::vector<Float> x_data = {0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1};
auto got = m.GetOutput<Float>(y_data, x_data);
ASSERT_EQ(got.size(), 8);
for (int i = 0; i < 8; ++i) {
EXPECT_FLOAT_EQ(got[i], std::atan2(y_data[i], x_data[i]));
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/atan2_custom.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/atan2_custom_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
b8fd7778-aef1-4e13-95a9-3baf8f3db331 | cpp | tensorflow/tensorflow | preprocessor | tensorflow/lite/delegates/gpu/gl/compiler/preprocessor.cc | tensorflow/lite/delegates/gpu/gl/compiler/preprocessor_test.cc | #include "tensorflow/lite/delegates/gpu/gl/compiler/preprocessor.h"
#include <string>
#include <utility>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
namespace tflite {
namespace gpu {
namespace gl {
namespace {
absl::string_view FindInlineBlock(absl::string_view s, char delimiter) {
size_t start = s.find(delimiter);
if (start != absl::string_view::npos) {
size_t end = s.find(delimiter, start + 1);
if (end != std::string::npos) {
return s.substr(start, end - start + 1);
}
return s.substr(start, 1);
}
return s.substr(s.size(), 0);
}
absl::string_view PastSubstr(absl::string_view s, absl::string_view subs) {
return s.substr(subs.data() + subs.size() - s.data());
}
}
absl::Status TextPreprocessor::Rewrite(const std::string& input,
std::string* output) {
absl::string_view s = input;
std::string result;
while (true) {
absl::string_view inline_block = FindInlineBlock(s, inline_delimiter_);
result.append(s.data(), inline_block.data() - s.data());
if (inline_block.empty()) {
break;
}
if (inline_block.size() == 1) {
return absl::NotFoundError("Unable to find end of inline block");
}
s = PastSubstr(s, inline_block);
bool processed = false;
for (auto& rewrite : inline_rewrites_) {
if (processed) {
break;
}
switch (rewrite->Rewrite(inline_block.substr(1, inline_block.size() - 2),
&result)) {
case RewriteStatus::NOT_RECOGNIZED:
break;
case RewriteStatus::SUCCESS:
processed = true;
break;
case RewriteStatus::ERROR:
return absl::InternalError(absl::StrCat("Error while rewriting '",
inline_block, "': ", result));
}
}
if (!processed) {
if (!keep_unknown_rewrites_) {
return absl::NotFoundError(absl::StrCat(
"Didn't find inline rewrite for '", inline_block, "'"));
}
absl::StrAppend(&result, inline_block);
}
}
*output = std::move(result);
return absl::OkStatus();
}
}
}
} | #include "tensorflow/lite/delegates/gpu/gl/compiler/preprocessor.h"
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/string_view.h"
namespace tflite {
namespace gpu {
namespace gl {
namespace {
class AccuInlineRewrite : public InlineRewrite {
public:
explicit AccuInlineRewrite(std::vector<std::string>* blocks)
: blocks_(blocks) {}
RewriteStatus Rewrite(absl::string_view input, std::string* output) final {
blocks_->push_back(std::string(input.data(), input.size()));
output->append("r:");
output->append(input.data(), input.size());
return RewriteStatus::SUCCESS;
}
std::vector<std::string>* blocks_;
};
std::vector<std::string> ParseInlines(const std::string& text) {
std::vector<std::string> blocks;
TextPreprocessor preprocessor('$', false);
AccuInlineRewrite rewrite(&blocks);
preprocessor.AddRewrite(&rewrite);
std::string discard;
preprocessor.Rewrite(text, &discard).IgnoreError();
return blocks;
}
TEST(Preprocessor, CornerCases) {
EXPECT_THAT(ParseInlines(""), testing::ElementsAre());
EXPECT_THAT(ParseInlines("text text"), testing::ElementsAre());
EXPECT_THAT(ParseInlines("$$"), testing::ElementsAre(""));
}
TEST(Preprocessor, One) {
EXPECT_THAT(ParseInlines("$text$"), testing::ElementsAre("text"));
EXPECT_THAT(ParseInlines(" $text$ "), testing::ElementsAre("text"));
}
TEST(Preprocessor, More) {
EXPECT_THAT(ParseInlines("Test $inline1$\n$inline2$ test $inline3$ "),
testing::ElementsAre("inline1", "inline2", "inline3"));
}
std::string RewriteInlines(const std::string& text) {
std::vector<std::string> blocks;
TextPreprocessor preprocessor('$', false);
AccuInlineRewrite rewrite(&blocks);
preprocessor.AddRewrite(&rewrite);
std::string out;
preprocessor.Rewrite(text, &out).IgnoreError();
return out;
}
TEST(Preprocessor, RewriteCornerCases) {
EXPECT_EQ(RewriteInlines(""), "");
EXPECT_EQ(RewriteInlines("text text"), "text text");
EXPECT_EQ(RewriteInlines("$$"), "r:");
}
TEST(Preprocessor, RewriteOne) {
EXPECT_EQ(RewriteInlines("$text$"), "r:text");
EXPECT_EQ(RewriteInlines(" $text$ "), " r:text ");
}
TEST(Preprocessor, RewriteMore) {
EXPECT_EQ(RewriteInlines("Test $inline1$\n$inline2$ test $inline3$ "),
"Test r:inline1\nr:inline2 test r:inline3 ");
}
class SingleRewrite : public InlineRewrite {
public:
RewriteStatus Rewrite(absl::string_view input, std::string* output) final {
if (input == "foo") {
output->append("bla");
return RewriteStatus::SUCCESS;
}
return RewriteStatus::NOT_RECOGNIZED;
}
std::vector<std::string>* blocks_;
};
TEST(Preprocessor, KeepUnknownRewrites) {
TextPreprocessor preprocessor('$', true);
SingleRewrite rewrite;
preprocessor.AddRewrite(&rewrite);
std::string out;
ASSERT_TRUE(preprocessor.Rewrite("Good morning, $name$! $foo$", &out).ok());
EXPECT_EQ("Good morning, $name$! bla", out);
}
TEST(Preprocessor, KeepUnknownRewrites_Fail) {
TextPreprocessor preprocessor('$', false);
SingleRewrite rewrite;
preprocessor.AddRewrite(&rewrite);
std::string out;
EXPECT_FALSE(preprocessor.Rewrite("Good morning, $name$! $foo$", &out).ok());
}
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/gl/compiler/preprocessor.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/gl/compiler/preprocessor_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
20faff15-9cb2-45e3-8fb6-71e81ba3c0a8 | cpp | tensorflow/tensorflow | sine | tensorflow/lite/experimental/shlo/ops/sine.cc | tensorflow/lite/experimental/shlo/ops/sine_test.cc | #include "tensorflow/lite/experimental/shlo/ops/sine.h"
#include <cmath>
#include "absl/status/status.h"
#include "tensorflow/lite/experimental/shlo/bf16.h"
#include "tensorflow/lite/experimental/shlo/data_type.h"
#include "tensorflow/lite/experimental/shlo/dispatch.h"
#include "tensorflow/lite/experimental/shlo/f16.h"
#include "tensorflow/lite/experimental/shlo/ops/unary_elementwise.h"
#include "tensorflow/lite/experimental/shlo/ops/util.h"
#include "tensorflow/lite/experimental/shlo/tensor.h"
namespace shlo_ref {
struct Sine {
template <class T>
T operator()(T v) const {
return std::sin(v);
}
};
template <>
F16 Sine::operator()<F16>(F16 val) const {
return F16(operator()(static_cast<float>(val)));
}
template <>
BF16 Sine::operator()<BF16>(BF16 val) const {
return BF16(operator()(static_cast<float>(val)));
}
SineOp Create(SineOp::Attributes) { return {}; }
absl::Status Prepare(SineOp& op, const Tensor& input, Tensor& output) {
SHLO_REF_RETURN_ON_ERROR(Propagate(input.shape(), output.shape()));
SHLO_REF_RETURN_ON_ERROR(CheckSupportedTypes(
CheckCtx("sine"), input, IsFloatTensor, IsQuantizedPerTensorTensor));
SHLO_REF_RETURN_ON_ERROR(
CheckSameBaselineType(CheckCtx("sine"), input, output));
return absl::OkStatus();
}
absl::Status Evaluate(SineOp& op, const Tensor& input, Tensor& output) {
Sine sine;
if (input.IsPerTensorQuantized()) {
DISPATCH_QUANTIZED(
detail::DequantizeOpQuantizePerTensor,
input.quantized_per_tensor_element_type().StorageType(),
input.quantized_per_tensor_element_type().ExpressedType(), sine, input,
output)
} else if (!input.IsQuantized() && IsFloat(input.StorageType())) {
DISPATCH_FLOAT(detail::EvaluateNoQuantization, input.tensor_element_type(),
sine, input, output);
}
return absl::FailedPreconditionError("Unsupported tensor type.");
}
}; | #include "tensorflow/lite/experimental/shlo/ops/sine.h"
#include <cmath>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/experimental/shlo/bf16.h"
#include "tensorflow/lite/experimental/shlo/f16.h"
#include "tensorflow/lite/experimental/shlo/ops/test_util.h"
#include "tensorflow/lite/experimental/shlo/ops/unary_elementwise_test_util.h"
#include "tensorflow/lite/experimental/shlo/quantize.h"
#include "tensorflow/lite/experimental/shlo/quantized_tensor_element_type.h"
#include "tensorflow/lite/experimental/shlo/shape.h"
#include "tensorflow/lite/experimental/shlo/status_matcher.h"
#include "tensorflow/lite/experimental/shlo/tensor.h"
using testing::ElementsAreArray;
using testing::NanSensitiveFloatEq;
using testing::Pointwise;
namespace shlo_ref {
template <>
struct ParamName<SineOp> {
static std::string Get() { return "Sine"; }
};
namespace {
struct Sine {
template <class T>
T operator()(T v) const {
return std::sin(v);
}
} sine_ref;
template <>
F16 Sine::operator()<F16>(F16 val) const {
return F16(operator()(static_cast<float>(val)));
}
template <>
BF16 Sine::operator()<BF16>(BF16 val) const {
return BF16(operator()(static_cast<float>(val)));
}
INSTANTIATE_TYPED_TEST_SUITE_P(Sine, UnaryElementwiseOpShapePropagationTest,
SineOp, TestParamNames);
INSTANTIATE_TYPED_TEST_SUITE_P(
Sine, UnaryElementwiseSameBaselineElementTypeConstraintTest,
UnaryElementwiseConstraint1Types<SineOp>, TestParamNames);
using UnsupportedTypes = WithOpTypes<
SineOp, ConcatTypes<BoolTestType, IntTestTypes, PerAxisQuantizedTestTypes>>;
INSTANTIATE_TYPED_TEST_SUITE_P(Sine, UnaryElementwiseUnsupportedTypeTest,
UnsupportedTypes, TestParamNames);
template <class T>
struct FloatSineTest : ::testing::Test {};
TYPED_TEST_SUITE(FloatSineTest, FloatTestTypes, TestParamNames);
TYPED_TEST(FloatSineTest, FloatTensorsWork) {
using StorageT = typename TypeParam::StorageT;
const Shape shape({2, 3, 4});
Vector<StorageT> input_data = RandomBuffer<TypeParam::kStorage>(shape);
Vector<StorageT> output_data(shape.NumElements());
const TensorType tensor_type =
TensorType{.shape = shape, .element_type = TypeParam::kStorage};
Tensor input_tensor{.type = tensor_type, .data = input_data.data()};
Tensor output_tensor{.type = tensor_type, .data = output_data.data()};
Vector<StorageT> expected_data(shape.NumElements());
absl::c_transform(input_data, expected_data.begin(), sine_ref);
auto op = Create(SineOp::Attributes{});
ASSERT_OK(Prepare(op, input_tensor, output_tensor));
ASSERT_OK(Evaluate(op, input_tensor, output_tensor));
EXPECT_THAT(output_data, Pointwise(NanSensitiveFloatEq(), expected_data));
}
template <class T>
struct QuantizedSineTest : ::testing::Test {};
TYPED_TEST_SUITE(QuantizedSineTest, QuantizedTestTypes, TestParamNames);
TYPED_TEST(QuantizedSineTest, PerTensorWorks) {
using StorageT = typename TypeParam::StorageT;
using ExpressedT = typename TypeParam::ExpressedT;
const Shape shape({2, 3, 4});
const ExpressedT scale = static_cast<ExpressedT>(1.5);
const StorageT zero_point = static_cast<StorageT>(5);
Vector<StorageT> input_data = RandomBuffer<TypeParam::kStorage>(shape);
Vector<StorageT> output_data(shape.NumElements());
const QuantizedPerTensorTensorType tensor_type = {
.shape = shape,
.element_type = QuantizedElementTypePerTensor(
TypeParam::kStorage, zero_point, TypeParam::kExpressed, scale)};
Tensor input_tensor{.type = tensor_type, .data = input_data.data()};
Tensor output_tensor{.type = tensor_type, .data = output_data.data()};
Vector<StorageT> expected_data(shape.NumElements());
absl::c_transform(
input_data, expected_data.begin(), [zero_point, scale](auto v) {
const ExpressedT dequantized_input = Dequantize(v, zero_point, scale);
const ExpressedT dequantized_res = sine_ref(dequantized_input);
return Quantize<TypeParam::kStorage, TypeParam::kExpressed>(
dequantized_res, zero_point, static_cast<ExpressedT>(1.) / scale);
});
auto op = Create(SineOp::Attributes{});
ASSERT_OK(Prepare(op, input_tensor, output_tensor));
ASSERT_OK(Evaluate(op, input_tensor, output_tensor));
EXPECT_THAT(output_data, ElementsAreArray(expected_data));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/experimental/shlo/ops/sine.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/experimental/shlo/ops/sine_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
b2165cf5-6d76-4ef0-ab7b-10c49b938012 | cpp | google/tsl | path | tsl/platform/path.cc | tsl/platform/path_test.cc | #include "tsl/platform/path.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(PLATFORM_WINDOWS)
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <string>
#include <vector>
#include "absl/algorithm/container.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/scanner.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace io {
namespace internal {
namespace {
const char kPathSep[] = "/";
}
string JoinPathImpl(std::initializer_list<absl::string_view> paths) {
string result;
for (absl::string_view path : paths) {
if (path.empty()) continue;
if (result.empty()) {
result = string(path);
continue;
}
if (IsAbsolutePath(path)) path = path.substr(1);
if (result[result.size() - 1] == kPathSep[0]) {
strings::StrAppend(&result, path);
} else {
strings::StrAppend(&result, kPathSep, path);
}
}
return result;
}
std::pair<absl::string_view, absl::string_view> SplitPath(
absl::string_view uri) {
absl::string_view scheme, host, path;
ParseURI(uri, &scheme, &host, &path);
auto pos = path.rfind('/');
#ifdef PLATFORM_WINDOWS
if (pos == StringPiece::npos) pos = path.rfind('\\');
#endif
if (pos == absl::string_view::npos)
return std::make_pair(
absl::string_view(uri.data(), host.end() - uri.begin()), path);
if (pos == 0)
return std::make_pair(
absl::string_view(uri.data(), path.begin() + 1 - uri.begin()),
absl::string_view(path.data() + 1, path.size() - 1));
return std::make_pair(
absl::string_view(uri.data(), path.begin() + pos - uri.begin()),
absl::string_view(path.data() + pos + 1, path.size() - (pos + 1)));
}
std::pair<absl::string_view, absl::string_view> SplitBasename(
absl::string_view path) {
path = Basename(path);
auto pos = path.rfind('.');
if (pos == absl::string_view::npos)
return std::make_pair(path,
absl::string_view(path.data() + path.size(), 0));
return std::make_pair(
absl::string_view(path.data(), pos),
absl::string_view(path.data() + pos + 1, path.size() - (pos + 1)));
}
}
bool IsAbsolutePath(absl::string_view path) {
return !path.empty() && path[0] == '/';
}
absl::string_view Dirname(absl::string_view path) {
return internal::SplitPath(path).first;
}
absl::string_view Basename(absl::string_view path) {
return internal::SplitPath(path).second;
}
absl::string_view Extension(absl::string_view path) {
return internal::SplitBasename(path).second;
}
absl::string_view BasenamePrefix(absl::string_view path) {
return internal::SplitBasename(path).first;
}
string CleanPath(absl::string_view unclean_path) {
string path(unclean_path);
const char* src = path.c_str();
string::iterator dst = path.begin();
const bool is_absolute_path = *src == '/';
if (is_absolute_path) {
*dst++ = *src++;
while (*src == '/') ++src;
}
string::const_iterator backtrack_limit = dst;
while (*src) {
bool parsed = false;
if (src[0] == '.') {
if (src[1] == '/' || !src[1]) {
if (*++src) {
++src;
}
parsed = true;
} else if (src[1] == '.' && (src[2] == '/' || !src[2])) {
src += 2;
if (dst != backtrack_limit) {
for (--dst; dst != backtrack_limit && dst[-1] != '/'; --dst) {
}
} else if (!is_absolute_path) {
src -= 2;
*dst++ = *src++;
*dst++ = *src++;
if (*src) {
*dst++ = *src;
}
backtrack_limit = dst;
}
if (*src) {
++src;
}
parsed = true;
}
}
if (!parsed) {
while (*src && *src != '/') {
*dst++ = *src++;
}
if (*src) {
*dst++ = *src++;
}
}
while (*src == '/') {
++src;
}
}
string::difference_type path_length = dst - path.begin();
if (path_length != 0) {
if (path_length > 1 && path[path_length - 1] == '/') {
--path_length;
}
path.resize(path_length);
} else {
path.assign(1, '.');
}
return path;
}
void ParseURI(absl::string_view uri, absl::string_view* scheme,
absl::string_view* host, absl::string_view* path) {
if (!strings::Scanner(uri)
.One(strings::Scanner::LETTER)
.Many(strings::Scanner::LETTER_DIGIT_DOT)
.StopCapture()
.OneLiteral(":
.GetResult(&uri, scheme)) {
*scheme = absl::string_view(uri.data(), 0);
*host = absl::string_view(uri.data(), 0);
*path = uri;
return;
}
if (!strings::Scanner(uri).ScanUntil('/').GetResult(&uri, host)) {
*host = uri;
*path = absl::string_view();
return;
}
*path = uri;
}
string CreateURI(absl::string_view scheme, absl::string_view host,
absl::string_view path) {
if (scheme.empty()) {
return string(path);
}
return strings::StrCat(scheme, ":
}
int64_t UniqueId() {
static mutex mu(LINKER_INITIALIZED);
static int64_t id = 0;
mutex_lock l(mu);
return ++id;
}
string CommonPathPrefix(absl::Span<const string> paths) {
if (paths.empty()) return "";
size_t min_filename_size =
absl::c_min_element(paths, [](const string& a, const string& b) {
return a.size() < b.size();
})->size();
if (min_filename_size == 0) return "";
size_t common_prefix_size = [&] {
for (size_t prefix_size = 0; prefix_size < min_filename_size;
prefix_size++) {
char c = paths[0][prefix_size];
for (int f = 1; f < paths.size(); f++) {
if (paths[f][prefix_size] != c) {
return prefix_size;
}
}
}
return min_filename_size;
}();
size_t rpos = absl::string_view(paths[0])
.substr(0, common_prefix_size)
.rfind(internal::kPathSep);
return rpos == std::string::npos
? ""
: std::string(absl::string_view(paths[0]).substr(0, rpos + 1));
}
string GetTempFilename(const string& extension) {
#if defined(__ANDROID__)
LOG(FATAL) << "GetTempFilename is not implemented in this platform.";
#elif defined(PLATFORM_WINDOWS)
char temp_dir[_MAX_PATH];
DWORD retval;
retval = GetTempPath(_MAX_PATH, temp_dir);
if (retval > _MAX_PATH || retval == 0) {
LOG(FATAL) << "Cannot get the directory for temporary files.";
}
char temp_file_name[_MAX_PATH];
retval = GetTempFileName(temp_dir, "", UniqueId(), temp_file_name);
if (retval > _MAX_PATH || retval == 0) {
LOG(FATAL) << "Cannot get a temporary file in: " << temp_dir;
}
string full_tmp_file_name(temp_file_name);
full_tmp_file_name.append(extension);
return full_tmp_file_name;
#else
for (const char* dir : std::vector<const char*>(
{getenv("TEST_TMPDIR"), getenv("TMPDIR"), getenv("TMP"), "/tmp"})) {
if (!dir || !dir[0]) {
continue;
}
struct stat statbuf;
if (!stat(dir, &statbuf) && S_ISDIR(statbuf.st_mode)) {
string tmp_filepath;
int fd;
if (extension.length()) {
tmp_filepath = io::JoinPath(
dir, strings::StrCat("tmp_file_tensorflow_", UniqueId(), "_XXXXXX.",
extension));
fd = mkstemps(&tmp_filepath[0], extension.length() + 1);
} else {
tmp_filepath = io::JoinPath(
dir,
strings::StrCat("tmp_file_tensorflow_", UniqueId(), "_XXXXXX"));
fd = mkstemp(&tmp_filepath[0]);
}
if (fd < 0) {
LOG(FATAL) << "Failed to create temp file.";
} else {
if (close(fd) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
return tmp_filepath;
}
}
}
LOG(FATAL) << "No temp directory found.";
std::abort();
#endif
}
namespace {
bool StartsWithSegment(absl::string_view path, absl::string_view segment) {
return absl::StartsWith(path, segment) &&
(path.size() == segment.size() ||
path.at(segment.size()) == internal::kPathSep[0]);
}
}
bool GetTestWorkspaceDir(string* dir) {
const char* srcdir = getenv("TEST_SRCDIR");
if (srcdir == nullptr) {
return false;
}
const char* workspace = getenv("TEST_WORKSPACE");
if (workspace == nullptr) {
return false;
}
if (dir != nullptr) {
*dir = tsl::io::JoinPath(srcdir, workspace);
}
return true;
}
bool GetTestUndeclaredOutputsDir(string* dir) {
const char* outputs_dir = getenv("TEST_UNDECLARED_OUTPUTS_DIR");
if (outputs_dir == nullptr) {
return false;
}
if (dir != nullptr) {
*dir = outputs_dir;
}
return true;
}
bool ResolveTestPrefixes(absl::string_view path, string& resolved_path) {
constexpr absl::string_view kTestWorkspaceSegment = "TEST_WORKSPACE";
constexpr absl::string_view kOutputDirSegment = "TEST_UNDECLARED_OUTPUTS_DIR";
if (StartsWithSegment(path, kTestWorkspaceSegment)) {
if (!GetTestWorkspaceDir(&resolved_path)) {
return false;
}
resolved_path += path.substr(kTestWorkspaceSegment.size());
return true;
} else if (StartsWithSegment(path, kOutputDirSegment)) {
if (!GetTestUndeclaredOutputsDir(&resolved_path)) {
return false;
}
resolved_path += path.substr(kOutputDirSegment.size());
return true;
} else {
resolved_path = path;
return true;
}
}
[[maybe_unused]] std::string& AppendDotExeIfWindows(std::string& path) {
#ifdef PLATFORM_WINDOWS
path.append(".exe");
#endif
return path;
}
}
} | #include "tsl/platform/path.h"
#include <string>
#include "tsl/platform/env.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace io {
TEST(PathTest, JoinPath) {
EXPECT_EQ("/foo/bar", JoinPath("/foo", "bar"));
EXPECT_EQ("foo/bar", JoinPath("foo", "bar"));
EXPECT_EQ("foo/bar", JoinPath("foo", "/bar"));
EXPECT_EQ("/foo/bar", JoinPath("/foo", "/bar"));
EXPECT_EQ("/bar", JoinPath("", "/bar"));
EXPECT_EQ("bar", JoinPath("", "bar"));
EXPECT_EQ("/foo", JoinPath("/foo", ""));
EXPECT_EQ("/foo/bar/baz/blah/blink/biz",
JoinPath("/foo/bar/baz/", "/blah/blink/biz"));
EXPECT_EQ("/foo/bar/baz/blah", JoinPath("/foo", "bar", "baz", "blah"));
}
TEST(PathTest, IsAbsolutePath) {
EXPECT_FALSE(IsAbsolutePath(""));
EXPECT_FALSE(IsAbsolutePath("../foo"));
EXPECT_FALSE(IsAbsolutePath("foo"));
EXPECT_FALSE(IsAbsolutePath("./foo"));
EXPECT_FALSE(IsAbsolutePath("foo/bar/baz/"));
EXPECT_TRUE(IsAbsolutePath("/foo"));
EXPECT_TRUE(IsAbsolutePath("/foo/bar/../baz"));
}
TEST(PathTest, Dirname) {
EXPECT_EQ("hdfs:
Dirname("hdfs:
EXPECT_EQ("/hello", Dirname("/hello/"));
EXPECT_EQ("/", Dirname("/hello"));
EXPECT_EQ("hello", Dirname("hello/world"));
EXPECT_EQ("hello", Dirname("hello/"));
EXPECT_EQ("", Dirname("world"));
EXPECT_EQ("/", Dirname("/"));
EXPECT_EQ("", Dirname(""));
}
TEST(PathTest, Basename) {
EXPECT_EQ("", Basename("/hello/"));
EXPECT_EQ("hello", Basename("/hello"));
EXPECT_EQ("world", Basename("hello/world"));
EXPECT_EQ("", Basename("hello/"));
EXPECT_EQ("world", Basename("world"));
EXPECT_EQ("", Basename("/"));
EXPECT_EQ("", Basename(""));
}
TEST(PathTest, Extension) {
EXPECT_EQ("gif", Extension("foo.gif"));
EXPECT_EQ("", Extension("foo."));
EXPECT_EQ("", Extension(""));
EXPECT_EQ("", Extension("/"));
EXPECT_EQ("", Extension("foo"));
EXPECT_EQ("", Extension("foo/"));
EXPECT_EQ("gif", Extension("/a/path/to/foo.gif"));
EXPECT_EQ("html", Extension("/a/path.bar/to/foo.html"));
EXPECT_EQ("", Extension("/a/path.bar/to/foo"));
EXPECT_EQ("baz", Extension("/a/path.bar/to/foo.bar.baz"));
}
TEST(PathTest, CleanPath) {
EXPECT_EQ(".", CleanPath(""));
EXPECT_EQ("x", CleanPath("x"));
EXPECT_EQ("/a/b/c/d", CleanPath("/a/b/c/d"));
EXPECT_EQ("/a/b/c/dtrue);
tsl::setenv("TEST_WORKSPACE", "my/workspace", true);
EXPECT_TRUE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, "/repo/src/my/workspace");
EXPECT_TRUE(GetTestWorkspaceDir(nullptr));
dir = kOriginalValue;
tsl::unsetenv("TEST_SRCDIR");
tsl::setenv("TEST_WORKSPACE", "my/workspace", true);
EXPECT_FALSE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestWorkspaceDir(nullptr));
dir = kOriginalValue;
tsl::setenv("TEST_SRCDIR", "/repo/src", true);
tsl::unsetenv("TEST_WORKSPACE");
EXPECT_FALSE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestWorkspaceDir(nullptr));
dir = kOriginalValue;
tsl::unsetenv("TEST_SRCDIR");
tsl::unsetenv("TEST_WORKSPACE");
EXPECT_FALSE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestWorkspaceDir(nullptr));
}
TEST(PathTest, GetTestUndeclaredOutputsDir) {
constexpr absl::string_view kOriginalValue = "original value";
std::string dir;
dir = kOriginalValue;
tsl::setenv("TEST_UNDECLARED_OUTPUTS_DIR", "/test/outputs",
true);
EXPECT_TRUE(GetTestUndeclaredOutputsDir(&dir));
EXPECT_EQ(dir, "/test/outputs");
EXPECT_TRUE(GetTestUndeclaredOutputsDir(nullptr));
dir = kOriginalValue;
tsl::unsetenv("TEST_UNDECLARED_OUTPUTS_DIR");
EXPECT_FALSE(GetTestUndeclaredOutputsDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestUndeclaredOutputsDir(nullptr));
}
TEST(PathTest, ResolveTestPrefixesKeepsThePathUnchanged) {
constexpr absl::string_view kOriginalValue = "original value";
std::string resolved_path;
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("", resolved_path));
EXPECT_EQ(resolved_path, "");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("/", resolved_path));
EXPECT_EQ(resolved_path, "/");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("alpha/beta", resolved_path));
EXPECT_EQ(resolved_path, "alpha/beta");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("/alpha/beta", resolved_path));
EXPECT_EQ(resolved_path, "/alpha/beta");
}
TEST(PathTest, ResolveTestPrefixesCanResolveTestWorkspace) {
constexpr absl::string_view kOriginalValue = "original value";
std::string resolved_path;
tsl::setenv("TEST_SRCDIR", "/repo/src", true);
tsl::setenv("TEST_WORKSPACE", "my/workspace", true);
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE", resolved_path));
EXPECT_EQ(resolved_path, "/repo/src/my/workspace");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE/", resolved_path));
EXPECT_EQ(resolved_path, "/repo/src/my/workspace/");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE/a/b", resolved_path));
EXPECT_EQ(resolved_path, "/repo/src/my/workspace/a/b");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACEE", resolved_path));
EXPECT_EQ(resolved_path, "TEST_WORKSPACEE");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("/TEST_WORKSPACE", resolved_path));
EXPECT_EQ(resolved_path, "/TEST_WORKSPACE");
}
TEST(PathTest, ResolveTestPrefixesCannotResolveTestWorkspace) {
constexpr absl::string_view kOriginalValue = "original value";
std::string resolved_path;
tsl::unsetenv("TEST_SRCDIR");
tsl::unsetenv("TEST_WORKSPACE");
resolved_path = kOriginalValue;
EXPECT_FALSE(ResolveTestPrefixes("TEST_WORKSPACE", resolved_path));
EXPECT_EQ(resolved_path, kOriginalValue);
}
TEST(PathTest, ResolveTestPrefixesCanResolveTestUndeclaredOutputsDir) {
constexpr absl::string_view kOriginalValue = "original value";
std::string resolved_path;
tsl::setenv("TEST_UNDECLARED_OUTPUTS_DIR", "/test/outputs",
true);
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR", resolved_path));
EXPECT_EQ(resolved_path, "/test/outputs");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR/", resolved_path));
EXPECT_EQ(resolved_path, "/test/outputs/");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR/a/b", resolved_path));
EXPECT_EQ(resolved_path, "/test/outputs/a/b");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIRR", resolved_path));
EXPECT_EQ(resolved_path, "TEST_UNDECLARED_OUTPUTS_DIRR");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("/TEST_UNDECLARED_OUTPUTS_DIR", resolved_path));
EXPECT_EQ(resolved_path, "/TEST_UNDECLARED_OUTPUTS_DIR");
}
TEST(PathTest, ResolveTestPrefixesCannotResolveTestUndeclaredOutputsDir) {
constexpr absl::string_view kOriginalValue = "original value";
std::string resolved_path;
tsl::unsetenv("TEST_UNDECLARED_OUTPUTS_DIR");
resolved_path = kOriginalValue;
EXPECT_FALSE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR", resolved_path));
EXPECT_EQ(resolved_path, kOriginalValue);
}
}
} | https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/path.cc | https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/path_test.cc | 6d708fdcdd4f40537b7fa273371215a6fa3d4423 |
f3b52274-8026-4ff3-9390-a910d61136c0 | cpp | tensorflow/tensorflow | array_spec | third_party/xla/xla/python/ifrt/array_spec.cc | third_party/xla/xla/python/ifrt/array_spec_test.cc | #include "xla/python/ifrt/array_spec.h"
#include <string>
#include <utility>
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "xla/python/ifrt/array_spec.pb.h"
#include "xla/python/ifrt/device.h"
#include "xla/python/ifrt/dtype.h"
#include "xla/python/ifrt/shape.h"
#include "xla/python/ifrt/sharding.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace ifrt {
absl::StatusOr<ArraySpec> ArraySpec::FromProto(
DeviceList::LookupDeviceFunc lookup_device, const ArraySpecProto& proto) {
TF_ASSIGN_OR_RETURN(auto dtype, DType::FromProto(proto.dtype()));
TF_ASSIGN_OR_RETURN(auto shape, Shape::FromProto(proto.shape()));
TF_ASSIGN_OR_RETURN(auto sharding,
Sharding::FromProto(lookup_device, proto.sharding()));
return ArraySpec{dtype, std::move(shape),
std::move(sharding)};
}
absl::StatusOr<ArraySpecProto> ArraySpec::ToProto() const {
ArraySpecProto proto;
*proto.mutable_dtype() = dtype.ToProto();
*proto.mutable_shape() = shape.ToProto();
TF_ASSIGN_OR_RETURN(*proto.mutable_sharding(), sharding->ToProto());
return proto;
}
std::string ArraySpec::DebugString() const {
return absl::StrCat("ArraySpec(dtype=", dtype.DebugString(),
",shape=", shape.DebugString(),
",sharding=", sharding->DebugString(), ")");
}
}
} | #include "xla/python/ifrt/array_spec.h"
#include <gtest/gtest.h>
#include "absl/status/statusor.h"
#include "llvm/Support/Casting.h"
#include "xla/python/ifrt/array_spec.pb.h"
#include "xla/python/ifrt/device.h"
#include "xla/python/ifrt/device_test_util.h"
#include "xla/python/ifrt/dtype.h"
#include "xla/python/ifrt/memory.h"
#include "xla/python/ifrt/shape.h"
#include "xla/python/ifrt/sharding.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace ifrt {
namespace {
class ArraySpecTest : public test_util::DeviceTest {};
TEST_P(ArraySpecTest, ToFromProto) {
auto device_list = GetDevices({0, 1});
DType dtype(DType::kS32);
Shape shape({4, 2});
Shape shard_shape({2, 2});
ArraySpec spec{dtype, shape,
ConcreteEvenSharding::Create(device_list, MemoryKind(),
shape,
shard_shape)};
auto lookup_device_func = [&](DeviceId device_id) -> absl::StatusOr<Device*> {
return client()->LookupDevice(device_id);
};
TF_ASSERT_OK_AND_ASSIGN(const ArraySpecProto proto, spec.ToProto());
TF_ASSERT_OK_AND_ASSIGN(const ArraySpec array_spec_copy,
ArraySpec::FromProto(lookup_device_func, proto));
EXPECT_EQ(array_spec_copy.dtype, dtype);
EXPECT_EQ(array_spec_copy.shape, shape);
const auto* sharding =
llvm::dyn_cast<ConcreteEvenSharding>(array_spec_copy.sharding.get());
ASSERT_NE(sharding, nullptr);
EXPECT_EQ(*sharding->devices(), *spec.sharding->devices());
EXPECT_EQ(sharding->memory_kind(), spec.sharding->memory_kind());
EXPECT_EQ(sharding->shape(), shape);
EXPECT_EQ(sharding->shard_shape(), shard_shape);
}
INSTANTIATE_TEST_SUITE_P(NumDevices, ArraySpecTest,
testing::Values(test_util::DeviceTestParam{
2,
2}));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/python/ifrt/array_spec.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/python/ifrt/array_spec_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
3b9c8a87-0a4d-43ad-924a-6cf494b4f7e3 | cpp | google/arolla | operator_name | arolla/util/operator_name.h | arolla/util/operator_name_test.cc | #ifndef AROLLA_UTIL_OPERATOR_NAME_H_
#define AROLLA_UTIL_OPERATOR_NAME_H_
#include "absl/strings/string_view.h"
#include "arolla/util/string.h"
namespace arolla {
constexpr bool IsOperatorName(absl::string_view name) {
return IsQualifiedIdentifier(name);
}
#define AROLLA_OPERATOR_NAME(name) \
( \
[]() { \
static_assert(::arolla::IsOperatorName(name), \
"Invalid operator name."); \
}(), \
name)
}
#endif | #include "arolla/util/operator_name.h"
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
namespace arolla {
namespace {
using ::testing::Eq;
using ::testing::StrEq;
TEST(OperatorNameTest, Macro) {
const char* name1 = AROLLA_OPERATOR_NAME("foo.bar");
EXPECT_THAT(name1, StrEq("foo.bar"));
absl::string_view name2 = AROLLA_OPERATOR_NAME("foo.bar");
EXPECT_THAT(name2, Eq("foo.bar"));
std::string name3 = AROLLA_OPERATOR_NAME("foo.bar");
EXPECT_THAT(name1, Eq("foo.bar"));
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/operator_name.h | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/operator_name_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
7dde5b77-37ca-4936-8496-28e66a591fb5 | cpp | tensorflow/tensorflow | buffer_comparator | third_party/xla/xla/service/gpu/buffer_comparator.cc | third_party/xla/xla/service/gpu/buffer_comparator_test.cc | #include "xla/service/gpu/buffer_comparator.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <string_view>
#include <type_traits>
#include <vector>
#include "Eigen/Core"
#include "xla/service/gpu/launch_dimensions.h"
#include "xla/service/hlo_module_config.h"
#include "xla/shape.h"
#include "xla/stream_executor/device_description.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/device_memory_handle.h"
#include "xla/stream_executor/kernel.h"
#include "xla/stream_executor/stream.h"
#include "xla/stream_executor/stream_executor.h"
#include "xla/stream_executor/typed_kernel_factory.h"
#include "xla/util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/ml_dtypes.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
template <typename ElementT>
using ComparisonKernelT =
se::TypedKernel<se::DeviceMemory<ElementT>, se::DeviceMemory<ElementT>,
float, uint64_t, se::DeviceMemory<uint64_t>>;
struct ComparisonParams {
double relative_tol = 0.1;
bool verbose = true;
const Shape* shape = nullptr;
se::Stream* stream = nullptr;
se::DeviceMemoryBase current{};
se::DeviceMemoryBase expected{};
};
template <typename ElementT>
static absl::StatusOr<bool> DeviceCompare(std::string_view kernel_name,
void* kernel_symbol,
const ComparisonParams& params) {
se::StreamExecutor* executor = params.stream->parent();
se::DeviceMemoryHandle out(executor, executor->AllocateScalar<uint64_t>());
TF_RETURN_IF_ERROR(
params.stream->MemZero(out.memory_ptr(), sizeof(uint64_t)));
if (params.current.size() != params.expected.size()) {
return Internal("Mismatched buffer size: %d bytes vs. %d bytes",
params.current.size(), params.expected.size());
}
se::DeviceMemory<ElementT> current_typed(params.current);
se::DeviceMemory<ElementT> expected_typed(params.expected);
uint64_t buffer_size = current_typed.ElementCount();
TF_ASSIGN_OR_RETURN(
ComparisonKernelT<ElementT> comparison_kernel,
(se::TypedKernelFactory<
se::DeviceMemory<ElementT>, se::DeviceMemory<ElementT>, float,
uint64_t, se::DeviceMemory<uint64_t>>::Create(executor, kernel_name,
kernel_symbol)));
const se::DeviceDescription& gpu_device_info =
executor->GetDeviceDescription();
LaunchDimensions dim =
CalculateLaunchDimensions(*params.shape, gpu_device_info);
se::DeviceMemory<uint64_t> as_uint64(out.memory());
TF_RETURN_IF_ERROR(params.stream->ThenLaunch(
dim.thread_counts_per_block(), dim.block_counts(), comparison_kernel,
current_typed, expected_typed, static_cast<float>(params.relative_tol),
buffer_size, as_uint64));
uint64_t result = -1;
CHECK_EQ(out.memory().size(), sizeof(result));
TF_RETURN_IF_ERROR(
params.stream->Memcpy(&result, out.memory(), sizeof(result)));
TF_RETURN_IF_ERROR(params.stream->BlockHostUntilDone());
return result == 0;
}
template <typename ElementType, typename ComparisonType>
static absl::StatusOr<bool> HostCompare(const ComparisonParams& params) {
int64_t n = params.current.size() / sizeof(ElementType);
std::vector<ElementType> host_current(n), host_expected(n);
TF_RETURN_IF_ERROR(params.stream->Memcpy(host_current.data(), params.current,
params.current.size()));
TF_RETURN_IF_ERROR(params.stream->Memcpy(
host_expected.data(), params.expected, params.expected.size()));
TF_RETURN_IF_ERROR(params.stream->BlockHostUntilDone());
const auto canonicalize = [](ComparisonType a) -> ComparisonType {
if (std::is_same<ElementType, Eigen::half>::value && a) {
constexpr ComparisonType kMaxFp16Value = 65505;
if (std::isnan(a)) {
return a;
}
return std::max(-kMaxFp16Value, std::min(a, kMaxFp16Value));
}
return a;
};
int differences_seen = 0;
for (int64_t i = 0; i < n && differences_seen < 10; ++i) {
auto current_value = static_cast<ComparisonType>(host_current[i]);
auto expected_value = static_cast<ComparisonType>(host_expected[i]);
ComparisonType current_value_canonical = canonicalize(current_value);
ComparisonType expected_value_canonical = canonicalize(expected_value);
if (std::isnan(current_value_canonical) &&
std::isnan(expected_value_canonical)) {
continue;
}
if (std::isinf(current_value_canonical) &&
std::isinf(expected_value_canonical) &&
current_value_canonical == expected_value_canonical) {
continue;
}
if (std::isfinite(current_value_canonical) !=
std::isfinite(expected_value_canonical) ||
!(std::abs(current_value_canonical - expected_value_canonical) /
(std::max(std::abs(current_value_canonical),
std::abs(expected_value_canonical)) +
1) <
params.relative_tol)) {
if (!params.verbose) return false;
++differences_seen;
LOG(ERROR) << "Difference at " << i << ": " << current_value
<< ", expected " << expected_value;
}
}
return differences_seen == 0;
}
template <typename ElementT, typename ComparisonT>
static absl::StatusOr<bool> CompareEqualParameterized(
std::string_view kernel_name, void* kernel_symbol,
const ComparisonParams& params) {
XLA_SCOPED_LOGGING_TIMER("BufferComparator::CompareEqual");
TF_ASSIGN_OR_RETURN(
bool result, DeviceCompare<ElementT>(kernel_name, kernel_symbol, params));
if (result) {
return true;
}
TF_ASSIGN_OR_RETURN(bool host_return,
(HostCompare<ElementT, ComparisonT>(params)));
CHECK_EQ(host_return, result)
<< "Host comparison succeeded even though GPU comparison failed.";
return false;
}
absl::StatusOr<bool> BufferComparator::CompareEqual(
se::Stream* stream, se::DeviceMemoryBase current,
se::DeviceMemoryBase expected) const {
ComparisonParams params{relative_tol_, verbose_, &shape_,
stream, current, expected};
switch (shape_.element_type()) {
#if GOOGLE_CUDA
case xla::F8E4M3FN:
return CompareEqualParameterized<tsl::float8_e4m3fn, float>(
"fp8_e4m3fn_comparison", buffer_comparator::fp8_e4m3fn_comparison(),
params);
case xla::F8E5M2:
return CompareEqualParameterized<tsl::float8_e5m2, float>(
"fp8_e5m2_comparison", buffer_comparator::fp8_e5m2_comparison(),
params);
#endif
#if TENSORFLOW_USE_ROCM && TF_ROCM_VERSION >= 60200
case xla::F8E4M3FNUZ:
return CompareEqualParameterized<tsl::float8_e4m3fnuz, float>(
"fp8_e4m3fnuz_comparison",
buffer_comparator::fp8_e4m3fnuz_comparison(), params);
case xla::F8E5M2FNUZ:
return CompareEqualParameterized<tsl::float8_e5m2fnuz, float>(
"fp8_e5m2fnuz_comparison",
buffer_comparator::fp8_e5m2fnuz_comparison(), params);
#endif
case xla::F16:
return CompareEqualParameterized<Eigen::half, float>(
"fp16_comparison", buffer_comparator::fp16_comparison(), params);
case xla::BF16:
return CompareEqualParameterized<Eigen::bfloat16, float>(
"bf16_comparison", buffer_comparator::bf16_comparison(), params);
case xla::F32:
return CompareEqualParameterized<float, float>(
"fp32_comparison", buffer_comparator::fp32_comparison(), params);
case xla::F64:
return CompareEqualParameterized<double, double>(
"fp64_comparison", buffer_comparator::fp64_comparison(), params);
case xla::S8:
return CompareEqualParameterized<int8_t, float>(
"int8_comparison", buffer_comparator::int8_comparison(), params);
case xla::S32:
return CompareEqualParameterized<int32_t, float>(
"int32_comparison", buffer_comparator::int32_comparison(), params);
default:
return Unimplemented("Unimplemented element type");
}
}
BufferComparator::BufferComparator(const Shape& shape, double tolerance,
bool verbose)
: shape_(shape), relative_tol_(tolerance), verbose_(verbose) {
auto double_dim_size = [&]() {
int64_t prev_zero_dim_size = shape_.dimensions(0);
shape_.set_dimensions(0, prev_zero_dim_size * 2);
};
if (shape_.element_type() == PrimitiveType::C64) {
shape_.set_element_type(PrimitiveType::F32);
double_dim_size();
} else if (shape_.element_type() == PrimitiveType::C128) {
shape_.set_element_type(PrimitiveType::F64);
double_dim_size();
}
}
}
} | #include "xla/service/gpu/buffer_comparator.h"
#include <cmath>
#include <complex>
#include <cstdint>
#include <limits>
#include <vector>
#include "xla/primitive_util.h"
#include "xla/service/gpu/stream_executor_util.h"
#include "xla/service/hlo_module_config.h"
#include "xla/shape_util.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/device_memory_handle.h"
#include "xla/stream_executor/platform.h"
#include "xla/stream_executor/platform_manager.h"
#include "xla/stream_executor/stream.h"
#include "xla/types.h"
#include "tsl/platform/ml_dtypes.h"
#include "tsl/platform/status.h"
#include "tsl/platform/test.h"
namespace xla {
namespace gpu {
namespace {
constexpr double kDefaultTolerance = 0.1;
class BufferComparatorTest : public testing::Test {
protected:
BufferComparatorTest()
#if GOOGLE_CUDA
: platform_(se::PlatformManager::PlatformWithName("CUDA").value()),
#elif TENSORFLOW_USE_ROCM
: platform_(se::PlatformManager::PlatformWithName("ROCM").value()),
#endif
stream_exec_(platform_->ExecutorForDevice(0).value()) {
}
template <typename ElementType>
bool CompareEqualBuffers(const std::vector<ElementType>& current,
const std::vector<ElementType>& expected,
double tolerance) {
auto stream = stream_exec_->CreateStream().value();
se::DeviceMemoryHandle current_buffer(
stream_exec_, stream_exec_->AllocateArray<ElementType>(current.size()));
se::DeviceMemoryHandle expected_buffer(
stream_exec_,
stream_exec_->AllocateArray<ElementType>(expected.size()));
TF_CHECK_OK(stream->Memcpy(current_buffer.memory_ptr(), current.data(),
current_buffer.memory().size()));
TF_CHECK_OK(stream->Memcpy(expected_buffer.memory_ptr(), expected.data(),
expected_buffer.memory().size()));
TF_CHECK_OK(stream->BlockHostUntilDone());
BufferComparator comparator(
ShapeUtil::MakeShape(
primitive_util::NativeToPrimitiveType<ElementType>(),
{static_cast<int64_t>(current.size())}),
tolerance);
return comparator
.CompareEqual(stream.get(), current_buffer.memory(),
expected_buffer.memory())
.value();
}
template <typename ElementType>
bool CompareEqualFloatBuffers(const std::vector<float>& lhs_float,
const std::vector<float>& rhs_float,
double tolerance = kDefaultTolerance) {
std::vector<ElementType> lhs(lhs_float.begin(), lhs_float.end());
std::vector<ElementType> rhs(rhs_float.begin(), rhs_float.end());
return CompareEqualBuffers(lhs, rhs, tolerance);
}
template <typename ElementType>
bool CompareEqualComplex(const std::vector<std::complex<ElementType>>& lhs,
const std::vector<std::complex<ElementType>>& rhs) {
return CompareEqualBuffers<std::complex<ElementType>>(lhs, rhs,
kDefaultTolerance);
}
se::Platform* platform_;
se::StreamExecutor* stream_exec_;
};
TEST_F(BufferComparatorTest, TestComplex) {
EXPECT_FALSE(
CompareEqualComplex<float>({{0.1, 0.2}, {2, 3}}, {{0.1, 0.2}, {6, 7}}));
EXPECT_TRUE(CompareEqualComplex<float>({{0.1, 0.2}, {2, 3}},
{{0.1, 0.2}, {2.2, 3.3}}));
EXPECT_TRUE(
CompareEqualComplex<float>({{0.1, 0.2}, {2, 3}}, {{0.1, 0.2}, {2, 3}}));
EXPECT_FALSE(
CompareEqualComplex<float>({{0.1, 0.2}, {2, 3}}, {{0.1, 0.2}, {6, 3}}));
EXPECT_FALSE(
CompareEqualComplex<float>({{0.1, 0.2}, {2, 3}}, {{0.1, 0.2}, {6, 7}}));
EXPECT_FALSE(
CompareEqualComplex<float>({{0.1, 0.2}, {2, 3}}, {{0.1, 6}, {2, 3}}));
EXPECT_TRUE(CompareEqualComplex<double>({{0.1, 0.2}, {2, 3}},
{{0.1, 0.2}, {2.2, 3.3}}));
EXPECT_FALSE(
CompareEqualComplex<double>({{0.1, 0.2}, {2, 3}}, {{0.1, 0.2}, {2, 7}}));
}
TEST_F(BufferComparatorTest, TestNaNs) {
EXPECT_TRUE(
CompareEqualFloatBuffers<Eigen::half>({std::nanf("")}, {std::nanf("")}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({std::nanf("")},
{std::nanf("1234")}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({std::nanf("")}, {1.}));
EXPECT_TRUE(
CompareEqualFloatBuffers<float>({std::nanf("")}, {std::nanf("")}));
EXPECT_TRUE(
CompareEqualFloatBuffers<float>({std::nanf("")}, {std::nanf("1234")}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({std::nanf("")}, {1.}));
EXPECT_TRUE(
CompareEqualFloatBuffers<double>({std::nanf("")}, {std::nanf("")}));
EXPECT_TRUE(
CompareEqualFloatBuffers<double>({std::nanf("")}, {std::nanf("1234")}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({std::nanf("")}, {1.}));
}
TEST_F(BufferComparatorTest, TestInfs) {
const auto inf = std::numeric_limits<float>::infinity();
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({inf}, {std::nanf("")}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({inf}, {inf}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({inf}, {65504}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({-inf}, {-65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({inf}, {-65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({-inf}, {65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({inf}, {-20}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({-inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({-inf}, {-20}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({inf}, {std::nanf("")}));
EXPECT_TRUE(CompareEqualFloatBuffers<float>({inf}, {inf}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({inf}, {65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({-inf}, {-65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({inf}, {-65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({-inf}, {65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({inf}, {-20}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({-inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({-inf}, {-20}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({inf}, {std::nanf("")}));
EXPECT_TRUE(CompareEqualFloatBuffers<double>({inf}, {inf}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({inf}, {65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({-inf}, {-65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({inf}, {-65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({-inf}, {65504}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({inf}, {-20}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({-inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({-inf}, {-20}));
#if GOOGLE_CUDA
EXPECT_TRUE(
CompareEqualFloatBuffers<tsl::float8_e4m3fn>({inf}, {std::nanf("")}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({inf}, {inf}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({inf}, {-inf}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({inf}, {448}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({inf}, {-448}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({inf}, {-20}));
EXPECT_FALSE(
CompareEqualFloatBuffers<tsl::float8_e5m2>({inf}, {std::nanf("")}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>({inf}, {inf}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({inf}, {-inf}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({inf}, {57344}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({-inf}, {-57344}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({inf}, {-20}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({-inf}, {20}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({-inf}, {-20}));
#endif
}
TEST_F(BufferComparatorTest, TestNumbers) {
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({20}, {20.1}));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({20}, {23.0}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({20}, {23.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({20}, {26.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({0}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({0.9}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({9}, {10}));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({10}, {9}));
EXPECT_TRUE(CompareEqualFloatBuffers<float>({20}, {20.1}));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({20}, {23.0}));
EXPECT_TRUE(CompareEqualFloatBuffers<float>({20}, {23.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({20}, {26.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({0}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<float>({0.9}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<float>({9}, {10}));
EXPECT_TRUE(CompareEqualFloatBuffers<float>({10}, {9}));
EXPECT_TRUE(CompareEqualFloatBuffers<double>({20}, {20.1}));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({20}, {23.0}));
EXPECT_TRUE(CompareEqualFloatBuffers<double>({20}, {23.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({20}, {26.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({0}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<double>({0.9}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<double>({9}, {10}));
EXPECT_TRUE(CompareEqualFloatBuffers<double>({10}, {9}));
EXPECT_TRUE(CompareEqualFloatBuffers<int8_t>({100}, {101}));
EXPECT_FALSE(CompareEqualFloatBuffers<int8_t>({100}, {120}));
EXPECT_TRUE(CompareEqualFloatBuffers<int8_t>({100}, {120}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<int8_t>({90}, {120}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<int8_t>({0}, {10}));
EXPECT_TRUE(CompareEqualFloatBuffers<int8_t>({9}, {10}));
EXPECT_TRUE(CompareEqualFloatBuffers<int8_t>({90}, {100}));
EXPECT_TRUE(CompareEqualFloatBuffers<int8_t>({100}, {90}));
EXPECT_FALSE(CompareEqualFloatBuffers<int8_t>({-128}, {127}));
#if GOOGLE_CUDA
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({20}, {20.1}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({20}, {23.0}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({20}, {23.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({20}, {26.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({0}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({0.9}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({9}, {10}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>({9}, {10}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>({20}, {20.1}));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({20}, {23.0}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>({20}, {23.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({20}, {30.0}, 0.2));
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>({0}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>({0.9}, {1}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>({11}, {12}));
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>({12}, {11}));
#endif
const double tol = 0.001;
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>({0.9}, {1}, tol));
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>({0.9}, {0.901}, tol));
EXPECT_FALSE(CompareEqualFloatBuffers<float>({10}, {10.1}, tol));
EXPECT_TRUE(CompareEqualFloatBuffers<float>({10}, {10.01}, tol));
EXPECT_FALSE(CompareEqualFloatBuffers<int8_t>({100}, {101}, tol));
EXPECT_FALSE(CompareEqualFloatBuffers<double>({20}, {20.1}, tol));
EXPECT_TRUE(CompareEqualFloatBuffers<double>({20}, {20.01}, tol));
}
TEST_F(BufferComparatorTest, TestMultiple) {
{
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>(
{20, 30, 40, 50, 60}, {20.1, 30.1, 40.1, 50.1, 60.1}));
std::vector<float> lhs(200);
std::vector<float> rhs(200);
for (int i = 0; i < 200; i++) {
EXPECT_TRUE(CompareEqualFloatBuffers<Eigen::half>(lhs, rhs))
<< "should be the same at index " << i;
lhs[i] = 3;
rhs[i] = 5;
EXPECT_FALSE(CompareEqualFloatBuffers<Eigen::half>(lhs, rhs))
<< "should be the different at index " << i;
lhs[i] = 0;
rhs[i] = 0;
}
}
{
EXPECT_TRUE(CompareEqualFloatBuffers<float>(
{20, 30, 40, 50, 60}, {20.1, 30.1, 40.1, 50.1, 60.1}));
std::vector<float> lhs(200);
std::vector<float> rhs(200);
for (int i = 0; i < 200; i++) {
EXPECT_TRUE(CompareEqualFloatBuffers<float>(lhs, rhs))
<< "should be the same at index " << i;
lhs[i] = 3;
rhs[i] = 5;
EXPECT_FALSE(CompareEqualFloatBuffers<float>(lhs, rhs))
<< "should be the different at index " << i;
lhs[i] = 0;
rhs[i] = 0;
}
}
{
EXPECT_TRUE(CompareEqualFloatBuffers<double>(
{20, 30, 40, 50, 60}, {20.1, 30.1, 40.1, 50.1, 60.1}));
std::vector<float> lhs(200);
std::vector<float> rhs(200);
for (int i = 0; i < 200; i++) {
EXPECT_TRUE(CompareEqualFloatBuffers<double>(lhs, rhs))
<< "should be the same at index " << i;
lhs[i] = 3;
rhs[i] = 5;
EXPECT_FALSE(CompareEqualFloatBuffers<double>(lhs, rhs))
<< "should be the different at index " << i;
lhs[i] = 0;
rhs[i] = 0;
}
}
{
EXPECT_TRUE(CompareEqualFloatBuffers<int8_t>({20, 30, 40, 50, 60},
{21, 31, 41, 51, 61}));
std::vector<float> lhs(200);
std::vector<float> rhs(200);
for (int i = 0; i < 200; i++) {
EXPECT_TRUE(CompareEqualFloatBuffers<int8_t>(lhs, rhs))
<< "should be the same at index " << i;
lhs[i] = 3;
rhs[i] = 5;
EXPECT_FALSE(CompareEqualFloatBuffers<int8_t>(lhs, rhs))
<< "should be the different at index " << i;
lhs[i] = 0;
rhs[i] = 0;
}
}
#if GOOGLE_CUDA
{
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>(
{20, 30, 40, 50, 60}, {20.1, 30.1, 40.1, 50.1, 60.1}));
std::vector<float> lhs(200);
std::vector<float> rhs(200);
for (int i = 0; i < 200; i++) {
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>(lhs, rhs))
<< "should be the same at index " << i;
lhs[i] = 3;
rhs[i] = 5;
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e4m3fn>(lhs, rhs))
<< "should be the different at index " << i;
lhs[i] = 0;
rhs[i] = 0;
}
}
{
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>(
{20, 30, 40, 50, 60}, {20.1, 30.1, 40.1, 50.1, 60.1}));
std::vector<float> lhs(200);
std::vector<float> rhs(200);
for (int i = 0; i < 200; i++) {
EXPECT_TRUE(CompareEqualFloatBuffers<tsl::float8_e5m2>(lhs, rhs))
<< "should be the same at index " << i;
lhs[i] = 3;
rhs[i] = 5;
EXPECT_FALSE(CompareEqualFloatBuffers<tsl::float8_e5m2>(lhs, rhs))
<< "should be the different at index " << i;
lhs[i] = 0;
rhs[i] = 0;
}
}
#endif
}
TEST_F(BufferComparatorTest, BF16) {
const int element_count = 3123;
int64_t rng_state = 0;
auto stream = stream_exec_->CreateStream().value();
se::DeviceMemoryHandle lhs(
stream_exec_,
stream_exec_->AllocateArray<Eigen::bfloat16>(element_count));
InitializeBuffer(stream.get(), BF16, &rng_state, lhs.memory());
se::DeviceMemoryHandle rhs(
stream_exec_,
stream_exec_->AllocateArray<Eigen::bfloat16>(element_count));
InitializeBuffer(stream.get(), BF16, &rng_state, rhs.memory());
BufferComparator comparator(ShapeUtil::MakeShape(BF16, {element_count}));
EXPECT_FALSE(comparator.CompareEqual(stream.get(), lhs.memory(), rhs.memory())
.value());
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/buffer_comparator.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/buffer_comparator_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
321442fe-b4d4-4301-bf31-494056f960f8 | cpp | tensorflow/tensorflow | host_callback | third_party/xla/xla/python/ifrt/host_callback.cc | third_party/xla/xla/pjrt/host_callback_test.cc | #include "xla/python/ifrt/host_callback.h"
namespace xla {
namespace ifrt {
char HostCallback::ID = 0;
char LoadedHostCallback::ID = 0;
}
} | #include "xla/pjrt/host_callback.h"
#include <cstring>
#include <memory>
#include <utility>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tsl/lib/core/status_test_util.h"
namespace xla {
namespace {
class TestPjRtHostMemoryForDeviceManager
: public PjRtHostMemoryForDeviceManager {
public:
~TestPjRtHostMemoryForDeviceManager() override = default;
absl::StatusOr<PjRtChunk> ToDeviceLayout(const void* src_data,
size_t src_size,
const Shape& host_shape,
const Shape& device_shape) override {
auto chunk = PjRtChunk::AllocateDefault(src_size);
std::memcpy(chunk.data(), src_data, src_size);
return chunk;
}
absl::Status ToHostLayout(const void* src_data, size_t src_size,
const Shape& src_shape, void* dst_data,
size_t dst_size, const Shape& dst_shape) override {
CHECK_EQ(src_size, dst_size);
std::memcpy(dst_data, src_data, src_size);
return absl::OkStatus();
}
};
class TestStream : public CopyToDeviceStream {
public:
TestStream(int64_t total_bytes, int64_t granule_bytes, PjRtChunk& chunk,
absl::Notification& done)
: CopyToDeviceStream(total_bytes, granule_bytes),
chunk_(chunk),
done_(done) {}
PjRtFuture<> AddChunk(PjRtChunk chunk) override {
CHECK(!done_.HasBeenNotified());
chunk_ = std::move(chunk);
done_.Notify();
return PjRtFuture<>(absl::OkStatus());
}
private:
PjRtChunk& chunk_;
absl::Notification& done_;
};
TEST(HostCallbackTest, Basic) {
HostCallback host_callback;
Shape shape = ShapeUtil::MakeShape(F32, {2, 2});
size_t byte_size = ShapeUtil::ByteSizeOf(shape);
host_callback.operands = {HostCallbackArgInfo{1, shape}};
host_callback.results = {HostCallbackArgInfo{2, shape}};
host_callback.callback = [byte_size](void** outputs, void** inputs) {
std::memcpy(outputs[0], inputs[0], byte_size);
return absl::OkStatus();
};
HostCallbackStates states;
auto& send_callbacks = states.send_callbacks.emplace_back();
auto& recv_callbacks = states.recv_callbacks.emplace_back();
TestPjRtHostMemoryForDeviceManager test_host_memory_for_device_manager;
auto context = CreateHostCallbackStateAndAppendSendRecvCallbacks(
std::move(host_callback), &test_host_memory_for_device_manager,
send_callbacks, recv_callbacks,
false);
PjRtTransferMetadata metadata;
metadata.device_shape = shape;
auto literal = LiteralUtil::CreateR2({{1.0f, 2.0f}, {3.0f, 4.0f}});
auto chunk = PjRtChunk::AllocateDefault(byte_size);
ASSERT_EQ(chunk.size(), literal.size_bytes());
std::memcpy(chunk.data(), literal.untyped_data(), literal.size_bytes());
TF_ASSERT_OK(context->OnSend(0, metadata, std::move(chunk)));
PjRtChunk received_chunk;
absl::Notification done;
auto stream = std::make_unique<TestStream>(byte_size, 8,
received_chunk, done);
context->Receive(0, metadata, std::move(stream));
done.WaitForNotification();
BorrowingLiteral borrowing_literal(
reinterpret_cast<const char*>(received_chunk.data()), shape);
EXPECT_TRUE(LiteralTestUtil::Equal(literal, borrowing_literal));
}
TEST(HostCallbackTest, NonBlockingRecv) {
HostCallback host_callback;
Shape shape = ShapeUtil::MakeShape(F32, {2, 2});
size_t byte_size = ShapeUtil::ByteSizeOf(shape);
host_callback.operands = {HostCallbackArgInfo{1, shape}};
host_callback.results = {HostCallbackArgInfo{2, shape}};
host_callback.callback = [byte_size](void** outputs, void** inputs) {
std::memcpy(outputs[0], inputs[0], byte_size);
return absl::OkStatus();
};
HostCallbackStates states;
auto& send_callbacks = states.send_callbacks.emplace_back();
auto& recv_callbacks = states.recv_callbacks.emplace_back();
TestPjRtHostMemoryForDeviceManager test_host_memory_for_device_manager;
auto context = CreateHostCallbackStateAndAppendSendRecvCallbacks(
std::move(host_callback), &test_host_memory_for_device_manager,
send_callbacks, recv_callbacks,
false);
PjRtTransferMetadata metadata;
metadata.device_shape = shape;
auto literal = LiteralUtil::CreateR2({{1.0f, 2.0f}, {3.0f, 4.0f}});
auto chunk = PjRtChunk::AllocateDefault(byte_size);
ASSERT_EQ(chunk.size(), literal.size_bytes());
std::memcpy(chunk.data(), literal.untyped_data(), literal.size_bytes());
absl::Notification done;
PjRtChunk received_chunk;
auto stream = std::make_unique<TestStream>(byte_size, 8,
received_chunk, done);
context->Receive(0, metadata, std::move(stream));
TF_ASSERT_OK(context->OnSend(0, metadata, std::move(chunk)));
done.WaitForNotification();
BorrowingLiteral borrowing_literal(
reinterpret_cast<const char*>(received_chunk.data()), shape);
EXPECT_TRUE(LiteralTestUtil::Equal(literal, borrowing_literal));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/python/ifrt/host_callback.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/pjrt/host_callback_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
e9777cc8-9c3a-4a56-9982-bde1e1df8706 | cpp | google/arolla | compile_std_function_operator | arolla/expr/eval/compile_std_function_operator.cc | arolla/expr/eval/compile_std_function_operator_test.cc | #include "arolla/expr/eval/compile_std_function_operator.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "absl/types/span.h"
#include "arolla/expr/eval/executable_builder.h"
#include "arolla/expr/expr_node.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/expr/operators/std_function_operator.h"
#include "arolla/memory/frame.h"
#include "arolla/qexpr/bound_operators.h"
#include "arolla/qexpr/eval_context.h"
#include "arolla/qtype/typed_ref.h"
#include "arolla/qtype/typed_slot.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr::eval_internal {
absl::Status CompileStdFunctionOperator(
const expr_operators::StdFunctionOperator& std_function_op,
absl::Span<const TypedSlot> input_slots, TypedSlot output_slot,
ExecutableBuilder& executable_builder, ExprNodePtr node) {
RETURN_IF_ERROR(ValidateDepsCount(std_function_op.signature(),
input_slots.size(),
absl::StatusCode::kFailedPrecondition));
auto fn = std_function_op.GetEvalFn();
int64_t ip = executable_builder.AddEvalOp(
MakeBoundOperator([fn, output_slot,
input_slots = std::vector(input_slots.begin(),
input_slots.end())](
EvaluationContext* ctx, FramePtr frame) {
std::vector<TypedRef> inputs;
inputs.reserve(input_slots.size());
for (const auto input_slot : input_slots) {
inputs.push_back(TypedRef::FromSlot(input_slot, frame));
}
ASSIGN_OR_RETURN(auto res, fn(inputs), ctx->set_status(std::move(_)));
if (res.GetType() != output_slot.GetType()) {
ctx->set_status(absl::InvalidArgumentError(absl::StrFormat(
"expected the result to have qtype %s, got %s",
output_slot.GetType()->name(), res.GetType()->name())));
return;
}
ctx->set_status(res.CopyToSlot(output_slot, frame));
}),
FormatOperatorCall(std_function_op.display_name(), input_slots,
{output_slot}),
std::string(std_function_op.display_name()));
executable_builder.RegisterStacktrace(ip, node);
return absl::OkStatus();
}
} | #include <cstdint>
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "arolla/expr/eval/eval.h"
#include "arolla/expr/eval/invoke.h"
#include "arolla/expr/eval/test_utils.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/expr/lambda_expr_operator.h"
#include "arolla/expr/operators/std_function_operator.h"
#include "arolla/memory/frame.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/qtype/testing/qtype.h"
#include "arolla/qtype/typed_ref.h"
#include "arolla/qtype/typed_value.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr::eval_internal {
namespace {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::arolla::testing::TypedValueWith;
using ::testing::AllOf;
using ::testing::Eq;
class StdFunctionOperatorTest
: public ::testing::TestWithParam<DynamicEvaluationEngineOptions> {
protected:
DynamicEvaluationEngineOptions GetOptions() const { return GetParam(); }
};
absl::StatusOr<TypedValue> Add(absl::Span<const TypedRef> inputs) {
ASSIGN_OR_RETURN(int32_t x, inputs[0].As<int32_t>());
ASSIGN_OR_RETURN(int64_t y, inputs[1].As<int64_t>());
double z = 3.0;
return TypedValue::FromValue(x + y + z);
}
INSTANTIATE_TEST_SUITE_P(
GarbageCollection, StdFunctionOperatorTest,
::testing::Values(
DynamicEvaluationEngineOptions{.collect_op_descriptions = true,
.allow_overriding_input_slots = false},
DynamicEvaluationEngineOptions{.collect_op_descriptions = true,
.allow_overriding_input_slots = true}));
TEST_P(StdFunctionOperatorTest, SimpleFn) {
auto op = std::make_shared<expr_operators::StdFunctionOperator>(
"add", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring",
[](absl::Span<const QTypePtr> input_qtypes) {
return GetQType<double>();
},
Add);
ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")}));
FrameLayout::Builder layout_builder;
expr::DynamicEvaluationEngineOptions options;
options.collect_op_descriptions = true;
auto x_slot = layout_builder.AddSlot<int32_t>();
auto y_slot = layout_builder.AddSlot<int64_t>();
EXPECT_THAT(expr::CompileAndBindForDynamicEvaluation(
options, &layout_builder, expr,
{{"x", TypedSlot::FromSlot(x_slot)},
{"y", TypedSlot::FromSlot(y_slot)}}),
IsOkAndHolds(AllOf(
InitOperationsAre(),
EvalOperationsAre(
"FLOAT64 [0x10] = add(INT32 [0x00], INT64 [0x08])"))));
EXPECT_THAT(Invoke(expr,
{{"x", TypedValue::FromValue(1)},
{"y", TypedValue::FromValue(int64_t{2})}},
GetOptions()),
IsOkAndHolds(TypedValueWith<double>(Eq(6.0))));
}
TEST_F(StdFunctionOperatorTest, StackTraceTest) {
auto error_op = std::make_shared<expr_operators::StdFunctionOperator>(
"error_op", ExprOperatorSignature{}, "dummy op docstring",
[](absl::Span<const QTypePtr> input_qtypes) {
return GetQType<double>();
},
[](absl::Span<const TypedRef> refs) -> absl::StatusOr<TypedValue> {
return absl::InternalError("Error from StdFunctionOperator");
});
ASSERT_OK_AND_ASSIGN(
auto error_lambda,
MakeLambdaOperator("error_lambda", ExprOperatorSignature{},
CallOp(error_op, {})));
ASSERT_OK_AND_ASSIGN(auto expr, CallOp(error_lambda, {}));
FrameLayout::Builder layout_builder;
expr::DynamicEvaluationEngineOptions options{.enable_expr_stack_trace = true};
EXPECT_THAT(expr::CompileAndBindForDynamicEvaluation(options, &layout_builder,
expr, {}),
StatusIs(absl::StatusCode::kInternal,
"Error from StdFunctionOperator; "
"during evaluation of operator error_op\n"
"ORIGINAL NODE: error_lambda():FLOAT64\n"
"COMPILED NODE: error_op():FLOAT64; while doing literal"
" folding; while transforming error_lambda():FLOAT64"));
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/eval/compile_std_function_operator.cc | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/eval/compile_std_function_operator_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
c721eaba-76e8-4a86-a444-76fea2575e91 | cpp | tensorflow/tensorflow | custom_call_target_registry | third_party/xla/xla/service/custom_call_target_registry.cc | third_party/xla/xla/service/custom_call_target_registry_test.cc | #include "xla/service/custom_call_target_registry.h"
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
namespace xla {
CustomCallTargetRegistry* CustomCallTargetRegistry::Global() {
static auto* registry = new CustomCallTargetRegistry;
return registry;
}
void CustomCallTargetRegistry::Register(const std::string& symbol,
void* address,
const std::string& platform) {
std::lock_guard<std::mutex> lock(mu_);
const auto [it, inserted] =
registered_symbols_.insert({{symbol, platform}, address});
if (!inserted && it->second != address) {
std::cerr << "Duplicate custom call registration detected for symbol \""
<< symbol << "\" with different addresses " << address
<< "(current) and " << it->second << " (previous) on platform "
<< platform
<< "Rejecting the registration to avoid confusion about which "
"symbol would actually get used at runtime.\n";
std::exit(1);
}
}
void* CustomCallTargetRegistry::Lookup(const std::string& symbol,
const std::string& platform) const {
std::lock_guard<std::mutex> lock(mu_);
auto it = registered_symbols_.find(std::make_pair(symbol, platform));
return it == registered_symbols_.end() ? nullptr : it->second;
}
std::unordered_map<std::string, void*>
CustomCallTargetRegistry::registered_symbols(
const std::string& platform) const {
std::unordered_map<std::string, void*> calls;
std::lock_guard<std::mutex> lock(mu_);
for (const auto& [metadata, address] : registered_symbols_) {
if (metadata.second == platform) {
calls[metadata.first] = address;
}
}
return calls;
}
} | #include "xla/service/custom_call_target_registry.h"
#include "xla/service/custom_call_status.h"
#include "xla/test.h"
namespace xla {
namespace {
using ::testing::_;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
void custom_call(void*, const void**, XlaCustomCallStatus*) {}
void custom_call2(void*, const void**, XlaCustomCallStatus*) {}
TEST(CustomCallRegistryTest, Registers) {
CustomCallTargetRegistry registry;
EXPECT_EQ(registry.Lookup("custom_call", "Host"), nullptr);
registry.Register("custom_call", reinterpret_cast<void*>(custom_call),
"Host");
EXPECT_EQ(custom_call, registry.Lookup("custom_call", "Host"));
registry.Register("custom_call2", reinterpret_cast<void*>(&custom_call),
"Host");
EXPECT_EQ(registry.Lookup("custom_call", "CUDA"), nullptr);
registry.Register("custom_call", reinterpret_cast<void*>(custom_call),
"CUDA");
EXPECT_EQ(custom_call, registry.Lookup("custom_call", "CUDA"));
registry.Register("custom_call", reinterpret_cast<void*>(custom_call),
"Host");
EXPECT_THAT(
registry.registered_symbols("Host"),
UnorderedElementsAre(Pair("custom_call", _), Pair("custom_call2", _)));
EXPECT_THAT(registry.registered_symbols("CUDA"),
UnorderedElementsAre(Pair("custom_call", _)));
}
TEST(CustomCallRegistryDeathTest, RejectsDuplicateRegistrations) {
CustomCallTargetRegistry registry;
registry.Register("custom_call", reinterpret_cast<void*>(custom_call),
"Host");
EXPECT_DEATH(registry.Register("custom_call",
reinterpret_cast<void*>(custom_call2), "Host"),
"Duplicate custom call");
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/custom_call_target_registry.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/custom_call_target_registry_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
a907909a-7bf7-4305-a605-0a452f58af0a | cpp | tensorflow/tensorflow | sampling_dataset_op | tensorflow/core/kernels/data/experimental/sampling_dataset_op.cc | tensorflow/core/kernels/data/experimental/sampling_dataset_op_test.cc | #include "tensorflow/core/kernels/data/experimental/sampling_dataset_op.h"
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/lib/random/random_distributions.h"
#include "tensorflow/core/lib/random/simple_philox.h"
namespace tensorflow {
namespace data {
namespace experimental {
constexpr const char* const SamplingDatasetOp::kDatasetType;
constexpr const char* const SamplingDatasetOp::kInputDataset;
constexpr const char* const SamplingDatasetOp::kRate;
constexpr const char* const SamplingDatasetOp::kSeed;
constexpr const char* const SamplingDatasetOp::kSeed2;
constexpr const char* const SamplingDatasetOp::kOutputTypes;
constexpr const char* const SamplingDatasetOp::kOutputShapes;
class SamplingDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, float rate, int64_t seed, int64_t seed2,
const DatasetBase* input)
: DatasetBase(DatasetContext(ctx)),
rate_(rate),
seeds_(seed, seed2),
input_(input) {
input_->Ref();
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, name_utils::IteratorPrefix(kDatasetType, prefix)},
seeds_.first, seeds_.second));
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return input_->output_shapes();
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(input_);
return absl::OkStatus();
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* rate = nullptr;
Node* seed = nullptr;
Node* seed2 = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(rate_, &rate));
TF_RETURN_IF_ERROR(b->AddScalar(seeds_.first, &seed));
TF_RETURN_IF_ERROR(b->AddScalar(seeds_.second, &seed2));
TF_RETURN_IF_ERROR(
b->AddDataset(this, {input_graph_node, rate, seed, seed2}, output));
return absl::OkStatus();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params, int64_t seed, int64_t seed2)
: DatasetIterator<Dataset>(params),
seeds_(MaybeOverrideSeeds({seed, seed2})),
parent_generator_(seeds_.first, seeds_.second),
generator_(&parent_generator_) {}
Status Initialize(IteratorContext* ctx) override {
return dataset()->input_->MakeIterator(ctx, this, prefix(), &input_impl_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
bool rand_val_hit;
do {
{
tf_shared_lock l(mu_);
if (!input_impl_) {
*end_of_sequence = true;
return absl::OkStatus();
}
TF_RETURN_IF_ERROR(
input_impl_->GetNext(ctx, out_tensors, end_of_sequence));
}
if (*end_of_sequence) {
mutex_lock l(mu_);
input_impl_.reset();
return absl::OkStatus();
}
float rand_val = Random();
rand_val_hit = rand_val < dataset()->rate_;
if (!rand_val_hit) {
out_tensors->clear();
}
} while (!rand_val_hit);
*end_of_sequence = false;
return absl::OkStatus();
}
protected:
void ResetRngs() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
parent_generator_ = random::PhiloxRandom(seeds_.first, seeds_.second);
generator_ =
random::SingleSampleAdapter<random::PhiloxRandom>(&parent_generator_);
generator_.Skip(num_random_samples_);
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(
this->full_name("num_random_samples"), num_random_samples_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(this->full_name("seed"), seeds_.first));
TF_RETURN_IF_ERROR(
writer->WriteScalar(this->full_name("seed2"), seeds_.second));
if (input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
}
return absl::OkStatus();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(reader->ReadScalar(
this->full_name("num_random_samples"), &num_random_samples_));
int64_t seed;
TF_RETURN_IF_ERROR(reader->ReadScalar(this->full_name("seed"), &seed));
int64_t seed2;
TF_RETURN_IF_ERROR(reader->ReadScalar(this->full_name("seed2"), &seed2));
seeds_ = {seed, seed2};
ResetRngs();
if (!reader->Contains(full_name("input_impl_empty"))) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
return absl::OkStatus();
}
mutex mu_;
std::pair<int64_t, int64_t> seeds_ TF_GUARDED_BY(mu_);
private:
std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_);
float Random() {
mutex_lock l(mu_);
num_random_samples_++;
uint32 random_uint = generator_();
return random::Uint32ToFloat(random_uint);
}
random::PhiloxRandom parent_generator_ TF_GUARDED_BY(mu_);
random::SingleSampleAdapter<random::PhiloxRandom> generator_
TF_GUARDED_BY(mu_);
int64_t num_random_samples_ TF_GUARDED_BY(mu_) = 0;
};
const float rate_;
const std::pair<int64_t, int64_t> seeds_;
const DatasetBase* const input_;
};
SamplingDatasetOp::SamplingDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void SamplingDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
float rate;
int64_t seed;
int64_t seed2;
OP_REQUIRES_OK(ctx, ParseScalarArgument<float>(ctx, kRate, &rate));
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64_t>(ctx, kSeed, &seed));
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64_t>(ctx, kSeed2, &seed2));
*output = new Dataset(ctx, rate, seed, seed2, input);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("SamplingDataset").Device(DEVICE_CPU),
SamplingDatasetOp);
}
}
}
} | #include "tensorflow/core/kernels/data/experimental/sampling_dataset_op.h"
#include "tensorflow/core/data/dataset_test_base.h"
namespace tensorflow {
namespace data {
namespace experimental {
namespace {
constexpr char kNodeName[] = "sampling_dataset";
constexpr int64_t kRandomSeed = 42;
constexpr int64_t kRandomSeed2 = 7;
class SamplingDatasetParams : public DatasetParams {
public:
template <typename T>
SamplingDatasetParams(T input_dataset_params, float rate,
DataTypeVector output_dtypes,
std::vector<PartialTensorShape> output_shapes,
string node_name)
: DatasetParams(std::move(output_dtypes), std::move(output_shapes),
std::move(node_name)),
rate_(rate) {
input_dataset_params_.push_back(std::make_unique<T>(input_dataset_params));
iterator_prefix_ =
name_utils::IteratorPrefix(input_dataset_params.dataset_type(),
input_dataset_params.iterator_prefix());
}
std::vector<Tensor> GetInputTensors() const override {
Tensor rate = CreateTensor<float>(TensorShape({}), {rate_});
Tensor seed_tensor = CreateTensor<int64_t>(TensorShape({}), {seed_tensor_});
Tensor seed2_tensor =
CreateTensor<int64_t>(TensorShape({}), {seed2_tensor_});
return {rate, seed_tensor, seed2_tensor};
}
Status GetInputNames(std::vector<string>* input_names) const override {
*input_names = {SamplingDatasetOp::kInputDataset, SamplingDatasetOp::kRate,
SamplingDatasetOp::kSeed, SamplingDatasetOp::kSeed2};
return absl::OkStatus();
}
Status GetAttributes(AttributeVector* attr_vector) const override {
*attr_vector = {{SamplingDatasetOp::kOutputTypes, output_dtypes_},
{SamplingDatasetOp::kOutputShapes, output_shapes_}};
return absl::OkStatus();
}
string dataset_type() const override {
return SamplingDatasetOp::kDatasetType;
}
private:
float rate_;
int64_t seed_tensor_ = kRandomSeed;
int64_t seed2_tensor_ = kRandomSeed2;
};
class SamplingDatasetOpTest : public DatasetOpsTestBase {};
SamplingDatasetParams OneHundredPercentSampleParams() {
return SamplingDatasetParams(RangeDatasetParams(0, 3, 1),
1.0,
{DT_INT64},
{PartialTensorShape({})},
kNodeName);
}
SamplingDatasetParams TenPercentSampleParams() {
return SamplingDatasetParams(RangeDatasetParams(0, 20, 1),
0.1,
{DT_INT64},
{PartialTensorShape({})},
kNodeName);
}
SamplingDatasetParams ZeroPercentSampleParams() {
return SamplingDatasetParams(RangeDatasetParams(0, 20, 1),
0.0,
{DT_INT64},
{PartialTensorShape({})},
kNodeName);
}
std::vector<GetNextTestCase<SamplingDatasetParams>> GetNextTestCases() {
return {
{OneHundredPercentSampleParams(),
CreateTensors<int64_t>(TensorShape({}),
{{0}, {1}, {2}})},
{TenPercentSampleParams(),
CreateTensors<int64_t>(TensorShape({}),
{{9}, {11}, {19}})},
{ZeroPercentSampleParams(), {}}};
}
ITERATOR_GET_NEXT_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
GetNextTestCases())
std::vector<DatasetNodeNameTestCase<SamplingDatasetParams>>
DatasetNodeNameTestCases() {
return {{TenPercentSampleParams(),
kNodeName}};
}
DATASET_NODE_NAME_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
DatasetNodeNameTestCases())
std::vector<DatasetTypeStringTestCase<SamplingDatasetParams>>
DatasetTypeStringTestCases() {
return {{TenPercentSampleParams(),
name_utils::OpName(
SamplingDatasetOp::kDatasetType)}};
}
DATASET_TYPE_STRING_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
DatasetTypeStringTestCases())
std::vector<DatasetOutputDtypesTestCase<SamplingDatasetParams>>
DatasetOutputDtypesTestCases() {
return {{TenPercentSampleParams(),
{DT_INT64}}};
}
DATASET_OUTPUT_DTYPES_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
DatasetOutputDtypesTestCases())
std::vector<DatasetOutputShapesTestCase<SamplingDatasetParams>>
DatasetOutputShapesTestCases() {
return {{TenPercentSampleParams(),
{PartialTensorShape({})}}};
}
DATASET_OUTPUT_SHAPES_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
DatasetOutputShapesTestCases())
std::vector<CardinalityTestCase<SamplingDatasetParams>> CardinalityTestCases() {
return {{OneHundredPercentSampleParams(),
kUnknownCardinality},
{TenPercentSampleParams(),
kUnknownCardinality},
{ZeroPercentSampleParams(),
kUnknownCardinality}};
}
DATASET_CARDINALITY_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
CardinalityTestCases())
std::vector<IteratorOutputDtypesTestCase<SamplingDatasetParams>>
IteratorOutputDtypesTestCases() {
return {{TenPercentSampleParams(),
{DT_INT64}}};
}
ITERATOR_OUTPUT_DTYPES_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
IteratorOutputDtypesTestCases())
std::vector<IteratorOutputShapesTestCase<SamplingDatasetParams>>
IteratorOutputShapesTestCases() {
return {{TenPercentSampleParams(),
{PartialTensorShape({})}}};
}
ITERATOR_OUTPUT_SHAPES_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
IteratorOutputShapesTestCases())
std::vector<IteratorPrefixTestCase<SamplingDatasetParams>>
IteratorOutputPrefixTestCases() {
return {{TenPercentSampleParams(),
name_utils::IteratorPrefix(
SamplingDatasetOp::kDatasetType,
TenPercentSampleParams().iterator_prefix())}};
}
ITERATOR_PREFIX_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
IteratorOutputPrefixTestCases())
std::vector<IteratorSaveAndRestoreTestCase<SamplingDatasetParams>>
IteratorSaveAndRestoreTestCases() {
return {{OneHundredPercentSampleParams(),
{0, 2, 5},
CreateTensors<int64_t>(TensorShape({}), {{0}, {1}, {2}})},
{TenPercentSampleParams(),
{0, 2, 5},
CreateTensors<int64_t>(TensorShape({}), {{9}, {11}, {19}})},
{ZeroPercentSampleParams(),
{0, 2, 5},
{}}};
}
ITERATOR_SAVE_AND_RESTORE_TEST_P(SamplingDatasetOpTest, SamplingDatasetParams,
IteratorSaveAndRestoreTestCases())
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/data/experimental/sampling_dataset_op.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/data/experimental/sampling_dataset_op_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
af3cb316-da96-4619-8d4c-eff187dc6413 | cpp | google/quiche | hpack_decoder_string_buffer | quiche/http2/hpack/decoder/hpack_decoder_string_buffer.cc | quiche/http2/hpack/decoder/hpack_decoder_string_buffer_test.cc | #include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include <ostream>
#include <string>
#include <utility>
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer::State v) {
switch (v) {
case HpackDecoderStringBuffer::State::RESET:
return out << "RESET";
case HpackDecoderStringBuffer::State::COLLECTING:
return out << "COLLECTING";
case HpackDecoderStringBuffer::State::COMPLETE:
return out << "COMPLETE";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_50_1)
<< "Invalid HpackDecoderStringBuffer::State: " << unknown;
return out << "HpackDecoderStringBuffer::State(" << unknown << ")";
}
std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer::Backing v) {
switch (v) {
case HpackDecoderStringBuffer::Backing::RESET:
return out << "RESET";
case HpackDecoderStringBuffer::Backing::UNBUFFERED:
return out << "UNBUFFERED";
case HpackDecoderStringBuffer::Backing::BUFFERED:
return out << "BUFFERED";
}
auto v2 = static_cast<int>(v);
QUICHE_BUG(http2_bug_50_2)
<< "Invalid HpackDecoderStringBuffer::Backing: " << v2;
return out << "HpackDecoderStringBuffer::Backing(" << v2 << ")";
}
HpackDecoderStringBuffer::HpackDecoderStringBuffer()
: remaining_len_(0),
is_huffman_encoded_(false),
state_(State::RESET),
backing_(Backing::RESET) {}
HpackDecoderStringBuffer::~HpackDecoderStringBuffer() = default;
void HpackDecoderStringBuffer::Reset() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::Reset";
state_ = State::RESET;
}
void HpackDecoderStringBuffer::OnStart(bool huffman_encoded, size_t len) {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnStart";
QUICHE_DCHECK_EQ(state_, State::RESET);
remaining_len_ = len;
is_huffman_encoded_ = huffman_encoded;
state_ = State::COLLECTING;
if (huffman_encoded) {
decoder_.Reset();
buffer_.clear();
backing_ = Backing::BUFFERED;
len = len * 8 / 5;
if (buffer_.capacity() < len) {
buffer_.reserve(len);
}
} else {
backing_ = Backing::RESET;
value_ = absl::string_view();
}
}
bool HpackDecoderStringBuffer::OnData(const char* data, size_t len) {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnData state=" << state_
<< ", backing=" << backing_;
QUICHE_DCHECK_EQ(state_, State::COLLECTING);
QUICHE_DCHECK_LE(len, remaining_len_);
remaining_len_ -= len;
if (is_huffman_encoded_) {
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
return decoder_.Decode(absl::string_view(data, len), &buffer_);
}
if (backing_ == Backing::RESET) {
if (remaining_len_ == 0) {
value_ = absl::string_view(data, len);
backing_ = Backing::UNBUFFERED;
return true;
}
backing_ = Backing::BUFFERED;
buffer_.reserve(remaining_len_ + len);
buffer_.assign(data, len);
return true;
}
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
buffer_.append(data, len);
return true;
}
bool HpackDecoderStringBuffer::OnEnd() {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnEnd";
QUICHE_DCHECK_EQ(state_, State::COLLECTING);
QUICHE_DCHECK_EQ(0u, remaining_len_);
if (is_huffman_encoded_) {
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
if (!decoder_.InputProperlyTerminated()) {
return false;
}
value_ = buffer_;
} else if (backing_ == Backing::BUFFERED) {
value_ = buffer_;
}
state_ = State::COMPLETE;
return true;
}
void HpackDecoderStringBuffer::BufferStringIfUnbuffered() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferStringIfUnbuffered state="
<< state_ << ", backing=" << backing_;
if (state_ != State::RESET && backing_ == Backing::UNBUFFERED) {
QUICHE_DVLOG(2)
<< "HpackDecoderStringBuffer buffering std::string of length "
<< value_.size();
buffer_.assign(value_.data(), value_.size());
if (state_ == State::COMPLETE) {
value_ = buffer_;
}
backing_ = Backing::BUFFERED;
}
}
bool HpackDecoderStringBuffer::IsBuffered() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::IsBuffered";
return state_ != State::RESET && backing_ == Backing::BUFFERED;
}
size_t HpackDecoderStringBuffer::BufferedLength() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferedLength";
return IsBuffered() ? buffer_.size() : 0;
}
absl::string_view HpackDecoderStringBuffer::str() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::str";
QUICHE_DCHECK_EQ(state_, State::COMPLETE);
return value_;
}
absl::string_view HpackDecoderStringBuffer::GetStringIfComplete() const {
if (state_ != State::COMPLETE) {
return {};
}
return str();
}
std::string HpackDecoderStringBuffer::ReleaseString() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::ReleaseString";
QUICHE_DCHECK_EQ(state_, State::COMPLETE);
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
if (state_ == State::COMPLETE) {
state_ = State::RESET;
if (backing_ == Backing::BUFFERED) {
return std::move(buffer_);
} else {
return std::string(value_);
}
}
return "";
}
void HpackDecoderStringBuffer::OutputDebugStringTo(std::ostream& out) const {
out << "{state=" << state_;
if (state_ != State::RESET) {
out << ", backing=" << backing_;
out << ", remaining_len=" << remaining_len_;
out << ", is_huffman_encoded=" << is_huffman_encoded_;
if (backing_ == Backing::BUFFERED) {
out << ", buffer: " << buffer_;
} else {
out << ", value: " << value_;
}
}
out << "}";
}
std::ostream& operator<<(std::ostream& out, const HpackDecoderStringBuffer& v) {
v.OutputDebugStringTo(out);
return out;
}
} | #include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include <initializer_list>
#include <sstream>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
using ::testing::HasSubstr;
namespace http2 {
namespace test {
namespace {
class HpackDecoderStringBufferTest : public quiche::test::QuicheTest {
protected:
typedef HpackDecoderStringBuffer::State State;
typedef HpackDecoderStringBuffer::Backing Backing;
State state() const { return buf_.state_for_testing(); }
Backing backing() const { return buf_.backing_for_testing(); }
AssertionResult VerifyLogHasSubstrs(std::initializer_list<std::string> strs) {
QUICHE_VLOG(1) << buf_;
std::ostringstream ss;
buf_.OutputDebugStringTo(ss);
std::string dbg_str(ss.str());
for (const auto& expected : strs) {
HTTP2_VERIFY_TRUE(absl::StrContains(dbg_str, expected));
}
return AssertionSuccess();
}
HpackDecoderStringBuffer buf_;
};
TEST_F(HpackDecoderStringBufferTest, PlainWhole) {
absl::string_view data("some text.");
QUICHE_LOG(INFO) << buf_;
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( false, data.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::RESET);
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(data.data(), data.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::UNBUFFERED);
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::UNBUFFERED);
EXPECT_EQ(0u, buf_.BufferedLength());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"state=COMPLETE", "backing=UNBUFFERED", "value: some text."}));
EXPECT_EQ(data.data(), buf_.str().data());
buf_.BufferStringIfUnbuffered();
QUICHE_LOG(INFO) << buf_;
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_EQ(data, buf_.str());
EXPECT_NE(data.data(), buf_.str().data());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"state=COMPLETE", "backing=BUFFERED", "buffer: some text."}));
}
TEST_F(HpackDecoderStringBufferTest, PlainSplit) {
absl::string_view data("some text.");
absl::string_view part1 = data.substr(0, 1);
absl::string_view part2 = data.substr(1);
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( false, data.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::RESET);
EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), part1.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
QUICHE_LOG(INFO) << buf_;
absl::string_view buffered = buf_.str();
EXPECT_EQ(data, buffered);
EXPECT_NE(data.data(), buffered.data());
buf_.BufferStringIfUnbuffered();
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_EQ(buffered, buf_.str());
EXPECT_EQ(buffered.data(), buf_.str().data());
}
TEST_F(HpackDecoderStringBufferTest, HuffmanWhole) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded));
absl::string_view decoded("www.example.com");
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
EXPECT_EQ(decoded, buf_.str());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"{state=COMPLETE", "backing=BUFFERED", "buffer: www.example.com}"}));
std::string s = buf_.ReleaseString();
EXPECT_EQ(s, decoded);
EXPECT_EQ(state(), State::RESET);
}
TEST_F(HpackDecoderStringBufferTest, HuffmanSplit) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded));
std::string part1 = encoded.substr(0, 5);
std::string part2 = encoded.substr(5);
absl::string_view decoded("www.example.com");
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(0u, buf_.BufferedLength());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_GT(buf_.BufferedLength(), 0u);
EXPECT_LT(buf_.BufferedLength(), decoded.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
EXPECT_EQ(decoded, buf_.str());
QUICHE_LOG(INFO) << buf_;
buf_.Reset();
EXPECT_EQ(state(), State::RESET);
QUICHE_LOG(INFO) << buf_;
}
TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnData) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("ffffffff", &encoded));
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_FALSE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
QUICHE_LOG(INFO) << buf_;
}
TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnEnd) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("00", &encoded));
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_FALSE(buf_.OnEnd());
QUICHE_LOG(INFO) << buf_;
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_string_buffer.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_string_buffer_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
753e4b82-adbd-4336-a554-86e584815eb5 | cpp | google/tensorstore | btree | tensorstore/kvstore/ocdbt/format/btree.cc | tensorstore/kvstore/ocdbt/format/btree_test.cc | #include "tensorstore/kvstore/ocdbt/format/btree.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <limits>
#include <memory>
#include <ostream>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_format.h"
#include "riegeli/bytes/reader.h"
#include "tensorstore/internal/integer_overflow.h"
#include "tensorstore/kvstore/ocdbt/format/btree_codec.h"
#include "tensorstore/kvstore/ocdbt/format/codec_util.h"
#include "tensorstore/kvstore/ocdbt/format/config.h"
#include "tensorstore/kvstore/ocdbt/format/data_file_id_codec.h"
#include "tensorstore/kvstore/ocdbt/format/indirect_data_reference.h"
#include "tensorstore/kvstore/ocdbt/format/indirect_data_reference_codec.h"
#include "tensorstore/util/quote_string.h"
#include "tensorstore/util/result.h"
#include "tensorstore/util/span.h"
#include "tensorstore/util/status.h"
#include "tensorstore/util/str_cat.h"
namespace tensorstore {
namespace internal_ocdbt {
namespace {
bool ReadKeyPrefixLengths(riegeli::Reader& reader,
span<KeyLength> prefix_lengths,
KeyLength& common_prefix_length) {
KeyLength min_prefix_length = kMaxKeyLength;
for (auto& prefix_length : prefix_lengths) {
if (!KeyLengthCodec{}(reader, prefix_length)) return false;
min_prefix_length = std::min(min_prefix_length, prefix_length);
}
common_prefix_length = min_prefix_length;
return true;
}
bool ReadKeySuffixLengths(riegeli::Reader& reader,
span<KeyLength> suffix_lengths) {
for (auto& length : suffix_lengths) {
if (!KeyLengthCodec{}(reader, length)) return false;
}
return true;
}
template <typename Entry>
bool ReadKeys(riegeli::Reader& reader, std::string_view& common_prefix,
BtreeNode::KeyBuffer& key_buffer, span<Entry> entries) {
const size_t num_entries = entries.size();
KeyLength common_prefix_length;
std::vector<KeyLength> key_length_buffer(num_entries * 2);
span<KeyLength> prefix_lengths(key_length_buffer.data(), num_entries);
span<KeyLength> suffix_lengths(key_length_buffer.data() + num_entries,
num_entries);
if (!ReadKeyPrefixLengths(reader, prefix_lengths.subspan(1),
common_prefix_length)) {
return false;
}
if (!ReadKeySuffixLengths(reader, suffix_lengths)) return false;
if constexpr (std::is_same_v<Entry, InteriorNodeEntry>) {
for (auto& entry : entries) {
if (!KeyLengthCodec{}(reader, entry.subtree_common_prefix_length)) {
return false;
}
common_prefix_length =
std::min(common_prefix_length, entry.subtree_common_prefix_length);
}
}
common_prefix_length = std::min(suffix_lengths[0], common_prefix_length);
size_t key_buffer_size = common_prefix_length;
for (size_t i = 0, prev_length = 0; i < num_entries; ++i) {
size_t prefix_length = prefix_lengths[i];
if (prefix_length > prev_length) {
reader.Fail(absl::DataLossError(absl::StrFormat(
"Child %d: Prefix length of %d exceeds previous key length %d", i,
prefix_length, prev_length)));
return false;
}
size_t suffix_length = suffix_lengths[i];
size_t key_length = prefix_length + suffix_length;
if (key_length > kMaxKeyLength) {
reader.Fail(absl::DataLossError(
absl::StrFormat("Child %d: Key length %d exceeds limit of %d", i,
key_length, kMaxKeyLength)));
return false;
}
if constexpr (std::is_same_v<Entry, InteriorNodeEntry>) {
auto& entry = entries[i];
if (entry.subtree_common_prefix_length > key_length) {
reader.Fail(absl::DataLossError(absl::StrFormat(
"Key %d: subtree common prefix length of %d exceeds key length of "
"%d",
i, entry.subtree_common_prefix_length, key_length)));
return false;
}
assert(entry.subtree_common_prefix_length >= common_prefix_length);
entry.subtree_common_prefix_length -= common_prefix_length;
}
prev_length = key_length;
key_buffer_size += key_length - common_prefix_length;
}
key_buffer = BtreeNode::KeyBuffer(key_buffer_size);
char* key_buffer_ptr = key_buffer.data.get();
const auto append_key_data = [&](auto... parts) {
std::string_view s(key_buffer_ptr, (parts.size() + ...));
(static_cast<void>(std::memcpy(key_buffer_ptr, parts.data(), parts.size()),
key_buffer_ptr += parts.size()),
...);
return s;
};
{
size_t key_length = suffix_lengths[0];
if (!reader.Pull(key_length)) return false;
auto full_first_key =
append_key_data(std::string_view(reader.cursor(), key_length));
common_prefix = full_first_key.substr(0, common_prefix_length);
entries[0].key = full_first_key.substr(common_prefix_length);
reader.move_cursor(key_length);
}
for (size_t i = 1; i < num_entries; ++i) {
size_t prefix_length = prefix_lengths[i] - common_prefix_length;
size_t suffix_length = suffix_lengths[i];
if (!reader.Pull(suffix_length)) return false;
auto prev_key = std::string_view(entries[i - 1].key);
auto suffix = std::string_view(reader.cursor(), suffix_length);
if (prev_key.substr(prefix_length) >= suffix) {
reader.Fail(absl::DataLossError("Invalid key order"));
return false;
}
entries[i].key = append_key_data(prev_key.substr(0, prefix_length), suffix);
reader.move_cursor(suffix_length);
}
return true;
}
template <typename Entry>
bool ReadBtreeNodeEntries(riegeli::Reader& reader,
const DataFileTable& data_file_table,
uint64_t num_entries, BtreeNode& node) {
auto& entries = node.entries.emplace<std::vector<Entry>>();
entries.resize(num_entries);
if (!ReadKeys<Entry>(reader, node.key_prefix, node.key_buffer, entries)) {
return false;
}
if constexpr (std::is_same_v<Entry, InteriorNodeEntry>) {
return BtreeNodeReferenceArrayCodec{data_file_table,
[](auto& entry) -> decltype(auto) {
return (entry.node);
}}(reader, entries);
} else {
return LeafNodeValueReferenceArrayCodec{data_file_table,
[](auto& entry) -> decltype(auto) {
return (entry.value_reference);
}}(reader, entries);
}
}
}
Result<BtreeNode> DecodeBtreeNode(const absl::Cord& encoded,
const BasePath& base_path) {
BtreeNode node;
auto status = DecodeWithOptionalCompression(
encoded, kBtreeNodeMagic, kBtreeNodeFormatVersion,
[&](riegeli::Reader& reader, uint32_t version) -> bool {
if (!reader.ReadByte(node.height)) return false;
DataFileTable data_file_table;
if (!ReadDataFileTable(reader, base_path, data_file_table)) {
return false;
}
uint32_t num_entries;
if (!ReadVarintChecked(reader, num_entries)) return false;
if (num_entries == 0) {
reader.Fail(absl::DataLossError("Empty b-tree node"));
return false;
}
if (num_entries > kMaxNodeArity) {
reader.Fail(absl::DataLossError(absl::StrFormat(
"B-tree node has arity %d, which exceeds limit of %d",
num_entries, kMaxNodeArity)));
return false;
}
if (node.height == 0) {
return ReadBtreeNodeEntries<LeafNodeEntry>(reader, data_file_table,
num_entries, node);
} else {
return ReadBtreeNodeEntries<InteriorNodeEntry>(
reader, data_file_table, num_entries, node);
}
});
if (!status.ok()) {
return tensorstore::MaybeAnnotateStatus(status,
"Error decoding b-tree node");
}
#ifndef NDEBUG
CheckBtreeNodeInvariants(node);
#endif
return node;
}
absl::Status ValidateBtreeNodeReference(const BtreeNode& node,
BtreeNodeHeight height,
std::string_view inclusive_min_key) {
if (node.height != height) {
return absl::DataLossError(absl::StrFormat(
"Expected height of %d but received: %d", height, node.height));
}
return std::visit(
[&](auto& entries) {
if (ComparePrefixedKeyToUnprefixedKey{node.key_prefix}(
entries.front().key, inclusive_min_key) < 0) {
return absl::DataLossError(
tensorstore::StrCat("First key ",
tensorstore::QuoteString(tensorstore::StrCat(
node.key_prefix, entries.front().key)),
" is less than inclusive_min ",
tensorstore::QuoteString(inclusive_min_key),
" specified by parent node"));
}
return absl::OkStatus();
},
node.entries);
}
bool operator==(const BtreeNodeStatistics& a, const BtreeNodeStatistics& b) {
return a.num_indirect_value_bytes == b.num_indirect_value_bytes &&
a.num_tree_bytes == b.num_tree_bytes && a.num_keys == b.num_keys;
}
std::ostream& operator<<(std::ostream& os, const BtreeNodeStatistics& x) {
return os << "{num_indirect_value_bytes=" << x.num_indirect_value_bytes
<< ", num_tree_bytes=" << x.num_tree_bytes
<< ", num_keys=" << x.num_keys << "}";
}
BtreeNodeStatistics& BtreeNodeStatistics::operator+=(
const BtreeNodeStatistics& other) {
num_indirect_value_bytes = internal::AddSaturate(
num_indirect_value_bytes, other.num_indirect_value_bytes);
num_tree_bytes = internal::AddSaturate(num_tree_bytes, other.num_tree_bytes);
num_keys = internal::AddSaturate(num_keys, other.num_keys);
return *this;
}
bool operator==(const LeafNodeEntry& a, const LeafNodeEntry& b) {
return a.key == b.key && a.value_reference == b.value_reference;
}
std::ostream& operator<<(std::ostream& os, const LeafNodeValueReference& x) {
if (auto* value = std::get_if<absl::Cord>(&x)) {
return os << tensorstore::QuoteString(std::string(*value));
} else {
return os << std::get<IndirectDataReference>(x);
}
}
std::ostream& operator<<(std::ostream& os, const LeafNodeEntry& e) {
return os << "{key=" << tensorstore::QuoteString(e.key)
<< ", value_reference=" << e.value_reference << "}";
}
bool operator==(const BtreeNodeReference& a, const BtreeNodeReference& b) {
return a.location == b.location && a.statistics == b.statistics;
}
std::ostream& operator<<(std::ostream& os, const BtreeNodeReference& x) {
return os << "{location=" << x.location << ", statistics=" << x.statistics
<< "}";
}
std::ostream& operator<<(std::ostream& os, const InteriorNodeEntry& e) {
return os << "{key=" << tensorstore::QuoteString(e.key)
<< ", subtree_common_prefix_length="
<< e.subtree_common_prefix_length << ", node=" << e.node << "}";
}
const LeafNodeEntry* FindBtreeEntry(span<const LeafNodeEntry> entries,
std::string_view key) {
const LeafNodeEntry* entry = FindBtreeEntryLowerBound(entries, key);
if (entry == entries.data() + entries.size() || entry->key != key) {
return nullptr;
}
return entry;
}
const LeafNodeEntry* FindBtreeEntryLowerBound(span<const LeafNodeEntry> entries,
std::string_view inclusive_min) {
return std::lower_bound(
entries.data(), entries.data() + entries.size(), inclusive_min,
[](const LeafNodeEntry& entry, std::string_view inclusive_min) {
return entry.key < inclusive_min;
});
}
span<const LeafNodeEntry> FindBtreeEntryRange(span<const LeafNodeEntry> entries,
std::string_view inclusive_min,
std::string_view exclusive_max) {
const LeafNodeEntry* lower = FindBtreeEntryLowerBound(entries, inclusive_min);
const LeafNodeEntry* upper = entries.data() + entries.size();
if (!exclusive_max.empty()) {
upper = std::lower_bound(
lower, upper, exclusive_max,
[](const LeafNodeEntry& entry, std::string_view exclusive_max) {
return entry.key < exclusive_max;
});
}
return {lower, upper};
}
const InteriorNodeEntry* FindBtreeEntry(span<const InteriorNodeEntry> entries,
std::string_view key) {
auto it = std::lower_bound(
entries.data(), entries.data() + entries.size(), key,
[](const InteriorNodeEntry& entry, std::string_view inclusive_min) {
return entry.key <= inclusive_min;
});
if (it == entries.data()) {
return nullptr;
}
return it - 1;
}
const InteriorNodeEntry* FindBtreeEntryLowerBound(
span<const InteriorNodeEntry> entries, std::string_view inclusive_min) {
auto it = std::lower_bound(
entries.data(), entries.data() + entries.size(), inclusive_min,
[](const InteriorNodeEntry& entry, std::string_view inclusive_min) {
return entry.key <= inclusive_min;
});
if (it != entries.data()) --it;
return it;
}
span<const InteriorNodeEntry> FindBtreeEntryRange(
span<const InteriorNodeEntry> entries, std::string_view inclusive_min,
std::string_view exclusive_max) {
const InteriorNodeEntry* lower =
FindBtreeEntryLowerBound(entries, inclusive_min);
const InteriorNodeEntry* upper = entries.data() + entries.size();
if (!exclusive_max.empty()) {
upper = std::lower_bound(
lower, upper, exclusive_max,
[](const InteriorNodeEntry& entry, std::string_view exclusive_max) {
return entry.key < exclusive_max;
});
}
return {lower, upper};
}
#ifndef NDEBUG
void CheckBtreeNodeInvariants(const BtreeNode& node) {
if (node.height == 0) {
assert(std::holds_alternative<BtreeNode::LeafNodeEntries>(node.entries));
auto& entries = std::get<BtreeNode::LeafNodeEntries>(node.entries);
assert(!entries.empty());
assert(entries.size() <= kMaxNodeArity);
for (size_t i = 0; i < entries.size(); ++i) {
auto& entry = entries[i];
if (auto* location =
std::get_if<IndirectDataReference>(&entry.value_reference)) {
assert(!location->IsMissing());
}
if (i != 0) {
assert(entry.key > entries[i - 1].key);
}
}
} else {
assert(
std::holds_alternative<BtreeNode::InteriorNodeEntries>(node.entries));
auto& entries = std::get<BtreeNode::InteriorNodeEntries>(node.entries);
assert(!entries.empty());
assert(entries.size() <= kMaxNodeArity);
for (size_t i = 0; i < entries.size(); ++i) {
auto& entry = entries[i];
assert(entry.subtree_common_prefix_length <= entry.key.size());
assert(!entry.node.location.IsMissing());
if (i != 0) {
assert(entry.key > entries[i - 1].key);
}
}
}
}
#endif
}
} | #include "tensorstore/kvstore/ocdbt/format/btree.h"
#include <stddef.h>
#include <algorithm>
#include <string>
#include <string_view>
#include <type_traits>
#include <variant>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_format.h"
#include "riegeli/bytes/writer.h"
#include "tensorstore/kvstore/ocdbt/format/btree_codec.h"
#include "tensorstore/kvstore/ocdbt/format/btree_node_encoder.h"
#include "tensorstore/kvstore/ocdbt/format/codec_util.h"
#include "tensorstore/kvstore/ocdbt/format/config.h"
#include "tensorstore/util/quote_string.h"
#include "tensorstore/util/status_testutil.h"
#include "tensorstore/util/str_cat.h"
namespace {
using ::tensorstore::MatchesStatus;
using ::tensorstore::Result;
using ::tensorstore::internal_ocdbt::BtreeNode;
using ::tensorstore::internal_ocdbt::BtreeNodeEncoder;
using ::tensorstore::internal_ocdbt::Config;
using ::tensorstore::internal_ocdbt::DecodeBtreeNode;
using ::tensorstore::internal_ocdbt::EncodedNode;
using ::tensorstore::internal_ocdbt::InteriorNodeEntry;
using ::tensorstore::internal_ocdbt::kMaxNodeArity;
using ::tensorstore::internal_ocdbt::LeafNodeEntry;
Result<std::vector<EncodedNode>> EncodeExistingNode(const Config& config,
const BtreeNode& node) {
return std::visit(
[&](const auto& entries) {
using Entry = typename std::decay_t<decltype(entries)>::value_type;
BtreeNodeEncoder<Entry> encoder(config, node.height,
node.key_prefix);
for (const auto& entry : entries) {
encoder.AddEntry(true, Entry(entry));
}
return encoder.Finalize(false);
},
node.entries);
}
void TestBtreeNodeRoundTrip(const Config& config, const BtreeNode& node) {
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto encoded_nodes,
EncodeExistingNode(config, node));
ASSERT_EQ(1, encoded_nodes.size());
auto& encoded_node = encoded_nodes[0];
EXPECT_EQ(node.key_prefix, encoded_node.info.inclusive_min_key.substr(
0, encoded_node.info.excluded_prefix_length));
SCOPED_TRACE(tensorstore::StrCat(
"data=",
tensorstore::QuoteString(std::string(encoded_node.encoded_node))));
std::visit(
[&](const auto& entries) {
using Entry = typename std::decay_t<decltype(entries)>::value_type;
TENSORSTORE_ASSERT_OK_AND_ASSIGN(
auto decoded_node,
DecodeBtreeNode(encoded_nodes[0].encoded_node, {}));
EXPECT_EQ(node.key_prefix,
tensorstore::StrCat(
encoded_node.info.inclusive_min_key.substr(
0, encoded_node.info.excluded_prefix_length),
decoded_node.key_prefix));
EXPECT_THAT(decoded_node.entries,
::testing::VariantWith<std::vector<Entry>>(entries));
},
node.entries);
}
TEST(BtreeNodeTest, LeafNodeRoundTrip) {
Config config;
config.compression = Config::NoCompression{};
BtreeNode node;
node.height = 0;
node.key_prefix = "ab";
auto& entries = node.entries.emplace<BtreeNode::LeafNodeEntries>();
entries.push_back({"c",
absl::Cord("value1")});
entries.push_back({"d",
absl::Cord("value2")});
TestBtreeNodeRoundTrip(config, node);
}
TEST(BtreeNodeTest, InteriorNodeRoundTrip) {
Config config;
BtreeNode node;
node.height = 2;
auto& entries = node.entries.emplace<BtreeNode::InteriorNodeEntries>();
{
InteriorNodeEntry entry;
entry.key = "abc";
entry.subtree_common_prefix_length = 1;
entry.node.location.file_id.base_path = "abc";
entry.node.location.file_id.relative_path = "def";
entry.node.location.offset = 5;
entry.node.location.length = 6;
entry.node.statistics.num_indirect_value_bytes = 100;
entry.node.statistics.num_tree_bytes = 200;
entry.node.statistics.num_keys = 5;
entries.push_back(entry);
}
{
InteriorNodeEntry entry;
entry.key = "def";
entry.subtree_common_prefix_length = 1;
entry.node.location.file_id.base_path = "abc1";
entry.node.location.file_id.relative_path = "def1";
entry.node.location.offset = 42;
entry.node.location.length = 9;
entry.node.statistics.num_indirect_value_bytes = 101;
entry.node.statistics.num_tree_bytes = 220;
entry.node.statistics.num_keys = 8;
entries.push_back(entry);
}
TestBtreeNodeRoundTrip(config, node);
}
TEST(BtreeNodeTest, InteriorNodeBasePath) {
Config config;
BtreeNode node;
node.height = 2;
auto& entries = node.entries.emplace<BtreeNode::InteriorNodeEntries>();
{
InteriorNodeEntry entry;
entry.key = "abc";
entry.subtree_common_prefix_length = 1;
entry.node.location.file_id.base_path = "abc";
entry.node.location.file_id.relative_path = "def";
entry.node.location.offset = 5;
entry.node.location.length = 6;
entry.node.statistics.num_indirect_value_bytes = 100;
entry.node.statistics.num_tree_bytes = 200;
entry.node.statistics.num_keys = 5;
entries.push_back(entry);
}
{
InteriorNodeEntry entry;
entry.key = "def";
entry.subtree_common_prefix_length = 1;
entry.node.location.file_id.base_path = "abc1";
entry.node.location.file_id.relative_path = "def1";
entry.node.location.offset = 42;
entry.node.location.length = 9;
entry.node.statistics.num_indirect_value_bytes = 101;
entry.node.statistics.num_tree_bytes = 220;
entry.node.statistics.num_keys = 8;
entries.push_back(entry);
}
{
InteriorNodeEntry entry;
entry.key = "ghi";
entry.subtree_common_prefix_length = 1;
entry.node.location.file_id.base_path = "abc1";
entry.node.location.file_id.relative_path = "def2";
entry.node.location.offset = 43;
entry.node.location.length = 10;
entry.node.statistics.num_indirect_value_bytes = 102;
entry.node.statistics.num_tree_bytes = 230;
entry.node.statistics.num_keys = 9;
entries.push_back(entry);
}
{
InteriorNodeEntry entry;
entry.key = "jkl";
entry.subtree_common_prefix_length = 1;
entry.node.location.file_id.base_path = "abc1";
entry.node.location.file_id.relative_path = "def1";
entry.node.location.offset = 43;
entry.node.location.length = 10;
entry.node.statistics.num_indirect_value_bytes = 102;
entry.node.statistics.num_tree_bytes = 230;
entry.node.statistics.num_keys = 9;
entries.push_back(entry);
}
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto encoded_nodes,
EncodeExistingNode(config, node));
ASSERT_EQ(1, encoded_nodes.size());
auto& encoded_node = encoded_nodes[0];
EXPECT_EQ(node.key_prefix, encoded_node.info.inclusive_min_key.substr(
0, encoded_node.info.excluded_prefix_length));
TENSORSTORE_ASSERT_OK_AND_ASSIGN(
auto decoded_node,
DecodeBtreeNode(encoded_nodes[0].encoded_node, "xyz/"));
entries[0].node.location.file_id.base_path = "xyz/abc";
entries[1].node.location.file_id.base_path = "xyz/abc1";
entries[2].node.location.file_id.base_path = "xyz/abc1";
entries[3].node.location.file_id.base_path = "xyz/abc1";
EXPECT_THAT(decoded_node.entries,
::testing::VariantWith<std::vector<InteriorNodeEntry>>(entries));
}
absl::Cord EncodeRawBtree(const std::vector<unsigned char>& data) {
using ::tensorstore::internal_ocdbt::kBtreeNodeFormatVersion;
using ::tensorstore::internal_ocdbt::kBtreeNodeMagic;
Config config;
config.compression = Config::NoCompression{};
return EncodeWithOptionalCompression(
config, kBtreeNodeMagic, kBtreeNodeFormatVersion,
[&](riegeli::Writer& writer) -> bool {
return writer.Write(std::string_view(
reinterpret_cast<const char*>(data.data()), data.size()));
})
.value();
}
absl::Status RoundTripRawBtree(const std::vector<unsigned char>& data) {
return DecodeBtreeNode(EncodeRawBtree(data), {}).status();
}
TEST(BtreeNodeTest, CorruptTruncateBodyZeroSize) {
EXPECT_THAT(
RoundTripRawBtree({}),
MatchesStatus(absl::StatusCode::kDataLoss,
"Error decoding b-tree node: Unexpected end of data; .*"));
}
TEST(BtreeNodeTest, CorruptLeafTruncatedNumEntries) {
EXPECT_THAT(
RoundTripRawBtree({
0,
}),
MatchesStatus(absl::StatusCode::kDataLoss,
"Error decoding b-tree node: Unexpected end of data; .*"));
}
TEST(BtreeNodeTest, CorruptLeafZeroNumEntries) {
EXPECT_THAT(
RoundTripRawBtree({
0,
0,
0,
0,
}),
MatchesStatus(absl::StatusCode::kDataLoss,
"Error decoding b-tree node: Empty b-tree node; .*"));
}
TEST(BtreeNodeTest, CorruptInteriorZeroNumEntries) {
EXPECT_THAT(
RoundTripRawBtree({
1,
0,
0,
0,
}),
MatchesStatus(absl::StatusCode::kDataLoss,
"Error decoding b-tree node: Empty b-tree node; .*"));
}
TEST(BtreeNodeTest, MaxArity) {
Config config;
config.compression = Config::NoCompression{};
config.max_decoded_node_bytes = 1000000000;
BtreeNode node;
node.height = 0;
auto& entries = node.entries.emplace<BtreeNode::LeafNodeEntries>();
std::vector<std::string> keys;
for (size_t i = 0; i <= kMaxNodeArity; ++i) {
keys.push_back(absl::StrFormat("%07d", i));
}
std::sort(keys.begin(), keys.end());
const auto add_entry = [&](size_t i) {
entries.push_back({keys[i],
absl::Cord()});
};
for (size_t i = 0; i < kMaxNodeArity; ++i) {
add_entry(i);
}
TestBtreeNodeRoundTrip(config, node);
add_entry(kMaxNodeArity);
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto encoded_nodes,
EncodeExistingNode(config, node));
ASSERT_EQ(2, encoded_nodes.size());
TENSORSTORE_ASSERT_OK_AND_ASSIGN(
auto decoded_node1,
DecodeBtreeNode(encoded_nodes[0].encoded_node, {}));
TENSORSTORE_ASSERT_OK_AND_ASSIGN(
auto decoded_node2,
DecodeBtreeNode(encoded_nodes[1].encoded_node, {}));
EXPECT_EQ(kMaxNodeArity / 2 + 1,
std::get<BtreeNode::LeafNodeEntries>(decoded_node1.entries).size());
EXPECT_EQ(kMaxNodeArity / 2,
std::get<BtreeNode::LeafNodeEntries>(decoded_node2.entries).size());
}
} | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/kvstore/ocdbt/format/btree.cc | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/kvstore/ocdbt/format/btree_test.cc | 4f887a6430414cd6088e1743555015b10f116d50 |
f97dfb87-0805-43bb-806b-b6193861e8fb | cpp | tensorflow/tensorflow | execution_state | third_party/xla/xla/ffi/execution_state.cc | third_party/xla/xla/ffi/execution_state_test.cc | #include "xla/ffi/execution_state.h"
#include <utility>
#include "absl/status/status.h"
#include "xla/ffi/type_id_registry.h"
#include "xla/util.h"
#include "tsl/platform/logging.h"
namespace xla::ffi {
ExecutionState::ExecutionState()
: type_id_(TypeIdRegistry::kUnknownTypeId),
state_(nullptr),
deleter_(nullptr) {}
ExecutionState::~ExecutionState() {
if (deleter_) deleter_(state_);
}
absl::Status ExecutionState::Set(TypeId type_id, void* state,
Deleter<void> deleter) {
DCHECK(state && deleter) << "State and deleter must not be null";
if (type_id_ != TypeIdRegistry::kUnknownTypeId) {
return FailedPrecondition("State is already set with a type id %d",
type_id_.value());
}
type_id_ = type_id;
state_ = state;
deleter_ = std::move(deleter);
return absl::OkStatus();
}
absl::StatusOr<void*> ExecutionState::Get(TypeId type_id) const {
if (type_id_ == TypeIdRegistry::kUnknownTypeId) {
return NotFound("State is not set");
}
if (type_id_ != type_id) {
return InvalidArgument(
"Set state type id %d does not match the requested one %d",
type_id_.value(), type_id.value());
}
return state_;
}
bool ExecutionState::IsSet() const {
return type_id_ != TypeIdRegistry::kUnknownTypeId;
}
} | #include "xla/ffi/execution_state.h"
#include <cstdint>
#include <memory>
#include "xla/tsl/lib/core/status_test_util.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace xla::ffi {
using TypeId = ExecutionState::TypeId;
using ::testing::HasSubstr;
TEST(ExecutionStateTest, SetAndGet) {
ExecutionState state;
EXPECT_FALSE(state.IsSet());
{
auto data = state.Get(TypeId(1));
EXPECT_THAT(data.status().message(), HasSubstr("State is not set"));
}
{
auto data = state.Get<int32_t>();
EXPECT_THAT(data.status().message(), HasSubstr("State is not set"));
}
TF_ASSERT_OK(state.Set(std::make_unique<int32_t>(42)));
EXPECT_TRUE(state.IsSet());
TF_ASSERT_OK_AND_ASSIGN(int32_t* data, state.Get<int32_t>());
EXPECT_EQ(*data, 42);
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/ffi/execution_state.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/ffi/execution_state_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
10d27e5d-535e-4d4c-b8ea-82d4c765fccf | cpp | tensorflow/tensorflow | profiler_lock | third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_lock.cc | third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_lock_test.cc | #include "tsl/profiler/lib/profiler_lock.h"
#include <atomic>
#include "absl/status/statusor.h"
#include "xla/tsl/util/env_var.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/macros.h"
namespace tsl {
namespace profiler {
namespace {
std::atomic<int> g_session_active = ATOMIC_VAR_INIT(0);
static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free");
}
bool ProfilerLock::HasActiveSession() {
return g_session_active.load(std::memory_order_relaxed) != 0;
}
absl::StatusOr<ProfilerLock> ProfilerLock::Acquire() {
static bool tf_profiler_disabled = [] {
bool disabled = false;
ReadBoolFromEnvVar("TF_DISABLE_PROFILING", false, &disabled).IgnoreError();
return disabled;
}();
if (TF_PREDICT_FALSE(tf_profiler_disabled)) {
return errors::AlreadyExists(
"TensorFlow Profiler is permanently disabled by env var "
"TF_DISABLE_PROFILING.");
}
int already_active = g_session_active.exchange(1, std::memory_order_acq_rel);
if (already_active) {
return errors::AlreadyExists(kProfilerLockContention);
}
return ProfilerLock(true);
}
void ProfilerLock::ReleaseIfActive() {
if (active_) {
g_session_active.store(0, std::memory_order_release);
active_ = false;
}
}
}
} | #include "tsl/profiler/lib/profiler_lock.h"
#include <utility>
#include "absl/status/statusor.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace profiler {
namespace {
TEST(ProfilerLockTest, DefaultConstructorCreatesInactiveInstance) {
ProfilerLock profiler_lock;
EXPECT_FALSE(profiler_lock.Active());
}
TEST(ProfilerLockTest, AcquireAndReleaseExplicitly) {
absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire();
ASSERT_TRUE(profiler_lock.ok());
EXPECT_TRUE(profiler_lock->Active());
profiler_lock->ReleaseIfActive();
EXPECT_FALSE(profiler_lock->Active());
}
TEST(ProfilerLockTest, AcquireAndReleaseOnDestruction) {
absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire();
ASSERT_TRUE(profiler_lock.ok());
EXPECT_TRUE(profiler_lock->Active());
}
TEST(ProfilerLockTest, ReacquireWithoutReleaseFails) {
absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire();
absl::StatusOr<ProfilerLock> profiler_lock_2 = ProfilerLock::Acquire();
ASSERT_TRUE(profiler_lock_1.ok());
EXPECT_TRUE(profiler_lock_1->Active());
EXPECT_FALSE(profiler_lock_2.ok());
}
TEST(ProfilerLockTest, ReacquireAfterReleaseSucceeds) {
auto profiler_lock_1 = ProfilerLock::Acquire();
ASSERT_TRUE(profiler_lock_1.ok());
ASSERT_TRUE(profiler_lock_1->Active());
profiler_lock_1->ReleaseIfActive();
ASSERT_FALSE(profiler_lock_1->Active());
auto profiler_lock_2 = ProfilerLock::Acquire();
EXPECT_TRUE(profiler_lock_2.ok());
EXPECT_TRUE(profiler_lock_2->Active());
}
TEST(ProfilerLockTest, InactiveAfterMove) {
absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire();
ASSERT_TRUE(profiler_lock_1.ok());
ASSERT_TRUE(profiler_lock_1->Active());
ProfilerLock profiler_lock_2 = std::move(*profiler_lock_1);
EXPECT_FALSE(profiler_lock_1->Active());
EXPECT_TRUE(profiler_lock_2.Active());
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_lock.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_lock_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
0239edc1-2484-43d0-8cc0-3407d549341e | cpp | tensorflow/tensorflow | c_api | tensorflow/c/eager/c_api.cc | tensorflow/c/eager/c_api_test.cc | #include "tensorflow/c/eager/c_api.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/memory/memory.h"
#include "tensorflow/c/c_api.h"
#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/c_api_experimental.h"
#include "tensorflow/c/eager/c_api_internal.h"
#include "tensorflow/c/eager/immediate_execution_operation.h"
#include "tensorflow/c/eager/immediate_execution_tensor_handle.h"
#include "tensorflow/c/eager/tfe_context_internal.h"
#include "tensorflow/c/eager/tfe_op_internal.h"
#include "tensorflow/c/eager/tfe_tensorhandle_internal.h"
#include "tensorflow/c/tf_buffer_internal.h"
#include "tensorflow/c/tf_status.h"
#include "tensorflow/c/tf_tensor_internal.h"
#include "xla/tsl/c/tsl_status_internal.h"
#include "tensorflow/core/common_runtime/copy_tensor.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/eager/attr_builder.h"
#include "tensorflow/core/common_runtime/eager/context.h"
#include "tensorflow/core/common_runtime/eager/custom_device.h"
#include "tensorflow/core/common_runtime/eager/custom_device_op_handler.h"
#include "tensorflow/core/common_runtime/eager/execute.h"
#include "tensorflow/core/common_runtime/eager/placement_utils.h"
#include "tensorflow/core/common_runtime/eager/tensor_handle.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/rendezvous.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/casts.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/profiler/lib/traceme.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
#include "tensorflow/core/public/version.h"
#if !defined(IS_MOBILE_PLATFORM)
#include "tensorflow/core/common_runtime/eager/context_distributed_manager.h"
#endif
using tensorflow::string;
namespace {
string DeviceName(const tensorflow::Device* d) {
return (d == nullptr) ? "cpu:0" : d->name();
}
void AnnotateEagerRuntimeConstructionContext(
tensorflow::FunctionDef& function_def) {
tensorflow::AttrValue value;
SetAttrValue("kEagerRuntime", &value);
(*function_def.mutable_attr())["_construction_context"] = value;
}
}
extern "C" {
TFE_ContextOptions* TFE_NewContextOptions() { return new TFE_ContextOptions; }
void TFE_ContextOptionsSetConfig(TFE_ContextOptions* options, const void* proto,
size_t proto_len, TF_Status* status) {
TF_SetConfig(&options->session_options, proto, proto_len, status);
}
void TFE_ContextOptionsSetAsync(TFE_ContextOptions* options,
unsigned char enable) {
options->async = enable;
}
void TFE_ContextOptionsSetDevicePlacementPolicy(
TFE_ContextOptions* options, TFE_ContextDevicePlacementPolicy policy) {
options->device_placement_policy = policy;
}
void TFE_DeleteContextOptions(TFE_ContextOptions* options) { delete options; }
TFE_Context* TFE_NewContext(const TFE_ContextOptions* opts, TF_Status* status) {
if (opts->use_tfrt) {
status->status = tensorflow::errors::Unimplemented("TFRT is not supported");
return nullptr;
}
std::vector<std::unique_ptr<tensorflow::Device>> devices;
status->status = tensorflow::DeviceFactory::AddDevices(
opts->session_options.options, "/job:localhost/replica:0/task:0",
&devices);
if (!status->status.ok()) return nullptr;
std::unique_ptr<tensorflow::DeviceMgr> device_mgr(
new tensorflow::DynamicDeviceMgr(std::move(devices)));
auto r = tsl::core::RefCountPtr<tensorflow::IntraProcessRendezvous>(
new tensorflow::IntraProcessRendezvous(device_mgr.get()));
tensorflow::EagerContext* eager_context = new tensorflow::EagerContext(
opts->session_options.options,
static_cast<tensorflow::ContextDevicePlacementPolicy>(
opts->device_placement_policy),
opts->async, device_mgr.release(),
true, std::move(r),
nullptr,
nullptr,
opts->run_eager_op_as_function,
opts->jit_compile_rewrite);
#if !defined(IS_MOBILE_PLATFORM)
eager_context->SetDistributedManager(
std::make_unique<tensorflow::EagerContextDistributedManager>(
eager_context));
#endif
return tensorflow::wrap(eager_context);
}
void TFE_DeleteContext(TFE_Context* ctx) {
if (ctx == nullptr) {
return;
}
tensorflow::unwrap(ctx)->Release();
}
TF_DeviceList* TFE_ContextListDevices(TFE_Context* ctx, TF_Status* status) {
TF_DeviceList* l = new TF_DeviceList;
tensorflow::unwrap(ctx)->ListDevices(&l->response);
return l;
}
void TFE_ContextClearCaches(TFE_Context* ctx) {
tensorflow::unwrap(ctx)->ClearCachesAndThreadExecutors();
}
TF_CAPI_EXPORT extern void TFE_ContextSetServerDef(TFE_Context* ctx,
int keep_alive_secs,
const void* proto,
size_t proto_len,
TF_Status* status) {
TFE_ContextSetServerDefWithTimeoutAndRetries(
ctx, keep_alive_secs, proto, proto_len, 0,
0, status, false);
}
TF_CAPI_EXPORT extern void TFE_ContextSetServerDefWithTimeout(
TFE_Context* ctx, int keep_alive_secs, const void* proto, size_t proto_len,
int64_t init_timeout_in_ms, TF_Status* status,
bool clear_existing_contexts) {
TFE_ContextSetServerDefWithTimeoutAndRetries(
ctx, keep_alive_secs, proto, proto_len, init_timeout_in_ms,
0, status, clear_existing_contexts);
}
TF_CAPI_EXPORT extern void TFE_ContextSetServerDefWithTimeoutAndRetries(
TFE_Context* ctx, int keep_alive_secs, const void* proto, size_t proto_len,
int64_t init_timeout_in_ms, int retries, TF_Status* status,
bool clear_existing_contexts) {
#if defined(IS_MOBILE_PLATFORM)
status->status = tensorflow::errors::Unimplemented(
"TFE_ContextSetServerDef not supported on mobile");
#else
tensorflow::ServerDef server_def;
if (!server_def.ParseFromArray(proto, proto_len)) {
status->status = tensorflow::errors::InvalidArgument(
"Invalid tensorflow.ServerDef protocol buffer");
return;
}
status->status =
tensorflow::unwrap(ctx)->GetDistributedManager()->SetOrUpdateServerDef(
server_def, true, keep_alive_secs,
init_timeout_in_ms, retries, clear_existing_contexts);
#endif
}
TF_CAPI_EXPORT extern void TFE_ContextUpdateServerDef(TFE_Context* ctx,
int keep_alive_secs,
const void* proto,
size_t proto_len,
TF_Status* status) {
TFE_ContextUpdateServerDefWithTimeout(ctx, keep_alive_secs, proto, proto_len,
0, status);
}
TF_CAPI_EXPORT extern void TFE_ContextUpdateServerDefWithTimeout(
TFE_Context* ctx, int keep_alive_secs, const void* proto, size_t proto_len,
int64_t init_timeout_in_ms, TF_Status* status) {
#if defined(IS_MOBILE_PLATFORM)
status->status = tensorflow::errors::Unimplemented(
"TFE_ContextUpdateServerDef not supported on mobile");
#else
tensorflow::ServerDef server_def;
tensorflow::EagerContext* context =
tensorflow::ContextFromInterface(tensorflow::unwrap(ctx));
if (!server_def.ParseFromArray(proto, proto_len)) {
status->status = tensorflow::errors::InvalidArgument(
"Invalid tensorflow.ServerDef protocol buffer");
return;
} else if (context->GetContextId() ==
tensorflow::EagerContext::kInvalidContextId) {
status->status = tensorflow::errors::InvalidArgument(
"Trying to update a context with invalid context id.");
}
status->status =
tensorflow::unwrap(ctx)->GetDistributedManager()->SetOrUpdateServerDef(
server_def, false, keep_alive_secs,
init_timeout_in_ms, 0);
#endif
}
TF_CAPI_EXPORT extern bool TFE_ContextCheckAlive(TFE_Context* ctx,
const char* worker_name,
TF_Status* status) {
#if defined(IS_MOBILE_PLATFORM)
status->status = tensorflow::errors::Unimplemented(
"TFE_ContextSetServerDef not supported on mobile");
return false;
#else
bool is_alive;
status->status =
tensorflow::unwrap(ctx)->GetDistributedManager()->CheckRemoteAlive(
worker_name, &is_alive);
return is_alive;
#endif
}
TF_CAPI_EXPORT extern void TFE_ContextAsyncWait(TFE_Context* ctx,
TF_Status* status) {
#if defined(IS_MOBILE_PLATFORM)
status->status = tensorflow::OkStatus();
#else
status->status = tensorflow::unwrap(ctx)->AsyncWait();
#endif
}
void TFE_ContextSetThreadLocalDevicePlacementPolicy(
TFE_Context* ctx, TFE_ContextDevicePlacementPolicy policy) {
tensorflow::unwrap(ctx)->SetThreadLocalDevicePlacementPolicy(
static_cast<tensorflow::ContextDevicePlacementPolicy>(policy));
}
extern TFE_ContextDevicePlacementPolicy TFE_ContextGetDevicePlacementPolicy(
TFE_Context* ctx) {
return static_cast<TFE_ContextDevicePlacementPolicy>(
tensorflow::unwrap(ctx)->GetDevicePlacementPolicy());
}
TFE_TensorHandle* TFE_NewTensorHandle(const TF_Tensor* t, TF_Status* status) {
tensorflow::Tensor tensor;
status->status = tensorflow::TF_TensorToTensor(t, &tensor);
if (!status->status.ok()) return nullptr;
return tensorflow::wrap(tensorflow::TensorHandle::CreateLocalHandle(tensor));
}
void TFE_DeleteTensorHandle(TFE_TensorHandle* h) {
if (h == nullptr) return;
tsl::profiler::TraceMe activity("TFE_DeleteTensorHandle",
tsl::profiler::TraceMeLevel::kInfo);
if (h) {
tensorflow::unwrap(h)->Unref();
}
}
TF_DataType TFE_TensorHandleDataType(TFE_TensorHandle* h) {
return static_cast<TF_DataType>(tensorflow::unwrap(h)->DataType());
}
int TFE_TensorHandleNumDims(TFE_TensorHandle* h, TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return -1;
}
int num_dims = -1;
status->status = tensorflow::unwrap(h)->NumDims(&num_dims);
return num_dims;
}
int64_t TFE_TensorHandleNumElements(TFE_TensorHandle* h, TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return -1;
}
int64_t num_elements = -1;
status->status = tensorflow::unwrap(h)->NumElements(&num_elements);
return num_elements;
}
int64_t TFE_TensorHandleDim(TFE_TensorHandle* h, int dim_index,
TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return -1;
}
int64_t dim = -1;
status->status = tensorflow::unwrap(h)->Dim(dim_index, &dim);
return dim;
}
const char* TFE_TensorHandleDeviceName(TFE_TensorHandle* h, TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return nullptr;
}
return tensorflow::unwrap(h)->DeviceName(&status->status);
}
const char* TFE_TensorHandleBackingDeviceName(TFE_TensorHandle* h,
TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return nullptr;
}
return tensorflow::unwrap(h)->BackingDeviceName(&status->status);
}
TF_CAPI_EXPORT extern TFE_TensorHandle* TFE_TensorHandleCopySharingTensor(
TFE_TensorHandle* h, TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return nullptr;
}
tensorflow::unwrap(h)->Ref();
return h;
}
TF_Tensor* TFE_TensorHandleResolve(TFE_TensorHandle* h, TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return nullptr;
}
tensorflow::AbstractTensorInterface* t =
tensorflow::unwrap(h)->Resolve(&status->status);
if (t == nullptr) {
return nullptr;
}
return new TF_Tensor{t};
}
void* TFE_TensorHandleDevicePointer(TFE_TensorHandle* h, TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return nullptr;
}
tensorflow::ImmediateExecutionTensorHandle* unwrapped_handle =
tensorflow::unwrap(h);
if (tensorflow::CustomDeviceTensorHandle::classof(unwrapped_handle)) {
return tensorflow::down_cast<tensorflow::CustomDeviceTensorHandle*>(
unwrapped_handle)
->DevicePointer();
}
if (!tensorflow::TensorHandle::classof(unwrapped_handle)) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return nullptr;
}
tensorflow::TensorHandle* handle =
tensorflow::TensorHandleFromInterface(unwrapped_handle);
if (handle->Type() != tensorflow::TensorHandle::LOCAL) {
status->status = tensorflow::errors::InvalidArgument(
"TFE_TensorHandleDevicePointer may not be called on a ",
handle->TypeString(), " tensor handle.");
return nullptr;
}
tensorflow::Device* device(handle->device());
if (device != nullptr) {
status->status = device->Sync();
if (!status->status.ok()) {
return nullptr;
}
}
const tensorflow::Tensor* tensor;
status->status = handle->Tensor(&tensor);
if (!status->status.ok()) {
return nullptr;
}
return const_cast<void*>(
static_cast<const void*>(tensor->tensor_data().data()));
}
namespace tensorflow {
namespace {
class CustomDeviceAPI : public tensorflow::CustomDevice {
public:
CustomDeviceAPI(TFE_Context* context, TFE_CustomDevice device, void* info,
string name)
: context_(context), device_(device), info_(info), name_(name) {}
~CustomDeviceAPI() override { device_.delete_device(info_); }
const string& name() override { return name_; }
tensorflow::Status CopyTensorToDevice(
ImmediateExecutionTensorHandle* handle,
ImmediateExecutionTensorHandle** result) override {
handle->Ref();
TF_Status status;
TFE_TensorHandle* result_handle = device_.copy_tensor_to_device(
context_, tensorflow::wrap(handle), &status, info_);
handle->Unref();
if (!status.status.ok()) return status.status;
*result = tensorflow::unwrap(result_handle);
(*result)->Ref();
TFE_DeleteTensorHandle(result_handle);
return status.status;
}
tensorflow::Status CopyTensorFromDevice(
ImmediateExecutionTensorHandle* handle,
const tensorflow::string& target_device_name,
ImmediateExecutionTensorHandle** result) override {
TF_Status status;
handle->Ref();
TFE_TensorHandle* result_handle = device_.copy_tensor_from_device(
context_, tensorflow::wrap(handle), target_device_name.c_str(), &status,
info_);
handle->Unref();
if (!status.status.ok()) return status.status;
*result = tensorflow::unwrap(result_handle);
(*result)->Ref();
TFE_DeleteTensorHandle(result_handle);
return status.status;
}
tensorflow::Status Execute(const ImmediateExecutionOperation* op,
ImmediateExecutionTensorHandle** retvals,
int* num_retvals) override {
std::vector<TFE_TensorHandle*> outputs(*num_retvals);
TF_Status status;
device_.execute(tensorflow::wrap(op), num_retvals, outputs.data(), &status,
info_);
if (status.status.ok()) {
for (int i = 0; i < *num_retvals; ++i) {
retvals[i] = tensorflow::unwrap(outputs[i]);
retvals[i]->Ref();
TFE_DeleteTensorHandle(outputs[i]);
}
}
return status.status;
}
tensorflow::Status Pack(absl::Span<ImmediateExecutionTensorHandle*> handles,
ImmediateExecutionTensorHandle** result) override {
TF_Status status;
*result = tensorflow::unwrap(device_.pack(context_,
tensorflow::wrap(handles.data()),
handles.size(), &status, info_));
return status.status;
}
absl::StatusOr<bool> ShallPinToThisDevice(
const ImmediateExecutionOperation* op) override {
TF_Status status;
if (device_.shall_pin_to_this_device != nullptr) {
return device_.shall_pin_to_this_device(tensorflow::wrap(op), &status);
}
return errors::Unimplemented("No custom device pinning implementation.");
}
private:
TFE_Context* context_;
TFE_CustomDevice device_;
void* info_;
string name_;
};
class CAPICustomDeviceTensorHandle
: public tensorflow::CustomDeviceTensorHandle {
public:
CAPICustomDeviceTensorHandle(tensorflow::ImmediateExecutionContext* context,
tensorflow::CustomDevice* device,
tensorflow::DataType dtype, void* data,
TFE_CustomDeviceTensorHandleMethods methods)
: tensorflow::CustomDeviceTensorHandle(context, device, dtype),
data_(data),
methods_(methods) {}
~CAPICustomDeviceTensorHandle() override { methods_.deallocator(data_); }
void* DevicePointer() const override { return data_; }
Status NumDims(int* num_dims) const override {
TF_Status s;
*num_dims = methods_.num_dims(data_, &s);
return s.status;
}
Status Dim(int dim_index, int64_t* dim) const override {
TF_Status s;
*dim = methods_.dim(data_, dim_index, &s);
return s.status;
}
bool PreferCustomSummarizer() const override {
return methods_.summarize != nullptr;
}
Status SummarizeValue(std::string& summary) const override {
if (methods_.summarize == nullptr) {
return tensorflow::CustomDeviceTensorHandle::SummarizeValue(summary);
}
TF_Status c_status;
std::unique_ptr<TF_Buffer, decltype(&TF_DeleteBuffer)> summary_buffer(
methods_.summarize(data_, &c_status), TF_DeleteBuffer);
if (!c_status.status.ok()) {
return c_status.status;
}
summary = std::string(reinterpret_cast<const char*>(summary_buffer->data),
summary_buffer->length);
return absl::OkStatus();
}
private:
void* const data_;
const TFE_CustomDeviceTensorHandleMethods methods_;
};
}
}
TFE_TensorHandle* TFE_NewCustomDeviceTensorHandle(
TFE_Context* ctx, const char* device_name, TF_DataType dtype, void* data,
TFE_CustomDeviceTensorHandleMethods methods, TF_Status* status) {
tensorflow::ImmediateExecutionContext* context = tensorflow::unwrap(ctx);
tensorflow::CustomDevice* device = nullptr;
if (!context->GetCustomDeviceOpHandler().FindCustomDeviceFromName(device_name,
&device)) {
methods.deallocator(data);
status->status =
tensorflow::errors::InvalidArgument(device_name, " unknown device.");
return nullptr;
}
return tensorflow::wrap(new tensorflow::CAPICustomDeviceTensorHandle(
context, device, *reinterpret_cast<tensorflow::DataType*>(&dtype), data,
methods));
}
TFE_TensorHandle* TFE_NewTensorHandleFromDeviceMemory(
TFE_Context* ctx, const char* device_name, TF_DataType dtype,
const int64_t* dims, int num_dims, void* data, size_t len,
void (*deallocator)(void* data, size_t len, void* arg),
void* deallocator_arg, TF_Status* status) {
tensorflow::Device* device = nullptr;
tensorflow::EagerContext* context =
tensorflow::ContextFromInterface(tensorflow::unwrap(ctx));
status->status = context->FindDeviceFromName(device_name, &device);
if (!status->status.ok()) {
deallocator(data, len, deallocator_arg);
status->status =
tensorflow::errors::InvalidArgument(device_name, " unknown device.");
return nullptr;
}
std::vector<int64_t> dimvec(num_dims);
for (int i = 0; i < num_dims; ++i) {
dimvec[i] = static_cast<int64_t>(dims[i]);
}
TF_ManagedBuffer* buf =
new TF_ManagedBuffer(data, len, deallocator, deallocator_arg,
false);
tensorflow::Tensor t(static_cast<tensorflow::DataType>(dtype),
tensorflow::TensorShape(dimvec), buf);
buf->Unref();
return tensorflow::wrap(tensorflow::TensorHandle::CreateLocalHandle(
std::move(t), device, device, context));
}
size_t TFE_TensorHandleDeviceMemorySize(TFE_TensorHandle* h,
TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return 0;
}
tensorflow::TensorHandle* handle =
tensorflow::TensorHandleFromInterface(tensorflow::unwrap(h));
if (handle->Type() != tensorflow::TensorHandle::LOCAL) {
status->status = tensorflow::errors::InvalidArgument(
"TFE_TensorHandleDeviceMemorySize may not be called on a ",
handle->TypeString(), " tensor handle.");
return 0;
}
const tensorflow::Tensor* tensor;
status->status = handle->Tensor(&tensor);
if (!status->status.ok()) {
return 0;
}
return tensor->TotalBytes();
}
TFE_Op* TFE_NewOp(TFE_Context* ctx, const char* op_or_function_name,
TF_Status* status) {
tensorflow::ImmediateExecutionOperation* new_op =
tensorflow::unwrap(ctx)->CreateOperation();
status->status = new_op->Reset(op_or_function_name, nullptr);
if (!status->status.ok()) {
new_op->Release();
new_op = nullptr;
}
return tensorflow::wrap(new_op);
}
void TFE_DeleteOp(TFE_Op* op) {
if (op == nullptr) {
return;
}
tensorflow::unwrap(op)->Release();
}
const char* TFE_OpGetName(const TFE_Op* op, TF_Status* status) {
return tensorflow::unwrap(op)->Name().c_str();
}
TFE_Context* TFE_OpGetContext(const TFE_Op* op, TF_Status* status) {
return tensorflow::wrap(tensorflow::unwrap(op)->GetContext());
}
void TFE_OpSetDevice(TFE_Op* op, const char* device_name, TF_Status* status) {
status->status = tensorflow::unwrap(op)->SetDeviceName(device_name);
}
const char* TFE_OpGetDevice(const TFE_Op* op, TF_Status* status) {
return tensorflow::unwrap(op)->DeviceName().c_str();
}
void TFE_OpAddInput(TFE_Op* op, TFE_TensorHandle* input, TF_Status* status) {
status->status = tensorflow::unwrap(op)->AddInput(tensorflow::unwrap(input));
}
void TFE_OpAddInputList(TFE_Op* op, TFE_TensorHandle** inputs, int num_inputs,
TF_Status* status) {
status->status = tensorflow::unwrap(op)->AddInputList(
{reinterpret_cast<tensorflow::AbstractTensorHandle**>(
tensorflow::unwrap(inputs)),
static_cast<size_t>(num_inputs)});
}
extern int TFE_OpGetFlatInputCount(const TFE_Op* op, TF_Status* status) {
return tensorflow::unwrap(op)->GetInputs().size();
}
extern TFE_TensorHandle* TFE_OpGetFlatInput(const TFE_Op* op, int index,
TF_Status* status) {
return tensorflow::wrap(tensorflow::unwrap(op)->GetInputs()[index]);
}
TF_AttrType TFE_OpGetAttrType(TFE_Op* op, const char* attr_name,
unsigned char* is_list, TF_Status* status) {
TF_AttrType ret = TF_ATTR_INT;
const tensorflow::AttrTypeMap* attr_types_;
bool is_function;
status->status = tensorflow::AttrTypeMapForOp(
tensorflow::unwrap(op)->Name().c_str(), &attr_types_, &is_function);
if (!status->status.ok()) {
return ret;
}
status->status =
tensorflow::AttrTypeByName(*attr_types_, attr_name, &ret, is_list);
return ret;
}
TF_AttrType TFE_OpNameGetAttrType(TFE_Context* ctx,
const char* op_or_function_name,
const char* attr_name, unsigned char* is_list,
TF_Status* status) {
TF_AttrType ret;
TFE_Op* op = TFE_NewOp(ctx, op_or_function_name, status);
if (status->status.ok()) {
ret = TFE_OpGetAttrType(op, attr_name, is_list, status);
} else {
ret = TF_ATTR_INT;
}
TFE_DeleteOp(op);
return ret;
}
void TFE_OpSetAttrString(TFE_Op* op, const char* attr_name, const void* value,
size_t length) {
auto s = tensorflow::unwrap(op)->SetAttrString(
attr_name, static_cast<const char*>(value), length);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrInt(TFE_Op* op, const char* attr_name, int64_t value) {
auto s = tensorflow::unwrap(op)->SetAttrInt(attr_name, value);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrFloat(TFE_Op* op, const char* attr_name, float value) {
auto s = tensorflow::unwrap(op)->SetAttrFloat(attr_name, value);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrBool(TFE_Op* op, const char* attr_name, unsigned char value) {
auto s = tensorflow::unwrap(op)->SetAttrBool(attr_name,
(value == 0) ? false : true);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrType(TFE_Op* op, const char* attr_name, TF_DataType value) {
auto s = tensorflow::unwrap(op)->SetAttrType(
attr_name, static_cast<tensorflow::DataType>(value));
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrShape(TFE_Op* op, const char* attr_name, const int64_t* dims,
const int num_dims, TF_Status* out_status) {
out_status->status =
tensorflow::unwrap(op)->SetAttrShape(attr_name, dims, num_dims);
}
void TFE_OpSetAttrFunction(TFE_Op* op, const char* attr_name,
const TFE_Op* value) {
auto s = tensorflow::unwrap(op)->SetAttrFunction(
attr_name, tensorflow::unwrap(const_cast<TFE_Op*>(value)));
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrFunctionName(TFE_Op* op, const char* attr_name,
const char* data, size_t length) {
auto s = tensorflow::unwrap(op)->SetAttrFunctionName(attr_name, data, length);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrTensor(TFE_Op* op, const char* attr_name, TF_Tensor* tensor,
TF_Status* status) {
tensorflow::Tensor t;
status->status = TF_TensorToTensor(tensor, &t);
tensorflow::TensorInterface interface(t);
status->status = tensorflow::unwrap(op)->SetAttrTensor(attr_name, &interface);
}
void TFE_OpSetAttrStringList(TFE_Op* op, const char* attr_name,
const void* const* values, const size_t* lengths,
int num_values) {
auto s = tensorflow::unwrap(op)->SetAttrStringList(attr_name, values, lengths,
num_values);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrFloatList(TFE_Op* op, const char* attr_name,
const float* values, int num_values) {
auto s =
tensorflow::unwrap(op)->SetAttrFloatList(attr_name, values, num_values);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrIntList(TFE_Op* op, const char* attr_name,
const int64_t* values, int num_values) {
auto s =
tensorflow::unwrap(op)->SetAttrIntList(attr_name, values, num_values);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrTypeList(TFE_Op* op, const char* attr_name,
const TF_DataType* values, int num_values) {
auto s = tensorflow::unwrap(op)->SetAttrTypeList(
attr_name, reinterpret_cast<const tensorflow::DataType*>(values),
num_values);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrBoolList(TFE_Op* op, const char* attr_name,
const unsigned char* values, int num_values) {
auto s =
tensorflow::unwrap(op)->SetAttrBoolList(attr_name, values, num_values);
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrShapeList(TFE_Op* op, const char* attr_name,
const int64_t** dims, const int* num_dims,
int num_values, TF_Status* out_status) {
out_status->status = tensorflow::unwrap(op)->SetAttrShapeList(
attr_name, dims, num_dims, num_values);
}
void TFE_OpSetAttrFunctionList(TFE_Op* op, const char* attr_name,
const TFE_Op** value, int num_values) {
auto s = tensorflow::unwrap(op)->SetAttrFunctionList(
attr_name, {reinterpret_cast<const tensorflow::AbstractOperation**>(
tensorflow::unwrap(value)),
static_cast<size_t>(num_values)});
if (!s.ok()) {
LOG(WARNING) << "Unable to set attribute: " << attr_name;
}
}
void TFE_OpSetAttrValueProto(const TFE_Op* op, const char* attr_name,
const void* proto, size_t proto_len,
TF_Status* status) {
tensorflow::AttrValue attr_value;
if (!attr_value.ParseFromArray(proto, proto_len)) {
status->status =
tensorflow::errors::InvalidArgument("Unparseable AttrValue proto");
return;
}
if (op == nullptr) {
status->status = tensorflow::errors::InvalidArgument(
"Got a null or uninitialized `op` argument");
return;
}
tensorflow::EagerOperation* operation =
OperationFromInterface(tensorflow::unwrap(const_cast<TFE_Op*>(op)));
operation->MutableAttrs()->Set(attr_name, attr_value);
}
TF_CAPI_EXPORT extern int TFE_OpGetInputLength(TFE_Op* op,
const char* input_name,
TF_Status* status) {
int ret = -1;
status->status = tensorflow::unwrap(op)->InputLength(input_name, &ret);
return ret;
}
TF_CAPI_EXPORT extern int TFE_OpGetOutputLength(TFE_Op* op,
const char* output_name,
TF_Status* status) {
int ret = -1;
status->status = tensorflow::unwrap(op)->OutputLength(output_name, &ret);
return ret;
}
void TFE_Execute(TFE_Op* op, TFE_TensorHandle** retvals, int* num_retvals,
TF_Status* status) {
tensorflow::ImmediateExecutionOperation* unwrapped_op =
tensorflow::unwrap(op);
status->status =
unwrapped_op->GetContext()->GetCustomDeviceOpHandler().Execute(
unwrapped_op,
reinterpret_cast<tensorflow::ImmediateExecutionTensorHandle**>(
retvals),
num_retvals);
}
TFE_TensorHandle* TFE_TensorHandleCopyToDevice(TFE_TensorHandle* h,
TFE_Context* ctx,
const char* device_name,
TF_Status* status) {
if (h == nullptr) {
status->status = tensorflow::errors::InvalidArgument("Invalid handle");
return nullptr;
}
tensorflow::ImmediateExecutionContext* unwrapped_ctx =
tensorflow::unwrap(ctx);
auto* result =
unwrapped_ctx->GetCustomDeviceOpHandler().CopyTensorHandleToDevice(
unwrapped_ctx, tensorflow::unwrap(h), device_name, &status->status);
if (status->status.ok()) {
return tensorflow::wrap(result);
}
return nullptr;
}
void TFE_ContextAddFunctionDef(TFE_Context* ctx,
const char* serialized_function_def, size_t size,
TF_Status* status) {
tensorflow::FunctionDef function_def;
if (!function_def.ParseFromArray(serialized_function_def, size)) {
status->status =
tensorflow::errors::InvalidArgument("Invalid FunctionDef proto");
return;
}
AnnotateEagerRuntimeConstructionContext(function_def);
status->status = tensorflow::unwrap(ctx)->AddFunctionDef(function_def);
}
void TFE_ContextAddFunction(TFE_Context* ctx, TF_Function* function,
TF_Status* status) {
auto fdef_or = function->record->mutable_fdef();
if (!fdef_or.ok()) {
status->status = fdef_or.status();
return;
}
AnnotateEagerRuntimeConstructionContext(*fdef_or.value());
status->status = tensorflow::unwrap(ctx)->AddFunctionDefWithStackTraces(
*fdef_or.value(), function->record->stack_traces());
}
TF_Function* TFE_ContextGetFunction(TFE_Context* ctx, const char* name,
TF_Status* status) {
tensorflow::core::RefCountPtr<tensorflow::FunctionRecord> record =
tensorflow::unwrap(ctx)->FindRecord(name);
if (record == nullptr) {
status->status = tensorflow::errors::NotFound(
"Unable to find Function with name: ", name);
return nullptr;
}
TF_Function* result = new TF_Function();
record->Ref();
result->record = record.get();
return result;
}
void TFE_ContextRemoveFunction(TFE_Context* ctx, const char* name,
TF_Status* status) {
status->status = tensorflow::unwrap(ctx)->RemoveFunction(name);
}
unsigned char TFE_ContextHasFunction(TFE_Context* ctx, const char* name) {
return tensorflow::unwrap(ctx)->FindFunctionDef(name) != nullptr;
}
void TFE_ContextEnableRunMetadata(TFE_Context* ctx) {
tensorflow::unwrap(ctx)->SetShouldStoreGraphs(true);
}
void TFE_ContextDisableRunMetadata(TFE_Context* ctx) {
tensorflow::unwrap(ctx)->SetShouldStoreGraphs(false);
}
}
TFE_TensorHandle* TFE_NewTensorHandle(const tensorflow::Tensor& t,
TF_Status* status) {
return tensorflow::wrap(tensorflow::TensorHandle::CreateLocalHandle(t));
}
void TFE_ContextExportRunMetadata(TFE_Context* ctx, TF_Buffer* buf,
TF_Status* status) {
auto* context = tensorflow::unwrap(ctx);
status->status = context->AsyncWait();
if (!status->status.ok()) return;
auto run_metadata = context->ExportRunMetadata();
status->status = MessageToBuffer(*run_metadata, buf);
}
namespace {
TFE_Op* GetFunc(TFE_Context* ctx, const tensorflow::NameAttrList& func,
TF_Status* status) {
TFE_Op* func_op = TFE_NewOp(ctx, func.name().data(), status);
for (const auto& attr : func.attr()) {
if (!status->status.ok()) return nullptr;
SetOpAttrValueScalar(ctx, func_op, attr.second, attr.first.data(), status);
if (!status->status.ok()) return nullptr;
}
return func_op;
}
}
void TFE_ContextStartStep(TFE_Context* ctx) {
tensorflow::unwrap(ctx)->StartStep();
}
void TFE_ContextEndStep(TFE_Context* ctx) {
tensorflow::unwrap(ctx)->EndStep();
}
const TFE_OpAttrs* TFE_OpGetAttrs(const TFE_Op* op) {
return tensorflow::wrap(tensorflow::unwrap(op)->GetOpAttrs());
}
void TFE_OpAddAttrs(TFE_Op* op, const TFE_OpAttrs* attrs) {
tensorflow::unwrap(op)->AddAttrs(tensorflow::unwrap(attrs));
}
void TFE_OpAttrsSerialize(const TFE_OpAttrs* attrs, TF_Buffer* buf,
TF_Status* status) {
tensorflow::NameAttrList name_and_attrs;
tensorflow::unwrap(attrs)->GetNameAttrList(&name_and_attrs);
status->status = MessageToBuffer(name_and_attrs, buf);
}
namespace tensorflow {
void SetOpAttrValueScalar(TFE_Context* ctx, TFE_Op* op,
const tensorflow::AttrValue& default_value,
const char* attr_name, TF_Status* status) {
switch (default_value.value_case()) {
case tensorflow::AttrValue::kS: {
const string& v = default_value.s();
TFE_OpSetAttrString(op, attr_name, v.data(), v.size());
break;
}
case tensorflow::AttrValue::kI:
TFE_OpSetAttrInt(op, attr_name, static_cast<int64_t>(default_value.i()));
break;
case tensorflow::AttrValue::kF:
TFE_OpSetAttrFloat(op, attr_name, default_value.f());
break;
case tensorflow::AttrValue::kB:
TFE_OpSetAttrBool(op, attr_name, default_value.b());
break;
case tensorflow::AttrValue::kType:
TFE_OpSetAttrType(op, attr_name,
static_cast<TF_DataType>(default_value.type()));
break;
case tensorflow::AttrValue::kShape: {
const auto& tensor_shape = default_value.shape();
if (tensor_shape.unknown_rank()) {
TFE_OpSetAttrShape(op, attr_name, nullptr, -1, status);
} else {
const auto num_dims = tensor_shape.dim_size();
std::unique_ptr<int64_t[]> dims(new int64_t[num_dims]);
for (int i = 0; i < num_dims; ++i) {
dims[i] = tensor_shape.dim(i).size();
}
TFE_OpSetAttrShape(op, attr_name, dims.get(), num_dims, status);
}
} break;
case tensorflow::AttrValue::kFunc: {
const auto func_op = GetFunc(ctx, default_value.func(), status);
if (!status->status.ok()) return;
TFE_OpSetAttrFunction(op, attr_name, func_op);
TFE_DeleteOp(func_op);
} break;
case tensorflow::AttrValue::kList: {
if (const int s_size = default_value.list().s_size()) {
absl::InlinedVector<const void*, 4> values_vector;
values_vector.reserve(s_size);
absl::InlinedVector<size_t, 4> lengths_vector;
lengths_vector.reserve(s_size);
for (int i = 0; i < s_size; ++i) {
const string& v = default_value.list().s(i);
values_vector.push_back(v.data());
lengths_vector.push_back(v.size());
}
TFE_OpSetAttrStringList(op, attr_name, values_vector.data(),
lengths_vector.data(), s_size);
}
if (const int i_size = default_value.list().i_size()) {
absl::InlinedVector<int64_t, 4> i_vector;
i_vector.reserve(i_size);
for (int i = 0; i < i_size; ++i) {
i_vector.push_back(default_value.list().i(i));
}
TFE_OpSetAttrIntList(op, attr_name, i_vector.data(), i_size);
}
if (const int f_size = default_value.list().f_size()) {
absl::InlinedVector<float, 4> f_vector;
f_vector.reserve(f_size);
for (int i = 0; i < f_size; ++i) {
f_vector.push_back(default_value.list().f(i));
}
TFE_OpSetAttrFloatList(op, attr_name, f_vector.data(), f_size);
}
if (const int b_size = default_value.list().b_size()) {
absl::InlinedVector<unsigned char, 4> b_vector;
b_vector.reserve(b_size);
for (int i = 0; i < b_size; i++) {
b_vector.push_back(default_value.list().b(i));
}
TFE_OpSetAttrBoolList(op, attr_name, b_vector.data(), b_size);
}
if (const int type_size = default_value.list().type_size()) {
absl::InlinedVector<unsigned int, 4> type_vector;
type_vector.reserve(type_size);
for (int i = 0; i < type_size; ++i) {
type_vector.push_back(default_value.list().type(i));
}
TFE_OpSetAttrTypeList(
op, attr_name,
reinterpret_cast<const TF_DataType*>(type_vector.data()),
type_size);
}
if (default_value.list().shape_size() > 0 ||
default_value.list().func_size() > 0 ||
default_value.list().tensor_size() > 0) {
TF_SetStatus(
status, TF_UNIMPLEMENTED,
tensorflow::strings::StrCat("Unable to get setfor default value: ",
default_value.DebugString())
.data());
}
} break;
case tensorflow::AttrValue::kTensor:
TF_FALLTHROUGH_INTENDED;
case tensorflow::AttrValue::kPlaceholder:
TF_FALLTHROUGH_INTENDED;
case tensorflow::AttrValue::VALUE_NOT_SET:
TF_SetStatus(
status, TF_UNIMPLEMENTED,
tensorflow::strings::StrCat("Unable to get setfor default value: ",
default_value.DebugString())
.data());
}
}
}
namespace {
TFE_TensorHandle* DefaultCustomDevicePack(TFE_Context* context,
TFE_TensorHandle** handles,
int num_handles, TF_Status* status,
void* device_info) {
TF_SetStatus(status, TF_UNIMPLEMENTED,
"This custom device does not support packing tensors.");
return nullptr;
}
}
extern "C" {
bool TFE_IsCustomDevice(TFE_Context* ctx, const char* device_name) {
return tensorflow::unwrap(ctx)->IsCustomDevice(device_name);
}
void TFE_RegisterCustomDevice(TFE_Context* ctx, TFE_CustomDevice device,
const char* device_name, void* device_info,
TF_Status* status) {
if (device.pack == nullptr) {
device.pack = &DefaultCustomDevicePack;
}
auto custom_device = std::make_unique<tensorflow::CustomDeviceAPI>(
ctx, device, device_info, device_name);
status->status = tensorflow::unwrap(ctx)->RegisterCustomDevice(
device_name, std::move(custom_device));
}
} | #include "tensorflow/c/eager/c_api.h"
#include <string.h>
#include <memory>
#include <string>
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/platform/platform.h"
#include "absl/strings/match.h"
#include "tensorflow/c/eager/c_api_experimental.h"
#include "tensorflow/c/eager/c_api_internal.h"
#include "tensorflow/c/eager/c_api_test_util.h"
#include "tensorflow/c/eager/tfe_op_internal.h"
#include "tensorflow/c/eager/tfe_tensorhandle_internal.h"
#include "tensorflow/c/tf_datatype.h"
#include "tensorflow/c/tf_status.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/core/common_runtime/eager/eager_operation.h"
#include "tensorflow/core/common_runtime/eager/tensor_handle.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/platform/casts.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/protobuf/cluster.pb.h"
#include "tensorflow/core/protobuf/config.pb.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
#include "tensorflow/core/protobuf/tensorflow_server.pb.h"
using tensorflow::string;
namespace {
void BM_InitOp(::testing::benchmark::State& state) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
for (auto s : state) {
TFE_Op* matmul = MatMulOp(ctx, m, m);
TFE_DeleteOp(matmul);
}
TFE_DeleteTensorHandle(m);
TFE_DeleteContext(ctx);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
BENCHMARK(BM_InitOp);
void BM_Execute(::testing::benchmark::State& state) {
const int async = state.range(0);
state.SetLabel(async ? "ExecuteAsync" : "Execute");
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_Op* matmul = TFE_NewOp(ctx, "MatMul", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* retvals[1];
int num_retvals = 1;
for (auto s : state) {
TFE_OpReset(matmul, "MatMul", nullptr, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(matmul, m, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(matmul, m, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(matmul, &retvals[0], &num_retvals, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
if (state.iterations() >= state.max_iterations && async) {
TFE_Executor* executor = TFE_ContextGetExecutorForThread(ctx);
TFE_ExecutorWaitForAllPendingNodes(executor, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteExecutor(executor);
}
}
TFE_DeleteOp(matmul);
TFE_DeleteTensorHandle(m);
TFE_DeleteContext(ctx);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
BENCHMARK(BM_Execute)->Arg(0)->Arg(1);
void BM_Execute_Identity(::testing::benchmark::State& state) {
const int async = state.range(0);
state.SetLabel(async ? "ExecuteIdentityAsync" : "ExecuteIdentity");
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_Op* identity = TFE_NewOp(ctx, "Identity", status);
TFE_TensorHandle* retvals[1];
int num_retvals = 1;
for (auto s : state) {
TFE_OpReset(identity, "Identity", nullptr, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(identity, m, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(identity, &retvals[0], &num_retvals, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
if (state.iterations() >= state.max_iterations && async) {
TFE_Executor* executor = TFE_ContextGetExecutorForThread(ctx);
TFE_ExecutorWaitForAllPendingNodes(executor, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteExecutor(executor);
}
}
TFE_DeleteOp(identity);
TFE_DeleteTensorHandle(m);
TFE_DeleteContext(ctx);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
BENCHMARK(BM_Execute_Identity)->Arg(0)->Arg(1);
TEST(CAPI, Context) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
TFE_DeleteContextOptions(opts);
TF_DeviceList* devices = TFE_ContextListDevices(ctx, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContext(ctx);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
const int num_devices = TF_DeviceListCount(devices);
EXPECT_GE(num_devices, 1) << "At least one CPU device should exist";
for (int i = 0; i < num_devices; ++i) {
EXPECT_NE("", TF_DeviceListName(devices, i, status)) << i;
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
}
TF_DeleteDeviceList(devices);
TF_DeleteStatus(status);
}
TEST(CAPI, TensorHandle) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status.get());
CHECK_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* h = TestMatrixTensorHandle(ctx);
EXPECT_EQ(TF_FLOAT, TFE_TensorHandleDataType(h));
TF_Tensor* t = TFE_TensorHandleResolve(h, status.get());
ASSERT_EQ(16, TF_TensorByteSize(t));
float data[4] = {0};
memcpy(&data[0], TF_TensorData(t), TF_TensorByteSize(t));
EXPECT_EQ(1.0, data[0]);
EXPECT_EQ(2.0, data[1]);
EXPECT_EQ(3.0, data[2]);
EXPECT_EQ(4.0, data[3]);
TF_DeleteTensor(t);
TFE_DeleteTensorHandle(h);
TFE_DeleteContext(ctx);
}
void TensorHandleCopyBetweenDevices(bool async) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status.get());
TFE_DeleteContextOptions(opts);
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_TensorHandle* hcpu = TestMatrixTensorHandle(ctx);
TF_Tensor* t = TFE_TensorHandleResolve(hcpu, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TF_DeviceList* devices = TFE_ContextListDevices(ctx, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
const int num_devices = TF_DeviceListCount(devices);
const char* kCPUDevice = "CPU:0";
for (int i = 0; i < num_devices; ++i) {
const string name(TF_DeviceListName(devices, i, status.get()));
if (TF_GetCode(status.get()) != TF_OK) {
ADD_FAILURE() << i << " -- " << TF_Message(status.get());
continue;
}
auto tag = tensorflow::strings::StrCat("Device #", i, " (", name, ")");
TFE_TensorHandle* hdevice =
TFE_TensorHandleCopyToDevice(hcpu, ctx, name.c_str(), status.get());
if (TF_GetCode(status.get()) != TF_OK) {
ADD_FAILURE() << tag << " -- " << TF_Message(status.get());
continue;
}
TFE_TensorHandle* hdevice2 =
TFE_TensorHandleCopyToDevice(hdevice, ctx, name.c_str(), status.get());
if (TF_GetCode(status.get()) != TF_OK) {
ADD_FAILURE() << tag << " -- " << TF_Message(status.get());
continue;
}
TFE_DeleteTensorHandle(hdevice);
TFE_TensorHandle* hcopy =
TFE_TensorHandleCopyToDevice(hdevice2, ctx, kCPUDevice, status.get());
if (TF_GetCode(status.get()) != TF_OK) {
ADD_FAILURE() << tag << " -- " << TF_Message(status.get());
continue;
}
TFE_DeleteTensorHandle(hdevice2);
TF_Tensor* tcopy = TFE_TensorHandleResolve(hcopy, status.get());
TFE_DeleteTensorHandle(hcopy);
if (TF_GetCode(status.get()) != TF_OK) {
ADD_FAILURE() << tag;
continue;
}
EXPECT_EQ(TF_TensorByteSize(t), TF_TensorByteSize(tcopy)) << tag;
EXPECT_EQ(
0, memcmp(TF_TensorData(t), TF_TensorData(tcopy), TF_TensorByteSize(t)))
<< tag;
TF_DeleteTensor(tcopy);
}
TF_DeleteDeviceList(devices);
TF_DeleteTensor(t);
TFE_DeleteTensorHandle(hcpu);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TensorHandleCopyBetweenDevices) {
TensorHandleCopyBetweenDevices(false);
}
TEST(CAPI, TensorHandleCopyBetweenDevicesAsync) {
TensorHandleCopyBetweenDevices(true);
}
void TensorHandleCopyBetweenDevicesError(bool async) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status.get());
TFE_DeleteContextOptions(opts);
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_TensorHandle* hcpu = TestMatrixTensorHandle(ctx);
const char* kErrorDevice = "NoSuchDevice:0";
TFE_TensorHandle* hdevice =
TFE_TensorHandleCopyToDevice(hcpu, ctx, kErrorDevice, status.get());
EXPECT_NE(TF_OK, TF_GetCode(status.get()));
const char* msg = "NoSuchDevice:0 unknown device";
EXPECT_TRUE(strstr(TF_Message(status.get()), msg) != nullptr)
<< TF_Message(status.get());
TF_SetStatus(status.get(), TF_OK, "");
const char* kCPUDevice = "CPU:0";
TFE_TensorHandle* hcopy =
TFE_TensorHandleCopyToDevice(hcpu, ctx, kCPUDevice, status.get());
EXPECT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_Executor* executor = TFE_ContextGetExecutorForThread(ctx);
TFE_ExecutorWaitForAllPendingNodes(executor, status.get());
EXPECT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_DeleteExecutor(executor);
TFE_DeleteTensorHandle(hcopy);
TFE_DeleteTensorHandle(hcpu);
if (hdevice != nullptr) TFE_DeleteTensorHandle(hdevice);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TensorHandleCopyBetweenDevicesError) {
TensorHandleCopyBetweenDevicesError(false);
}
TEST(CAPI, TensorHandleCopyBetweenDevicesErrorAsync) {
TensorHandleCopyBetweenDevicesError(true);
}
void TensorHandleCopyBetweenTwoGPUDevices(bool async) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status.get());
TFE_DeleteContextOptions(opts);
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_TensorHandle* hcpu = TestMatrixTensorHandle(ctx);
TF_Tensor* t = TFE_TensorHandleResolve(hcpu, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TF_DeviceList* devices = TFE_ContextListDevices(ctx, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
const int num_devices = TF_DeviceListCount(devices);
bool has_gpu0 = false;
bool has_gpu1 = false;
for (int i = 0; i < num_devices; ++i) {
const char* dev = TF_DeviceListName(devices, i, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
string device_name(dev);
if (device_name.find("GPU:0") != string::npos) {
has_gpu0 = true;
}
if (device_name.find("GPU:1") != string::npos) {
has_gpu1 = true;
}
}
const char* kCPUDevice = "CPU:0";
if (!has_gpu0 || !has_gpu1) {
TF_DeleteDeviceList(devices);
TF_DeleteTensor(t);
TFE_DeleteTensorHandle(hcpu);
TFE_DeleteContext(ctx);
return;
}
const string gpu_1_name(TF_DeviceListName(devices, 1, status.get()));
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK);
const string gpu_2_name(TF_DeviceListName(devices, 2, status.get()));
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK);
TFE_TensorHandle* hdevice =
TFE_TensorHandleCopyToDevice(hcpu, ctx, gpu_1_name.c_str(), status.get());
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK);
TFE_TensorHandle* hdevice2 = TFE_TensorHandleCopyToDevice(
hdevice, ctx, gpu_2_name.c_str(), status.get());
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK);
TFE_DeleteTensorHandle(hdevice);
TFE_TensorHandle* hcopy =
TFE_TensorHandleCopyToDevice(hdevice2, ctx, kCPUDevice, status.get());
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK);
TFE_DeleteTensorHandle(hdevice2);
TF_Tensor* tcopy = TFE_TensorHandleResolve(hcopy, status.get());
TFE_DeleteTensorHandle(hcopy);
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK);
EXPECT_EQ(TF_TensorByteSize(t), TF_TensorByteSize(tcopy));
EXPECT_EQ(
0, memcmp(TF_TensorData(t), TF_TensorData(tcopy), TF_TensorByteSize(t)));
TF_DeleteTensor(tcopy);
TF_DeleteDeviceList(devices);
TF_DeleteTensor(t);
TFE_DeleteTensorHandle(hcpu);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TensorHandleCopyBetweenTwoGPUDevices) {
TensorHandleCopyBetweenTwoGPUDevices(false);
}
TEST(CAPI, TensorHandleCopyBetweenTwoGPUDevicesAsync) {
TensorHandleCopyBetweenTwoGPUDevices(true);
}
void TensorHandleSilentCopy(bool async,
TFE_ContextDevicePlacementPolicy global_policy,
TFE_ContextDevicePlacementPolicy thread_policy,
bool cpu_op) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_ContextOptionsSetDevicePlacementPolicy(opts, global_policy);
TFE_Context* ctx = TFE_NewContext(opts, status.get());
if (thread_policy != global_policy) {
TFE_ContextSetThreadLocalDevicePlacementPolicy(ctx, thread_policy);
}
TFE_DeleteContextOptions(opts);
ASSERT_EQ(TF_GetCode(status.get()), TF_OK) << TF_Message(status.get());
TFE_TensorHandle* hcpu = TestMatrixTensorHandle(ctx);
TF_Tensor* t = TFE_TensorHandleResolve(hcpu, status.get());
ASSERT_EQ(TF_GetCode(status.get()), TF_OK) << TF_Message(status.get());
string gpu_device_name;
if (GetDeviceName(ctx, &gpu_device_name, "GPU")) {
TFE_TensorHandle* hgpu = TFE_TensorHandleCopyToDevice(
hcpu, ctx, gpu_device_name.c_str(), status.get());
ASSERT_EQ(TF_GetCode(status.get()), TF_OK) << TF_Message(status.get());
auto cpu_arg =
tensorflow::TensorHandleFromInterface(tensorflow::unwrap(hcpu));
auto gpu_arg =
tensorflow::TensorHandleFromInterface(tensorflow::unwrap(hgpu));
auto gpu_device = gpu_arg->device();
ASSERT_FALSE(cpu_arg->HasLocalMirror(gpu_device));
TFE_Op* matmul = MatMulOp(ctx, hcpu, hgpu);
if (cpu_op) {
string cpu_device_name;
ASSERT_TRUE(GetDeviceName(ctx, &cpu_device_name, "CPU"));
TFE_OpSetDevice(matmul, cpu_device_name.c_str(), status.get());
} else {
TFE_OpSetDevice(matmul, gpu_device_name.c_str(), status.get());
}
ASSERT_EQ(TF_GetCode(status.get()), TF_OK) << TF_Message(status.get());
TFE_TensorHandle* retvals[1];
int num_retvals = 1;
TFE_Execute(matmul, &retvals[0], &num_retvals, status.get());
ASSERT_EQ(TF_GetCode(status.get()), TF_OK) << TF_Message(status.get());
ASSERT_TRUE(cpu_arg->HasLocalMirror(gpu_device));
TFE_DeleteOp(matmul);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteTensorHandle(hgpu);
}
TF_DeleteTensor(t);
TFE_DeleteTensorHandle(hcpu);
TFE_Executor* executor = TFE_ContextGetExecutorForThread(ctx);
TFE_ExecutorWaitForAllPendingNodes(executor, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_DeleteExecutor(executor);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TensorHandleSilentCopy) {
TensorHandleSilentCopy(false, TFE_DEVICE_PLACEMENT_SILENT,
TFE_DEVICE_PLACEMENT_SILENT, false);
}
TEST(CAPI, TensorHandleSilentCopyAsync) {
TensorHandleSilentCopy(true, TFE_DEVICE_PLACEMENT_SILENT,
TFE_DEVICE_PLACEMENT_SILENT, false);
}
TEST(CAPI, TensorHandleSilentCopyLocalPolicy) {
TensorHandleSilentCopy(false, TFE_DEVICE_PLACEMENT_EXPLICIT,
TFE_DEVICE_PLACEMENT_SILENT, false);
}
TEST(CAPI, TensorHandleSilentCopyLocalPolicyAsync) {
TensorHandleSilentCopy(true, TFE_DEVICE_PLACEMENT_EXPLICIT,
TFE_DEVICE_PLACEMENT_SILENT, false);
}
void SetAndGetOpDevices(bool async) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_Op* matmul = MatMulOp(ctx, m, m);
string gpu_device_name;
if (GetDeviceName(ctx, &gpu_device_name, "GPU")) {
TFE_OpSetDevice(matmul, "GPU:0", status);
ASSERT_TRUE(TF_GetCode(status) == TF_OK) << TF_Message(status);
const char* device_name = TFE_OpGetDevice(matmul, status);
ASSERT_TRUE(strstr(device_name, "GPU:0") != nullptr);
TFE_OpSetDevice(matmul, "CPU:0", status);
ASSERT_TRUE(TF_GetCode(status) == TF_OK) << TF_Message(status);
device_name = TFE_OpGetDevice(matmul, status);
ASSERT_TRUE(strstr(device_name, "CPU:0") != nullptr);
}
TFE_DeleteOp(matmul);
TFE_DeleteTensorHandle(m);
TFE_DeleteContext(ctx);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
TEST(CAPI, TensorHandleNullptr) {
TFE_TensorHandle* h = nullptr;
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TF_Tensor* t = TFE_TensorHandleResolve(h, status.get());
ASSERT_EQ(TF_INVALID_ARGUMENT, TF_GetCode(status.get()));
ASSERT_EQ(t, nullptr);
ASSERT_EQ("Invalid handle", string(TF_Message(status.get())));
TF_SetStatus(status.get(), TF_OK, "");
const char* device_name = TFE_TensorHandleDeviceName(h, status.get());
ASSERT_EQ(TF_INVALID_ARGUMENT, TF_GetCode(status.get()));
ASSERT_EQ(device_name, nullptr);
ASSERT_EQ("Invalid handle", string(TF_Message(status.get())));
TF_SetStatus(status.get(), TF_OK, "");
device_name = TFE_TensorHandleBackingDeviceName(h, status.get());
ASSERT_EQ(TF_INVALID_ARGUMENT, TF_GetCode(status.get()));
ASSERT_EQ(device_name, nullptr);
ASSERT_EQ("Invalid handle", string(TF_Message(status.get())));
TF_SetStatus(status.get(), TF_OK, "");
int num_dims = TFE_TensorHandleNumDims(h, status.get());
ASSERT_EQ(TF_INVALID_ARGUMENT, TF_GetCode(status.get()));
ASSERT_EQ(num_dims, -1);
ASSERT_EQ("Invalid handle", string(TF_Message(status.get())));
TF_SetStatus(status.get(), TF_OK, "");
int dim = TFE_TensorHandleDim(h, 0, status.get());
ASSERT_EQ(TF_INVALID_ARGUMENT, TF_GetCode(status.get()));
ASSERT_EQ(dim, -1);
ASSERT_EQ("Invalid handle", string(TF_Message(status.get())));
}
TEST(CAPI, TensorHandleDevices) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status.get());
TFE_DeleteContextOptions(opts);
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_TensorHandle* hcpu = TestMatrixTensorHandle(ctx);
const char* device_name = TFE_TensorHandleDeviceName(hcpu, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
ASSERT_TRUE(absl::StrContains(device_name, "CPU:0")) << device_name;
const char* backing_device_name =
TFE_TensorHandleBackingDeviceName(hcpu, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
ASSERT_TRUE(absl::StrContains(backing_device_name, "CPU:0"))
<< backing_device_name;
string gpu_device_name;
if (GetDeviceName(ctx, &gpu_device_name, "GPU")) {
TFE_TensorHandle* hgpu = TFE_TensorHandleCopyToDevice(
hcpu, ctx, gpu_device_name.c_str(), status.get());
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK) << TF_Message(status.get());
TFE_Op* shape_op = ShapeOp(ctx, hgpu);
TFE_OpSetDevice(shape_op, gpu_device_name.c_str(), status.get());
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK) << TF_Message(status.get());
TFE_TensorHandle* retvals[1];
int num_retvals = 1;
TFE_Execute(shape_op, &retvals[0], &num_retvals, status.get());
ASSERT_TRUE(TF_GetCode(status.get()) == TF_OK) << TF_Message(status.get());
device_name = TFE_TensorHandleDeviceName(retvals[0], status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
ASSERT_TRUE(absl::StrContains(device_name, "GPU:0")) << device_name;
backing_device_name =
TFE_TensorHandleBackingDeviceName(retvals[0], status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
ASSERT_TRUE(absl::StrContains(backing_device_name, "CPU:0"))
<< backing_device_name;
TFE_DeleteOp(shape_op);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteTensorHandle(hgpu);
}
TFE_DeleteTensorHandle(hcpu);
TFE_Executor* executor = TFE_ContextGetExecutorForThread(ctx);
TFE_ExecutorWaitForAllPendingNodes(executor, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_DeleteExecutor(executor);
TFE_DeleteContext(ctx);
}
void ExecuteAdd(bool async, bool forward_input, bool tfrt) {
#ifdef PLATFORM_WINDOWS
return;
#else
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetTfrt(opts, tfrt);
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* n = TestMatrixTensorHandle100x100(ctx);
std::string gpu_device_name;
if (GetDeviceName(ctx, &gpu_device_name, "GPU")) {
TFE_TensorHandle* n_gpu =
TFE_TensorHandleCopyToDevice(n, ctx, gpu_device_name.c_str(), status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteTensorHandle(n);
n = n_gpu;
}
TFE_TensorHandle* m = TestMatrixTensorHandle100x100(ctx);
TF_Tensor* orig = TFE_TensorHandleResolve(n, status);
void* orig_ptr = TF_TensorData(orig);
TF_DeleteTensor(orig);
TFE_Op* add_op = AddOp(ctx, n, m);
std::string cpu_device_name;
ASSERT_TRUE(GetDeviceName(ctx, &cpu_device_name, "CPU"));
TFE_OpSetDevice(add_op, cpu_device_name.c_str(), status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
if (forward_input) {
TFE_DeleteTensorHandle(n);
}
int num_retvals = 1;
if (async) {
for (int i = 0; i < 100000; ++i) {
TFE_Op* add_op_dummy = AddOp(ctx, m, m);
TFE_OpSetDevice(add_op_dummy, cpu_device_name.c_str(), status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* dummy = nullptr;
TFE_Execute(add_op_dummy, &dummy, &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteTensorHandle(dummy);
TFE_DeleteOp(add_op_dummy);
}
}
TFE_TensorHandle* retval = nullptr;
TFE_Execute(add_op, &retval, &num_retvals, status);
EXPECT_EQ(1, num_retvals);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
if (!forward_input) {
TFE_DeleteTensorHandle(n);
}
TFE_DeleteOp(add_op);
TF_Tensor* t = TFE_TensorHandleResolve(retval, status);
if (async) {
if (forward_input) {
EXPECT_EQ(orig_ptr, TF_TensorData(t));
} else {
EXPECT_EQ(orig_ptr, TF_TensorData(t));
}
} else {
if (forward_input) {
EXPECT_EQ(orig_ptr, TF_TensorData(t));
} else {
EXPECT_NE(orig_ptr, TF_TensorData(t));
}
}
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteTensorHandle(m);
TFE_DeleteTensorHandle(retval);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float result[100 * 100] = {0};
EXPECT_EQ(sizeof(result), TF_TensorByteSize(t));
memcpy(&result[0], TF_TensorData(t), TF_TensorByteSize(t));
TF_DeleteTensor(t);
for (int i = 0; i < 100 * 100; ++i) {
EXPECT_EQ(2.0f, result[i]);
}
TFE_DeleteContext(ctx);
TF_DeleteStatus(status);
#endif
}
TEST(CAPI, ExecuteAdd) {
ExecuteAdd(
false,
false,
false);
}
TEST(CAPI, DISABLED_ExecuteAddAsync) {
ExecuteAdd(
true,
false,
false);
}
TEST(CAPI, ExecuteAddForward) {
ExecuteAdd(
false,
true,
false);
}
TEST(CAPI, ExecuteAddForwardAsync) {
ExecuteAdd(
true,
true,
false);
}
#ifdef PLATFORM_GOOGLE
TEST(CAPI, DISABLED_ExecuteAddTfrt) {
ExecuteAdd(
false,
false,
true);
}
#endif
void Execute_MatMul_CPU(bool async) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_Op* matmul = MatMulOp(ctx, m, m);
TFE_TensorHandle* retvals[2] = {nullptr, nullptr};
int num_retvals = 2;
TFE_Execute(matmul, &retvals[0], &num_retvals, status);
EXPECT_EQ(1, num_retvals);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(matmul);
TFE_DeleteTensorHandle(m);
TF_Tensor* t = TFE_TensorHandleResolve(retvals[0], status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteContext(ctx);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float product[4] = {0};
EXPECT_EQ(sizeof(product), TF_TensorByteSize(t));
memcpy(&product[0], TF_TensorData(t), TF_TensorByteSize(t));
TF_DeleteTensor(t);
EXPECT_EQ(7, product[0]);
EXPECT_EQ(10, product[1]);
EXPECT_EQ(15, product[2]);
EXPECT_EQ(22, product[3]);
TF_DeleteStatus(status);
}
TEST(CAPI, Execute_MatMul_CPU) { Execute_MatMul_CPU(false); }
TEST(CAPI, Execute_MatMul_CPUAsync) { Execute_MatMul_CPU(true); }
void Execute_MatMul_CPU_Runtime_Error(bool async) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* m2 = DoubleTestMatrixTensorHandle3X2(ctx);
TFE_Op* matmul = MatMulOp(ctx, m1, m2);
TFE_OpSetDevice(matmul, "/job:localhost/replica:0/task:0/device:CPU:0",
status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Op* matmul2 = MatMulOp(ctx, m1, m1);
TFE_OpSetDevice(matmul2, "/job:localhost/replica:0/task:0/device:CPU:0",
status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* retvals[1] = {nullptr};
int num_retvals = 1;
TFE_Execute(matmul, &retvals[0], &num_retvals, status);
TFE_DeleteOp(matmul);
if (!async) {
EXPECT_NE(TF_OK, TF_GetCode(status));
} else {
TF_Tensor* t = TFE_TensorHandleResolve(retvals[0], status);
EXPECT_NE(TF_OK, TF_GetCode(status));
EXPECT_EQ(nullptr, t);
const char* msg = "Matrix size-incompatible: In[0]: [2,2], In[1]: [3,2]";
EXPECT_TRUE(strstr(TF_Message(status), msg) != nullptr)
<< TF_Message(status);
TF_SetStatus(status, TF_OK, "");
TFE_DeleteTensorHandle(retvals[0]);
TFE_Executor* executor = TFE_ContextGetExecutorForThread(ctx);
TFE_ExecutorWaitForAllPendingNodes(executor, status);
EXPECT_NE(TF_OK, TF_GetCode(status));
TF_SetStatus(status, TF_OK, "");
retvals[0] = nullptr;
TFE_Execute(matmul2, &retvals[0], &num_retvals, status);
EXPECT_NE(TF_OK, TF_GetCode(status));
TFE_ExecutorClearError(executor);
TFE_ExecutorWaitForAllPendingNodes(executor, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteExecutor(executor);
}
TF_SetStatus(status, TF_OK, "");
if (retvals[0] != nullptr) {
TFE_DeleteTensorHandle(retvals[0]);
}
retvals[0] = nullptr;
TFE_Execute(matmul2, &retvals[0], &num_retvals, status);
EXPECT_EQ(TF_OK, TF_GetCode(status));
TF_Tensor* t = TFE_TensorHandleResolve(retvals[0], status);
EXPECT_EQ(TF_OK, TF_GetCode(status));
TF_DeleteTensor(t);
TFE_DeleteOp(matmul2);
TFE_DeleteTensorHandle(m1);
TFE_DeleteTensorHandle(m2);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteContext(ctx);
TF_DeleteStatus(status);
}
TEST(CAPI, Execute_MatMul_CPU_Runtime_Error) {
Execute_MatMul_CPU_Runtime_Error(false);
}
TEST(CAPI, Execute_MatMul_CPU_Runtime_ErrorAsync) {
Execute_MatMul_CPU_Runtime_Error(true);
}
void Execute_MatMul_CPU_Type_Error(bool async) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* m2 = DoubleTestMatrixTensorHandle(ctx);
TFE_Op* matmul = MatMulOp(ctx, m1, m2);
TFE_TensorHandle* retvals[1] = {nullptr};
int num_retvals = 1;
TFE_Execute(matmul, &retvals[0], &num_retvals, status);
EXPECT_NE(TF_OK, TF_GetCode(status));
TFE_DeleteOp(matmul);
TFE_DeleteTensorHandle(m1);
TFE_DeleteTensorHandle(m2);
if (retvals[0] != nullptr) {
TFE_DeleteTensorHandle(retvals[0]);
}
TFE_DeleteContext(ctx);
TF_DeleteStatus(status);
}
TEST(CAPI, Execute_MatMul_CPU_Type_Error) {
Execute_MatMul_CPU_Type_Error(false);
}
TEST(CAPI, Execute_MatMul_CPU_Type_ErrorAsync) {
Execute_MatMul_CPU_Type_Error(true);
}
TEST(CAPI, Execute_Min_CPU) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* input = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* axis = TestAxisTensorHandle(ctx);
TFE_Op* minOp = MinOp(ctx, input, axis);
TFE_TensorHandle* retvals[1] = {nullptr};
int num_retvals = 1;
TFE_Execute(minOp, &retvals[0], &num_retvals, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(minOp);
TFE_DeleteTensorHandle(input);
TFE_DeleteTensorHandle(axis);
ASSERT_EQ(1, num_retvals);
TF_Tensor* t = TFE_TensorHandleResolve(retvals[0], status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteTensorHandle(retvals[0]);
float output[2] = {0};
EXPECT_EQ(sizeof(output), TF_TensorByteSize(t));
memcpy(&output[0], TF_TensorData(t), TF_TensorByteSize(t));
TF_DeleteTensor(t);
EXPECT_EQ(1, output[0]);
EXPECT_EQ(3, output[1]);
TFE_DeleteContext(ctx);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
void ExecuteWithTracing(bool async) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
TFE_ContextEnableRunMetadata(ctx);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_Op* matmul = MatMulOp(ctx, m, m);
TFE_TensorHandle* retvals[1] = {nullptr};
int num_retvals = 1;
TFE_Execute(matmul, &retvals[0], &num_retvals, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(matmul);
TFE_DeleteTensorHandle(m);
TF_Buffer* b = TF_NewBuffer();
TFE_ContextExportRunMetadata(ctx, b, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::RunMetadata rm;
EXPECT_TRUE(
rm.ParseFromString({reinterpret_cast<const char*>(b->data), b->length}));
TF_DeleteBuffer(b);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(1, num_retvals);
TF_Tensor* t = TFE_TensorHandleResolve(retvals[0], status);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteContext(ctx);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float product[4] = {0};
EXPECT_EQ(sizeof(product), TF_TensorByteSize(t));
memcpy(&product[0], TF_TensorData(t), TF_TensorByteSize(t));
TF_DeleteTensor(t);
EXPECT_EQ(7, product[0]);
EXPECT_EQ(10, product[1]);
EXPECT_EQ(15, product[2]);
EXPECT_EQ(22, product[3]);
TF_DeleteStatus(status);
}
TEST(CAPI, ExecuteWithTracing) { ExecuteWithTracing(false); }
TEST(CAPI, ExecuteWithTracingAsync) { ExecuteWithTracing(true); }
REGISTER_OP("TestNonCommUnavailable")
.Output("out: string")
.Doc(R"doc(Test non-communication op throwing Unavailable error.)doc");
REGISTER_OP("TestCommUnavailable")
.Output("out: string")
.SetIsDistributedCommunication()
.Doc(R"doc(Test communication op throwing Unavailable error.)doc");
class TestUnavailableErrorOp : public tensorflow::OpKernel {
public:
explicit TestUnavailableErrorOp(tensorflow::OpKernelConstruction* ctx)
: tensorflow::OpKernel(ctx) {}
void Compute(tensorflow::OpKernelContext* ctx) override {
ctx->SetStatus(tensorflow::errors::Unavailable("Test error."));
}
};
REGISTER_KERNEL_BUILDER(
Name("TestNonCommUnavailable").Device(tensorflow::DEVICE_DEFAULT),
TestUnavailableErrorOp);
REGISTER_KERNEL_BUILDER(
Name("TestCommUnavailable").Device(tensorflow::DEVICE_DEFAULT),
TestUnavailableErrorOp);
string FunctionWithErrorOp(const tensorflow::StringPiece op_name) {
const std::string& func_str =
" signature {"
" name: 'FunctionWith__OP_NAME__'"
" output_arg {"
" name: 'out'"
" type: DT_STRING"
" }"
" }"
" node_def {"
" name: 'error_op'"
" op: '__OP_NAME__'"
" }"
" ret {"
" key: 'out'"
" value: 'error_op:out'"
" }";
tensorflow::FunctionDef def;
CHECK(tensorflow::protobuf::TextFormat::ParseFromString(
tensorflow::str_util::StringReplace(func_str, "__OP_NAME__", op_name,
true),
&def));
return def.SerializeAsString();
}
TEST(CAPI, ExecuteOpAndFunctionWithError) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(false));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_Op* non_comm_op = TFE_NewOp(ctx, "TestNonCommUnavailable", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* retval[1] = {};
int num_retvals = 1;
TFE_Execute(non_comm_op, retval, &num_retvals, status);
EXPECT_EQ(TF_INTERNAL, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(non_comm_op);
TFE_Op* comm_op = TFE_NewOp(ctx, "TestCommUnavailable", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(comm_op, retval, &num_retvals, status);
EXPECT_EQ(TF_UNAVAILABLE, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(comm_op);
const string& fdef1 = FunctionWithErrorOp("TestNonCommUnavailable");
TFE_ContextAddFunctionDef(ctx, fdef1.data(), fdef1.size(), status);
TFE_Op* fn1 = TFE_NewOp(ctx, "FunctionWithTestNonCommUnavailable", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(fn1, retval, &num_retvals, status);
EXPECT_EQ(TF_INTERNAL, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(fn1);
const string& fdef2 = FunctionWithErrorOp("TestCommUnavailable");
TFE_ContextAddFunctionDef(ctx, fdef2.data(), fdef2.size(), status);
TFE_Op* fn2 = TFE_NewOp(ctx, "FunctionWithTestCommUnavailable", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(fn2, retval, &num_retvals, status);
EXPECT_EQ(TF_UNAVAILABLE, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(fn2);
TFE_DeleteContext(ctx);
TF_DeleteStatus(status);
}
string MatMulFunction() {
tensorflow::FunctionDef def;
CHECK(tensorflow::protobuf::TextFormat::ParseFromString(
" signature {"
" name: 'MatMulFunction'"
" input_arg {"
" name: 'a'"
" type: DT_FLOAT"
" }"
" output_arg {"
" name: 'm'"
" type: DT_FLOAT"
" }"
" }"
" node_def {"
" name: 'matmul'"
" op: 'MatMul'"
" input: 'a'"
" input: 'a'"
" attr {"
" key: 'T'"
" value {"
" type: DT_FLOAT"
" }"
" }"
" }"
" ret {"
" key: 'm'"
" value: 'matmul:product'"
" }",
&def));
return def.SerializeAsString();
}
string AddFunction() {
tensorflow::FunctionDef def;
CHECK(tensorflow::protobuf::TextFormat::ParseFromString(
" signature {"
" name: 'AddFunction'"
" input_arg {"
" name: 'a'"
" type: DT_FLOAT"
" }"
" output_arg {"
" name: 'o'"
" type: DT_FLOAT"
" }"
" }"
" node_def {"
" name: 'output'"
" op: 'Add'"
" input: 'a'"
" input: 'a'"
" attr {"
" key: 'T'"
" value {"
" type: DT_FLOAT"
" }"
" }"
" }"
" ret {"
" key: 'o'"
" value: 'output:z'"
" }",
&def));
return def.SerializeAsString();
}
void FunctionDefAndExecute(bool async) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
string function_def = MatMulFunction();
TFE_ContextAddFunctionDef(ctx, function_def.data(), function_def.size(),
status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
for (bool clear_cache : {true, false, true}) {
if (clear_cache) {
TFE_ContextClearCaches(ctx);
}
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* retval[1] = {nullptr};
int num_retvals = 1;
TFE_Op* op = TFE_NewOp(ctx, "MatMulFunction", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(op, m, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(op, &retval[0], &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(1, num_retvals);
TFE_DeleteOp(op);
TFE_DeleteTensorHandle(m);
TF_Tensor* t = TFE_TensorHandleResolve(retval[0], status);
TFE_DeleteTensorHandle(retval[0]);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float product[4] = {0};
EXPECT_EQ(sizeof(product), TF_TensorByteSize(t));
memcpy(&product[0], TF_TensorData(t), TF_TensorByteSize(t));
TF_DeleteTensor(t);
EXPECT_EQ(7, product[0]);
EXPECT_EQ(10, product[1]);
EXPECT_EQ(15, product[2]);
EXPECT_EQ(22, product[3]);
}
TFE_ContextRemoveFunction(ctx, "MatMulFunction", status);
ASSERT_TRUE(TF_GetCode(status) == TF_OK) << TF_Message(status);
TFE_DeleteContext(ctx);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
TEST(CAPI, FunctionDefAndExecute) { FunctionDefAndExecute(false); }
TEST(CAPI, FunctionDefAndExecuteAsync) { FunctionDefAndExecute(true); }
void RunAddFunction(bool use_tfrt, bool enable_grappler) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetTfrt(opts, use_tfrt);
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
string function_def = AddFunction();
TFE_ContextAddFunctionDef(ctx, function_def.data(), function_def.size(),
status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* retval[1] = {nullptr};
int num_retvals = 1;
TFE_Op* op = TFE_NewOp(ctx, "AddFunction", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
if (enable_grappler) {
tensorflow::ConfigProto config;
config.mutable_graph_options()
->mutable_rewrite_options()
->set_min_graph_nodes(-1);
string serialized_config;
ASSERT_TRUE(config.SerializeToString(&serialized_config));
TFE_OpSetAttrString(
op, "config_proto",
reinterpret_cast<const void*>(serialized_config.c_str()),
serialized_config.length());
}
if (use_tfrt) {
TFE_OpSetAttrBool(op, "TFRT_TEST_enable_native_ops", false);
TFE_OpSetAttrBool(op, "TFRT_TEST_enable_grappler", enable_grappler);
}
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(op, m, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(op, &retval[0], &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(1, num_retvals);
TFE_DeleteOp(op);
TFE_DeleteTensorHandle(m);
TF_Tensor* t = TFE_TensorHandleResolve(retval[0], status);
TFE_DeleteTensorHandle(retval[0]);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float product[4] = {0};
EXPECT_EQ(sizeof(product), TF_TensorByteSize(t));
memcpy(&product[0], TF_TensorData(t), TF_TensorByteSize(t));
TF_DeleteTensor(t);
EXPECT_EQ(2, product[0]);
EXPECT_EQ(4, product[1]);
EXPECT_EQ(6, product[2]);
EXPECT_EQ(8, product[3]);
if (use_tfrt) {
TF_Buffer* buf = TF_NewBuffer();
TFE_GetExecutedOpNames(ctx, buf, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
#ifndef NDEBUG
if (enable_grappler)
EXPECT_NE(strstr(static_cast<const char*>(buf->data), "tf.Mul"), nullptr);
else
EXPECT_NE(strstr(static_cast<const char*>(buf->data), "tf.Add"), nullptr);
#endif
TF_DeleteBuffer(buf);
}
TFE_ContextRemoveFunction(ctx, "AddFunction", status);
ASSERT_TRUE(TF_GetCode(status) == TF_OK) << TF_Message(status);
TFE_DeleteContext(ctx);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
TEST(CAPI, RunAddFunctionWithGrappler) {
RunAddFunction(false, true);
}
void BM_ExecuteFunction(::testing::benchmark::State& state) {
const int async = state.range(0);
state.SetLabel(async ? "ExecuteFunctionAsync" : "ExecuteFunction");
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetAsync(opts, static_cast<unsigned char>(async));
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
string function_def = MatMulFunction();
TFE_ContextAddFunctionDef(ctx, function_def.data(), function_def.size(),
status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* m = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* retval[1] = {nullptr};
int num_retvals = 1;
for (auto s : state) {
TFE_Op* matmul = TFE_NewOp(ctx, "MatMulFunction", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(matmul, m, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(matmul, &retval[0], &num_retvals, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(matmul);
if (state.iterations() >= state.max_iterations && async) {
TFE_Executor* executor = TFE_ContextGetExecutorForThread(ctx);
TFE_ExecutorWaitForAllPendingNodes(executor, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteExecutor(executor);
}
}
TFE_DeleteTensorHandle(m);
TFE_DeleteTensorHandle(retval[0]);
TFE_ContextRemoveFunction(ctx, "MatMulFunction", status);
ASSERT_TRUE(TF_GetCode(status) == TF_OK) << TF_Message(status);
TFE_DeleteContext(ctx);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
BENCHMARK(BM_ExecuteFunction)->Arg(0)->Arg(1);
TEST(CAPI, Variables) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* var_handle = TestVariable(ctx, 12.0);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Op* op = TFE_NewOp(ctx, "ReadVariableOp", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(op, "dtype", TF_FLOAT);
TFE_OpAddInput(op, var_handle, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
int num_retvals = 1;
TFE_TensorHandle* value_handle = nullptr;
TFE_Execute(op, &value_handle, &num_retvals, status);
TFE_DeleteOp(op);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(1, num_retvals);
EXPECT_EQ(TF_FLOAT, TFE_TensorHandleDataType(value_handle));
EXPECT_EQ(0, TFE_TensorHandleNumDims(value_handle, status));
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float value = 0.0f;
TF_Tensor* t = TFE_TensorHandleResolve(value_handle, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(sizeof(float), TF_TensorByteSize(t));
memcpy(&value, TF_TensorData(t), sizeof(float));
TF_DeleteTensor(t);
EXPECT_EQ(12.0, value);
TFE_DeleteTensorHandle(var_handle);
TFE_DeleteTensorHandle(value_handle);
TFE_DeleteContext(ctx);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
void BM_ReadVariable(::testing::benchmark::State& state) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* var_handle = TestVariable(ctx, 5.0);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
int num_retvals = 1;
TFE_TensorHandle* h = nullptr;
for (auto s : state) {
TFE_Op* op = TFE_NewOp(ctx, "ReadVariableOp", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(op, "dtype", TF_FLOAT);
TFE_OpAddInput(op, var_handle, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(op, &h, &num_retvals, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
CHECK_EQ(1, num_retvals);
CHECK(h);
CHECK_EQ(TF_FLOAT, TFE_TensorHandleDataType(h));
CHECK_EQ(0, TFE_TensorHandleNumDims(h, status));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
h = nullptr;
TFE_DeleteOp(op);
}
TFE_DeleteTensorHandle(var_handle);
TFE_DeleteContext(ctx);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
BENCHMARK(BM_ReadVariable);
TEST(CAPI, StringAttributes) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
std::vector<int64_t> dims(4, 1);
TFE_Op* op = TFE_NewOp(ctx, "AvgPool", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_Tensor* tensor =
TF_AllocateTensor(TF_FLOAT, dims.data(), dims.size(), sizeof(float));
float tensor_data[] = {1};
memcpy(TF_TensorData(tensor), tensor_data, TF_TensorByteSize(tensor));
TFE_TensorHandle* tensor_handle = TFE_NewTensorHandle(tensor, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(op, tensor_handle, status);
TF_DeleteTensor(tensor);
TFE_DeleteTensorHandle(tensor_handle);
std::vector<int64_t> values(4, 1);
TFE_OpSetAttrIntList(op, "ksize", values.data(), values.size());
TFE_OpSetAttrIntList(op, "strides", values.data(), values.size());
const int BUFFER_SIZE = 10;
char buffer[BUFFER_SIZE];
std::strncpy(buffer, "VALID", BUFFER_SIZE);
TFE_OpSetAttrString(op, "padding", buffer, std::strlen(buffer));
std::strncpy(buffer, "NHWC", BUFFER_SIZE);
TFE_OpSetAttrString(op, "data_format", buffer, std::strlen(buffer));
TFE_OpSetAttrType(op, "T", TF_FLOAT);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* retvals[1];
int num_retvals = 1;
TFE_Execute(op, &retvals[0], &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(1, num_retvals);
tensor = TFE_TensorHandleResolve(retvals[0], status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(4, TF_TensorByteSize(tensor));
TF_DeleteTensor(tensor);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteOp(op);
TFE_DeleteContext(ctx);
TF_DeleteStatus(status);
}
TEST(CAPI, TestTFE_SetOpAttrs) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
std::vector<int64_t> dims(4, 1);
TFE_Op* op = TFE_NewOp(ctx, "AvgPool", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_Tensor* tensor =
TF_AllocateTensor(TF_FLOAT, dims.data(), dims.size(), sizeof(float));
float tensor_data[] = {1};
memcpy(TF_TensorData(tensor), tensor_data, TF_TensorByteSize(tensor));
TFE_TensorHandle* tensor_handle = TFE_NewTensorHandle(tensor, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(op, tensor_handle, status);
TF_DeleteTensor(tensor);
TFE_DeleteTensorHandle(tensor_handle);
tensorflow::AttrValue i_list_values;
for (int i = 0; i < 4; ++i) {
i_list_values.mutable_list()->add_i(1);
}
SetOpAttrValueScalar(ctx, op, i_list_values, "ksize", status);
SetOpAttrValueScalar(ctx, op, i_list_values, "strides", status);
tensorflow::AttrValue padding_value;
*padding_value.mutable_s() = "VALID";
tensorflow::SetOpAttrValueScalar(ctx, op, padding_value, "padding", status);
tensorflow::AttrValue data_format_value;
*data_format_value.mutable_s() = "NHWC";
tensorflow::SetOpAttrValueScalar(ctx, op, data_format_value, "data_format",
status);
TFE_OpSetAttrType(op, "T", TF_FLOAT);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* retvals[1];
int num_retvals = 1;
TFE_Execute(op, &retvals[0], &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(1, num_retvals);
tensor = TFE_TensorHandleResolve(retvals[0], status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(4, TF_TensorByteSize(tensor));
TF_DeleteTensor(tensor);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteOp(op);
TFE_DeleteContext(ctx);
TF_DeleteStatus(status);
}
TEST(CAPI, TestTFE_TensorHandleCopySharingUnderlyingTensorHandle) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status.get());
CHECK_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* h = TestMatrixTensorHandle(ctx);
EXPECT_EQ(TF_FLOAT, TFE_TensorHandleDataType(h));
TFE_TensorHandle* h_shares_tensor =
TFE_TensorHandleCopySharingTensor(h, status.get());
ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get());
TF_Tensor* t = TFE_TensorHandleResolve(h_shares_tensor, status.get());
ASSERT_EQ(16, TF_TensorByteSize(t));
float data[4] = {0};
memcpy(&data[0], TF_TensorData(t), TF_TensorByteSize(t));
EXPECT_EQ(1.0, data[0]);
EXPECT_EQ(2.0, data[1]);
EXPECT_EQ(3.0, data[2]);
EXPECT_EQ(4.0, data[3]);
TF_DeleteTensor(t);
TFE_DeleteTensorHandle(h);
TFE_DeleteTensorHandle(h_shares_tensor);
TFE_DeleteContext(ctx);
}
tensorflow::AttrValueMap ExtractAttrs(TFE_Op* op) {
tensorflow::AttrValueMap attr_values;
tensorflow::EagerOperation* operation =
tensorflow::OperationFromInterface(tensorflow::unwrap(op));
operation->Attrs().FillAttrValueMap(&attr_values);
return attr_values;
}
TEST(CAPI, TestTFE_OpInferSingleInputAttrs) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* input = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* axis = TestAxisTensorHandle(ctx);
TFE_Op* minOp = TFE_NewOp(ctx, "Min", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(minOp, input, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(minOp, axis, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::AttrValueMap attr_values = ExtractAttrs(minOp);
tensorflow::AttrValueMap::const_iterator attr_found = attr_values.find("T");
EXPECT_NE(attr_found, attr_values.cend());
EXPECT_EQ(attr_found->second.type(), tensorflow::DataType::DT_FLOAT);
attr_found = attr_values.find("Tidx");
EXPECT_NE(attr_found, attr_values.cend());
EXPECT_EQ(attr_found->second.type(), tensorflow::DataType::DT_INT32);
TFE_TensorHandle* retvals[1] = {nullptr};
int num_retvals = 1;
TFE_Execute(minOp, &retvals[0], &num_retvals, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
TFE_DeleteOp(minOp);
TFE_DeleteTensorHandle(input);
TFE_DeleteTensorHandle(axis);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TestTFE_OpInferSingleTypeInputListAttrs) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* input1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* input2 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* dim = TestScalarTensorHandle(ctx, 0);
TFE_Op* concatOp = TFE_NewOp(ctx, "Concat", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* inputs[] = {input1, input2};
TFE_OpAddInput(concatOp, dim, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInputList(concatOp, inputs, 2, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::AttrValueMap attr_values = ExtractAttrs(concatOp);
tensorflow::AttrValueMap::const_iterator attr_found = attr_values.find("T");
EXPECT_NE(attr_found, attr_values.cend());
EXPECT_EQ(attr_found->second.type(), tensorflow::DataType::DT_FLOAT);
attr_found = attr_values.find("N");
EXPECT_NE(attr_found, attr_values.cend());
EXPECT_EQ(attr_found->second.i(), 2);
TFE_TensorHandle* retvals[1] = {nullptr};
int num_retvals = 1;
TFE_Execute(concatOp, &retvals[0], &num_retvals, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
TFE_DeleteOp(concatOp);
TFE_DeleteTensorHandle(input1);
TFE_DeleteTensorHandle(input2);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteTensorHandle(dim);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TestTFE_OpInferMixedTypeInputListAttrs) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* condition = TestScalarTensorHandle(ctx, true);
TFE_TensorHandle* t1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* t2 = TestAxisTensorHandle(ctx);
TFE_Op* assertOp = TFE_NewOp(ctx, "Assert", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(assertOp, condition, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* data[] = {condition, t1, t2};
TFE_OpAddInputList(assertOp, data, 3, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::AttrValueMap attr_values = ExtractAttrs(assertOp);
tensorflow::AttrValueMap::const_iterator attr_found = attr_values.find("T");
EXPECT_NE(attr_found, attr_values.cend());
EXPECT_EQ(attr_found->second.list().type(0), tensorflow::DataType::DT_BOOL);
EXPECT_EQ(attr_found->second.list().type(1), tensorflow::DataType::DT_FLOAT);
EXPECT_EQ(attr_found->second.list().type(2), tensorflow::DataType::DT_INT32);
TFE_TensorHandle* retvals[1] = {nullptr};
int num_retvals = 1;
TFE_Execute(assertOp, &retvals[0], &num_retvals, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
TFE_DeleteOp(assertOp);
TFE_DeleteTensorHandle(condition);
TFE_DeleteTensorHandle(t1);
TFE_DeleteTensorHandle(t2);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TestTFE_OpAttrsInferenceDisabledWhenNotCallingOpAddInputList) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* input1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* input2 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* dim = TestScalarTensorHandle(ctx, 0);
TFE_Op* concatOp = TFE_NewOp(ctx, "Concat", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* inputs[] = {input1, input2};
TFE_OpAddInput(concatOp, dim, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
CHECK(tensorflow::unwrap(concatOp)->OpDef());
TFE_OpAddInput(concatOp, inputs[0], status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_FALSE(tensorflow::unwrap(concatOp)->OpDef())
<< "Inference context is still present";
TFE_OpAddInput(concatOp, inputs[1], status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::AttrValueMap attr_values = ExtractAttrs(concatOp);
EXPECT_EQ(attr_values.find("T"), attr_values.end());
EXPECT_EQ(attr_values.find("N"), attr_values.end());
TF_DeleteStatus(status);
TFE_DeleteOp(concatOp);
TFE_DeleteTensorHandle(input1);
TFE_DeleteTensorHandle(input2);
TFE_DeleteTensorHandle(dim);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TestTFE_OpGetInputAndOutputLengths) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* input1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* input2 = TestMatrixTensorHandle(ctx);
TFE_Op* identityOp = TFE_NewOp(ctx, "IdentityN", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(-1, TFE_OpGetInputLength(identityOp, "input", status));
CHECK_NE(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(-1, TFE_OpGetOutputLength(identityOp, "output", status));
CHECK_NE(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* inputs[] = {input1, input2};
TFE_OpAddInputList(identityOp, inputs, 2, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(2, TFE_OpGetInputLength(identityOp, "input", status));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(2, TFE_OpGetOutputLength(identityOp, "output", status));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* retvals[2] = {nullptr};
int num_retvals = 2;
TFE_Execute(identityOp, &retvals[0], &num_retvals, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(2, TFE_OpGetInputLength(identityOp, "input", status));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(2, TFE_OpGetOutputLength(identityOp, "output", status));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
TFE_DeleteOp(identityOp);
TFE_DeleteTensorHandle(input1);
TFE_DeleteTensorHandle(input2);
TFE_DeleteTensorHandle(retvals[0]);
TFE_DeleteTensorHandle(retvals[1]);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TestTFE_OpGetInputAndOutputLengthsFailForUnknownArguments) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_TensorHandle* input1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* input2 = TestMatrixTensorHandle(ctx);
TFE_Op* identityOp = TFE_NewOp(ctx, "IdentityN", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* inputs[] = {input1, input2};
TFE_OpAddInputList(identityOp, inputs, 2, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(-1, TFE_OpGetInputLength(identityOp, "cheese", status));
CHECK_EQ(TF_INVALID_ARGUMENT, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ(-1, TFE_OpGetOutputLength(identityOp, "cheese", status));
CHECK_EQ(TF_INVALID_ARGUMENT, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
TFE_DeleteOp(identityOp);
TFE_DeleteTensorHandle(input1);
TFE_DeleteTensorHandle(input2);
TFE_DeleteContext(ctx);
}
void TestOpAddAttrs(bool use_tfrt) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetTfrt(opts, use_tfrt);
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_Op* var_op = TFE_NewOp(ctx, "VarHandleOp", status);
TFE_OpSetAttrType(var_op, "dtype", TF_INT64);
TFE_OpSetAttrShape(var_op, "shape", {}, 0, status);
const TFE_OpAttrs* attributes = TFE_OpGetAttrs(var_op);
TFE_Op* copy_op = TFE_NewOp(ctx, "VarHandleOp", status);
TFE_OpSetAttrType(copy_op, "dtype", TF_FLOAT);
TFE_OpAddAttrs(copy_op, attributes);
unsigned char is_list = 0;
ASSERT_EQ(TF_ATTR_TYPE,
TFE_OpGetAttrType(copy_op, "dtype", &is_list, status));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(TF_ATTR_SHAPE,
TFE_OpGetAttrType(copy_op, "shape", &is_list, status));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::AttrValueMap attr_values;
tensorflow::EagerOperation* op =
tensorflow::OperationFromInterface(tensorflow::unwrap(copy_op));
op->Attrs().FillAttrValueMap(&attr_values);
EXPECT_EQ(tensorflow::DT_FLOAT, attr_values.find("dtype")->second.type());
TF_DeleteStatus(status);
TFE_DeleteOp(var_op);
TFE_DeleteOp(copy_op);
TFE_DeleteContext(ctx);
}
TEST(CAPI, TestTFE_OpAddAttrs) { TestOpAddAttrs(false); }
TEST(CAPI, TestTFE_OpAttrsSerialize) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_Op* var_op = TFE_NewOp(ctx, "VarHandleOp", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(var_op, "dtype", TF_INT64);
TFE_OpSetAttrShape(var_op, "shape", {}, 0, status);
const TFE_OpAttrs* attributes = TFE_OpGetAttrs(var_op);
TF_Buffer* serialized_attr_values = TF_NewBuffer();
TFE_OpAttrsSerialize(attributes, serialized_attr_values, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::NameAttrList name_and_attrs;
ASSERT_TRUE(name_and_attrs.ParseFromArray(serialized_attr_values->data,
serialized_attr_values->length));
ASSERT_EQ("VarHandleOp", name_and_attrs.name());
ASSERT_EQ(tensorflow::DT_INT64,
name_and_attrs.attr().find("dtype")->second.type());
TF_DeleteBuffer(serialized_attr_values);
TFE_Op* var_op_2 = TFE_NewOp(ctx, "VarHandleOp", status);
string serialized_dtype;
ASSERT_TRUE(name_and_attrs.attr().find("dtype")->second.SerializeToString(
&serialized_dtype));
TFE_OpSetAttrValueProto(
var_op_2, "dtype",
reinterpret_cast<const void*>(serialized_dtype.c_str()),
serialized_dtype.length(), status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
tensorflow::AttrValueMap attr_values;
tensorflow::EagerOperation* op =
tensorflow::OperationFromInterface(tensorflow::unwrap(var_op_2));
op->Attrs().FillAttrValueMap(&attr_values);
EXPECT_EQ(tensorflow::DT_INT64, attr_values.find("dtype")->second.type());
TF_DeleteStatus(status);
TFE_DeleteOp(var_op);
TFE_DeleteOp(var_op_2);
TFE_DeleteContext(ctx);
}
TFE_Op* CloneOp(const TFE_Op* other) {
TF_Status* status = TF_NewStatus();
TFE_Context* context = TFE_OpGetContext(other, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
const char* op_name = TFE_OpGetName(other, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Op* ret = TFE_NewOp(context, op_name, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
const char* device = TFE_OpGetDevice(other, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetDevice(ret, device, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddAttrs(ret, TFE_OpGetAttrs(other));
int num_inputs = TFE_OpGetFlatInputCount(other, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
for (int input_index = 0; input_index < num_inputs; ++input_index) {
TFE_TensorHandle* input = TFE_OpGetFlatInput(other, input_index, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpAddInput(ret, input, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
}
TF_DeleteStatus(status);
return ret;
}
TEST(CAPI, TestTFE_OpRecreation) {
TF_Status* status = TF_NewStatus();
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_Context* ctx = TFE_NewContext(opts, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteContextOptions(opts);
TFE_Op* original_var_op = TFE_NewOp(ctx, "VarHandleOp", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(original_var_op, "dtype", TF_INT64);
TFE_OpSetAttrShape(original_var_op, "shape", {}, 0, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ("", std::string(TFE_OpGetDevice(original_var_op, status)));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetDevice(original_var_op,
"/job:localhost/replica:0/task:0/device:CPU:0", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Op* cloned = CloneOp(original_var_op);
EXPECT_EQ("/job:localhost/replica:0/task:0/device:CPU:0",
std::string(TFE_OpGetDevice(cloned, status)));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
EXPECT_EQ("VarHandleOp", std::string(TFE_OpGetName(cloned, status)));
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
int num_retvals = 1;
TFE_TensorHandle* ret;
TFE_Execute(cloned, &ret, &num_retvals, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteTensorHandle(ret);
TFE_TensorHandle* input1 = TestMatrixTensorHandle(ctx);
TFE_TensorHandle* input2 = TestMatrixTensorHandle(ctx);
TFE_Op* original_identity = TFE_NewOp(ctx, "IdentityN", status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_TensorHandle* inputs[] = {input1, input2};
TFE_OpAddInputList(original_identity, inputs, 2, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Op* cloned_identity = CloneOp(original_identity);
EXPECT_EQ("", std::string(TFE_OpGetDevice(cloned_identity, status)));
TFE_TensorHandle* identity_ret[] = {nullptr, nullptr};
num_retvals = 2;
TFE_Execute(cloned_identity, identity_ret, &num_retvals, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteTensorHandle(input1);
TFE_DeleteTensorHandle(input2);
TFE_DeleteTensorHandle(identity_ret[0]);
TFE_DeleteTensorHandle(identity_ret[1]);
TFE_DeleteOp(cloned_identity);
TFE_DeleteOp(original_identity);
TFE_DeleteOp(original_var_op);
TFE_DeleteOp(cloned);
TF_DeleteStatus(status);
TFE_DeleteContext(ctx);
}
TEST(CAPI, ShareVariableAcrossContextsWorks) {
tensorflow::ServerDef server_def_0 = GetServerDef(3);
server_def_0.mutable_default_session_config()->set_isolate_session_state(
false);
tensorflow::ServerDef server_def_1 =
ReplaceTaskInServerDef(server_def_0, 0);
string serialized_server_def_0 = server_def_0.SerializeAsString();
string serialized_server_def_1 = server_def_1.SerializeAsString();
server_def_0.set_task_index(1);
std::unique_ptr<tensorflow::GrpcServer> worker_server1;
ASSERT_TRUE(tensorflow::GrpcServer::Create(
server_def_0, tensorflow::Env::Default(), &worker_server1)
.ok());
ASSERT_TRUE(worker_server1->Start().ok());
server_def_0.set_task_index(2);
std::unique_ptr<tensorflow::GrpcServer> worker_server2;
ASSERT_TRUE(tensorflow::GrpcServer::Create(
server_def_0, tensorflow::Env::Default(), &worker_server2)
.ok());
ASSERT_TRUE(worker_server2->Start().ok());
TFE_Context* ctx_0 = CreateContext(serialized_server_def_0,
false,
0);
TFE_Context* ctx_1 = CreateContext(serialized_server_def_1,
false,
0);
const char remote_device[] = "/job:localhost/replica:0/task:1/device:CPU:0";
{
const std::vector<std::string>& device_names = ListDeviceNames(ctx_0);
ASSERT_TRUE(std::find(device_names.begin(), device_names.end(),
remote_device) != device_names.end());
}
{
const std::vector<std::string>& device_names = ListDeviceNames(ctx_1);
ASSERT_TRUE(std::find(device_names.begin(), device_names.end(),
remote_device) != device_names.end());
}
TFE_TensorHandle* handle_0 =
CreateVariable(ctx_0, 1.2, remote_device, "var2");
TF_Status* status = TF_NewStatus();
TFE_ContextAsyncWait(ctx_0, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
{
TFE_TensorHandle* var_handle =
CreateVarHandle(ctx_1, remote_device, "var2");
TFE_TensorHandle* handle_1 = nullptr;
int num_retvals = 1;
TF_Status* status = TF_NewStatus();
TFE_Op* op = TFE_NewOp(ctx_1, "ReadVariableOp", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(op, "dtype", TF_FLOAT);
TFE_OpAddInput(op, var_handle, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(op, &handle_1, &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(op);
ASSERT_EQ(1, num_retvals);
EXPECT_EQ(TF_FLOAT, TFE_TensorHandleDataType(handle_1));
EXPECT_EQ(0, TFE_TensorHandleNumDims(handle_1, status));
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float value = 0.0f;
TF_Tensor* t = TFE_TensorHandleResolve(handle_1, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(sizeof(float), TF_TensorByteSize(t));
memcpy(&value, TF_TensorData(t), sizeof(float));
TF_DeleteTensor(t);
EXPECT_EQ(1.2f, value);
TFE_DeleteTensorHandle(handle_1);
TF_DeleteStatus(status);
TFE_DeleteTensorHandle(var_handle);
}
TFE_DeleteTensorHandle(handle_0);
TFE_DeleteContext(ctx_0);
TFE_DeleteContext(ctx_1);
worker_server1.release();
worker_server2.release();
}
TEST(CAPI, ShareVariableAcrossContextsAfterUpdateContextWorks) {
tensorflow::ServerDef server_def_0 = GetServerDef(3);
server_def_0.mutable_default_session_config()->set_isolate_session_state(
false);
tensorflow::ServerDef server_def_1 =
ReplaceTaskInServerDef(server_def_0, 0);
string serialized_server_def_0 = server_def_0.SerializeAsString();
string serialized_server_def_1 = server_def_1.SerializeAsString();
server_def_0.set_task_index(1);
std::unique_ptr<tensorflow::GrpcServer> worker_server1;
ASSERT_TRUE(tensorflow::GrpcServer::Create(
server_def_0, tensorflow::Env::Default(), &worker_server1)
.ok());
ASSERT_TRUE(worker_server1->Start().ok());
server_def_0.set_task_index(2);
std::unique_ptr<tensorflow::GrpcServer> worker_server2;
ASSERT_TRUE(tensorflow::GrpcServer::Create(
server_def_0, tensorflow::Env::Default(), &worker_server2)
.ok());
ASSERT_TRUE(worker_server2->Start().ok());
TFE_Context* ctx_0 = CreateContext(serialized_server_def_0,
false,
0);
TFE_Context* ctx_1 = CreateContext(serialized_server_def_1,
false,
0);
const char remote_device[] = "/job:localhost/replica:0/task:2/device:CPU:0";
{
const std::vector<std::string>& device_names = ListDeviceNames(ctx_0);
ASSERT_TRUE(std::find(device_names.begin(), device_names.end(),
remote_device) != device_names.end());
}
{
const std::vector<std::string>& device_names = ListDeviceNames(ctx_1);
ASSERT_TRUE(std::find(device_names.begin(), device_names.end(),
remote_device) != device_names.end());
}
TFE_TensorHandle* handle_0 =
CreateVariable(ctx_0, 1.2, remote_device, "var");
TF_Status* status = TF_NewStatus();
TFE_ContextAsyncWait(ctx_0, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
int port = tensorflow::testing::PickUnusedPortOrDie();
ReplaceTaskInServerDef(&server_def_0, 1, "localhost", port);
ReplaceTaskInServerDef(&server_def_1, 1, "localhost", port);
server_def_0.set_task_index(1);
worker_server1.release();
ASSERT_TRUE(tensorflow::GrpcServer::Create(
server_def_0, tensorflow::Env::Default(), &worker_server1)
.ok());
ASSERT_TRUE(worker_server1->Start().ok());
{
server_def_0.set_task_index(0);
string serialized_update = server_def_0.SerializeAsString();
TF_Status* status = TF_NewStatus();
TFE_ContextUpdateServerDef(ctx_0, 0, serialized_update.data(),
serialized_update.size(), status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
{
server_def_1.set_task_index(0);
string serialized_update = server_def_1.SerializeAsString();
TF_Status* status = TF_NewStatus();
TFE_ContextUpdateServerDef(ctx_1, 0, serialized_update.data(),
serialized_update.size(), status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
}
{
TFE_TensorHandle* var_handle =
CreateVarHandle(ctx_1, remote_device, "var");
TFE_TensorHandle* handle_1 = nullptr;
int num_retvals = 1;
TF_Status* status = TF_NewStatus();
TFE_Op* op = TFE_NewOp(ctx_1, "ReadVariableOp", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(op, "dtype", TF_FLOAT);
TFE_OpAddInput(op, var_handle, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(op, &handle_1, &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(op);
ASSERT_EQ(1, num_retvals);
EXPECT_EQ(TF_FLOAT, TFE_TensorHandleDataType(handle_1));
EXPECT_EQ(0, TFE_TensorHandleNumDims(handle_1, status));
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float value = 0.0f;
TF_Tensor* t = TFE_TensorHandleResolve(handle_1, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(sizeof(float), TF_TensorByteSize(t));
memcpy(&value, TF_TensorData(t), sizeof(float));
TF_DeleteTensor(t);
EXPECT_EQ(1.2f, value);
TFE_DeleteTensorHandle(handle_1);
TF_DeleteStatus(status);
TFE_DeleteTensorHandle(var_handle);
}
TFE_DeleteTensorHandle(handle_0);
TFE_DeleteContext(ctx_0);
TFE_DeleteContext(ctx_1);
worker_server1.release();
worker_server2.release();
}
tensorflow::ServerDef CreateSingleHostServerDef(
const tensorflow::ServerDef& cluster_server_def, int task_index) {
tensorflow::ServerDef single_host_server_def;
single_host_server_def.set_job_name("worker");
single_host_server_def.set_protocol(cluster_server_def.protocol());
single_host_server_def.set_task_index(0);
tensorflow::ClusterDef* cluster_def =
single_host_server_def.mutable_cluster();
tensorflow::JobDef* job_def = cluster_def->add_job();
job_def->set_name("client");
job_def->mutable_tasks()->insert(
{0, tensorflow::strings::StrCat(
"localhost:", tensorflow::testing::PickUnusedPortOrDie())});
tensorflow::JobDef* job_def2 = cluster_def->add_job();
job_def2->set_name("worker");
for (auto task : cluster_server_def.cluster().job(0).tasks()) {
if (task.first == task_index) {
job_def2->mutable_tasks()->insert({task.first, task.second});
}
}
return single_host_server_def;
}
tensorflow::ServerDef GetClusterServerDef(const string& worker_job_name,
int num_workers) {
tensorflow::ServerDef server_def = GetServerDef(worker_job_name, num_workers);
tensorflow::ClusterDef* cluster_def = server_def.mutable_cluster();
tensorflow::JobDef* job_def2 = cluster_def->add_job();
job_def2->set_name("client");
job_def2->mutable_tasks()->insert(
{0, tensorflow::strings::StrCat(
"localhost:", tensorflow::testing::PickUnusedPortOrDie())});
return server_def;
}
TEST(CAPI, SingleHostServerDefV1Works) {
tensorflow::ServerDef cluster_server_def = GetClusterServerDef("worker", 2);
tensorflow::ServerDef worker_1_server_def =
CreateSingleHostServerDef(cluster_server_def, 1);
worker_1_server_def.set_task_index(1);
worker_1_server_def.set_job_name("worker");
std::unique_ptr<tensorflow::GrpcServer> worker_server1;
ASSERT_TRUE(tensorflow::GrpcServer::Create(worker_1_server_def,
tensorflow::Env::Default(),
&worker_server1)
.ok());
ASSERT_TRUE(worker_server1->Start().ok());
worker_1_server_def.set_task_index(0);
worker_1_server_def.set_job_name("client");
TFE_Context* local_ctx =
CreateContext(worker_1_server_def.SerializeAsString(),
false,
0);
const char remote_device[] = "/job:worker/replica:0/task:1/device:CPU:0";
TFE_TensorHandle* handle_0 =
CreateVariable(local_ctx, 1.2, remote_device, "var");
TF_Status* status = TF_NewStatus();
TFE_ContextAsyncWait(local_ctx, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
TFE_DeleteTensorHandle(handle_0);
tensorflow::ServerDef worker_0_server_def =
CreateSingleHostServerDef(cluster_server_def, 0);
worker_0_server_def.set_task_index(0);
std::unique_ptr<tensorflow::GrpcServer> worker_server0;
ASSERT_TRUE(tensorflow::GrpcServer::Create(worker_0_server_def,
tensorflow::Env::Default(),
&worker_server0)
.ok());
ASSERT_TRUE(worker_server0->Start().ok());
cluster_server_def.set_task_index(0);
cluster_server_def.set_job_name("client");
TFE_Context* remote_ctx =
CreateContext(cluster_server_def.SerializeAsString(),
false,
0);
{
TFE_TensorHandle* var_handle =
CreateVarHandle(remote_ctx, remote_device, "var");
TFE_TensorHandle* handle_1 = nullptr;
int num_retvals = 1;
TF_Status* status = TF_NewStatus();
TFE_Op* op = TFE_NewOp(remote_ctx, "ReadVariableOp", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(op, "dtype", TF_FLOAT);
TFE_OpAddInput(op, var_handle, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(op, &handle_1, &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(op);
ASSERT_EQ(1, num_retvals);
EXPECT_EQ(TF_FLOAT, TFE_TensorHandleDataType(handle_1));
EXPECT_EQ(0, TFE_TensorHandleNumDims(handle_1, status));
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float value = 0.0f;
TF_Tensor* t = TFE_TensorHandleResolve(handle_1, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(sizeof(float), TF_TensorByteSize(t));
memcpy(&value, TF_TensorData(t), sizeof(float));
TF_DeleteTensor(t);
EXPECT_EQ(1.2f, value);
TFE_DeleteTensorHandle(handle_1);
TF_DeleteStatus(status);
TFE_DeleteTensorHandle(var_handle);
}
TFE_DeleteContext(local_ctx);
TFE_DeleteContext(remote_ctx);
worker_server1.release();
worker_server0.release();
}
TEST(CAPI, SingleHostServerDefV2Works) {
tensorflow::ServerDef cluster_server_def = GetClusterServerDef("worker", 2);
cluster_server_def.set_task_index(0);
cluster_server_def.set_job_name("worker");
std::unique_ptr<tensorflow::GrpcServer> worker_server0;
ASSERT_TRUE(tensorflow::GrpcServer::Create(cluster_server_def,
tensorflow::Env::Default(),
&worker_server0)
.ok());
ASSERT_TRUE(worker_server0->Start().ok());
cluster_server_def.set_task_index(1);
cluster_server_def.set_job_name("worker");
std::unique_ptr<tensorflow::GrpcServer> worker_server1;
ASSERT_TRUE(tensorflow::GrpcServer::Create(cluster_server_def,
tensorflow::Env::Default(),
&worker_server1)
.ok());
ASSERT_TRUE(worker_server1->Start().ok());
cluster_server_def.set_task_index(0);
cluster_server_def.set_job_name("client");
TFE_Context* ctx_with_cluster_server_def =
CreateContext(cluster_server_def.SerializeAsString(),
false,
0);
const char worker_1_device[] = "/job:worker/replica:0/task:1/device:CPU:0";
TFE_TensorHandle* handle_0 =
CreateVariable(ctx_with_cluster_server_def, 1.2, worker_1_device,
"var");
TF_Status* status = TF_NewStatus();
TFE_ContextAsyncWait(ctx_with_cluster_server_def, status);
EXPECT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteStatus(status);
TFE_DeleteTensorHandle(handle_0);
tensorflow::ServerDef worker_1_server_def =
CreateSingleHostServerDef(cluster_server_def, 1);
worker_1_server_def.set_task_index(0);
worker_1_server_def.set_job_name("client");
TFE_Context* ctx_with_worker_1_server_def =
CreateContext(worker_1_server_def.SerializeAsString(),
false,
0);
{
TFE_TensorHandle* var_handle = CreateVarHandle(
ctx_with_worker_1_server_def, worker_1_device, "var");
TFE_TensorHandle* handle_1 = nullptr;
int num_retvals = 1;
TF_Status* status = TF_NewStatus();
TFE_Op* op =
TFE_NewOp(ctx_with_worker_1_server_def, "ReadVariableOp", status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_OpSetAttrType(op, "dtype", TF_FLOAT);
TFE_OpAddInput(op, var_handle, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_Execute(op, &handle_1, &num_retvals, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TFE_DeleteOp(op);
ASSERT_EQ(1, num_retvals);
EXPECT_EQ(TF_FLOAT, TFE_TensorHandleDataType(handle_1));
EXPECT_EQ(0, TFE_TensorHandleNumDims(handle_1, status));
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
float value = 0.0f;
TF_Tensor* t = TFE_TensorHandleResolve(handle_1, status);
ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
ASSERT_EQ(sizeof(float), TF_TensorByteSize(t));
memcpy(&value, TF_TensorData(t), sizeof(float));
TF_DeleteTensor(t);
EXPECT_EQ(1.2f, value);
TFE_DeleteTensorHandle(handle_1);
TF_DeleteStatus(status);
TFE_DeleteTensorHandle(var_handle);
}
TFE_DeleteContext(ctx_with_worker_1_server_def);
TFE_DeleteContext(ctx_with_cluster_server_def);
worker_server1.release();
worker_server0.release();
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/c/eager/c_api.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/c/eager/c_api_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
f04a7bc0-66d1-4061-a1dd-c9111cff0a3a | cpp | tensorflow/tensorflow | tfprof_tensor | tensorflow/core/profiler/internal/tfprof_tensor.cc | tensorflow/core/profiler/internal/tfprof_tensor_test.cc | #include "tensorflow/core/profiler/internal/tfprof_tensor.h"
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
namespace tensorflow {
namespace tfprof {
void TFProfTensor::Display(string* formatted_str,
TFProfTensorProto* tfprof_tensor_pb) {
if (formatted_str) {
if (formatted_str_.length() >= kTFProfTenosrMaxDisplayLen) {
*formatted_str =
absl::StrCat(formatted_str_, "...omitted from display\n\n");
} else {
*formatted_str = formatted_str_;
}
}
if (tfprof_tensor_pb) {
tfprof_tensor_pb->MergeFrom(tfprof_tensor_pb_);
}
}
void TFProfTensor::Build() {
tfprof_tensor_pb_.set_dtype(tensor_->dtype());
switch (tensor_->dtype()) {
case DataType::DT_FLOAT:
case DataType::DT_DOUBLE: {
std::vector<double> values_vec;
if (tensor_->dtype() == DataType::DT_FLOAT) {
GetValueVec<float, double>(&values_vec);
} else if (tensor_->dtype() == DataType::DT_DOUBLE) {
GetValueVec<double, double>(&values_vec);
}
BuildOutput<double>(0, 0, values_vec, &tfprof_tensor_pb_);
break;
}
case DataType::DT_INT32:
case DataType::DT_INT64: {
std::vector<int64_t> values_vec;
if (tensor_->dtype() == DataType::DT_INT32) {
GetValueVec<int32, int64_t>(&values_vec);
} else if (tensor_->dtype() == DataType::DT_INT64) {
GetValueVec<int64_t, int64_t>(&values_vec);
}
BuildOutput<int64_t>(0, 0, values_vec, &tfprof_tensor_pb_);
break;
}
case DataType::DT_STRING: {
std::vector<tstring> values_vec;
GetValueVec<tstring, tstring>(&values_vec);
BuildOutput<tstring>(0, 0, values_vec, &tfprof_tensor_pb_);
break;
}
default: {
absl::FPrintF(stderr, "Not Supported type %d\n", tensor_->dtype());
break;
}
}
}
}
} | #include <memory>
#include <utility>
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/profiler/internal/tfprof_stats.h"
#include "tensorflow/core/profiler/internal/tfprof_utils.h"
#include "tensorflow/core/profiler/tfprof_log.pb.h"
#include "tensorflow/core/profiler/tfprof_options.h"
#include "tensorflow/core/profiler/tfprof_output.pb.h"
namespace tensorflow {
namespace tfprof {
class TFProfTensorTest : public ::testing::Test {
protected:
TFProfTensorTest() {
string graph_path =
io::JoinPath(testing::TensorFlowSrcRoot(),
"core/profiler/internal/testdata/graph.pbtxt");
std::unique_ptr<tensorflow::GraphDef> graph_pb(new tensorflow::GraphDef());
TF_CHECK_OK(
ReadProtoFile(Env::Default(), graph_path, graph_pb.get(), false));
std::unique_ptr<tensorflow::RunMetadata> run_meta_pb;
std::unique_ptr<OpLogProto> op_log_pb;
string ckpt_path = io::JoinPath(testing::TensorFlowSrcRoot(),
"core/profiler/internal/testdata/ckpt");
TF_Status* status = TF_NewStatus();
std::unique_ptr<checkpoint::CheckpointReader> ckpt_reader(
new checkpoint::CheckpointReader(ckpt_path, status));
CHECK(TF_GetCode(status) == TF_OK);
TF_DeleteStatus(status);
tf_stats_ =
std::make_unique<TFStats>(std::move(graph_pb), std::move(run_meta_pb),
std::move(op_log_pb), std::move(ckpt_reader));
tf_stats_->BuildAllViews();
}
std::unique_ptr<TFStats> tf_stats_;
};
TEST_F(TFProfTensorTest, Basics) {
Options opts(3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, "name", {"VariableV2"},
{".*"}, {""}, {".*"}, {""}, false,
{"tensor_value"},
"", {});
const GraphNodeProto& root = tf_stats_->ShowGraphNode("scope", opts);
EXPECT_EQ(root.children(0).name(), "DW");
EXPECT_GT(root.children(0).tensor_value().value_double_size(), 10);
EXPECT_EQ(root.children(1).name(), "DW2");
EXPECT_GT(root.children(1).tensor_value().value_double_size(), 10);
EXPECT_EQ(root.children(2).name(), "ScalarW");
EXPECT_EQ(root.children(2).tensor_value().value_double_size(), 1);
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/profiler/internal/tfprof_tensor.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/profiler/internal/tfprof_tensor_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
b237aaf1-e2e0-46bd-9a9f-7c64978e4db3 | cpp | tensorflow/tensorflow | window_dataset_op | tensorflow/core/kernels/data/window_dataset_op.cc | tensorflow/core/kernels/data/window_dataset_op_test.cc | #include "tensorflow/core/kernels/data/window_dataset_op.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/dataset_options.pb.h"
#include "tensorflow/core/framework/model.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/op_requires.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/kernels/data/window_dataset.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/platform/stringprintf.h"
#include "tensorflow/core/platform/tstring.h"
#include "tensorflow/core/platform/types.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/thread_annotations.h"
namespace tensorflow {
namespace data {
constexpr const char* const WindowDatasetOp::kDatasetType;
constexpr const char* const WindowDatasetOp::kInputDataset;
constexpr const char* const WindowDatasetOp::kSize;
constexpr const char* const WindowDatasetOp::kShift;
constexpr const char* const WindowDatasetOp::kStride;
constexpr const char* const WindowDatasetOp::kDropRemainder;
constexpr const char* const WindowDatasetOp::kOutputTypes;
constexpr const char* const WindowDatasetOp::kOutputShapes;
constexpr char kInputImplEmpty[] = "input_impl_empty";
constexpr char kBufferSize[] = "buffer_size";
constexpr char kBuffer[] = "buffer";
constexpr char kSizeSuffix[] = ".size";
constexpr char kCodeSuffix[] = ".code";
constexpr char kErrorMessage[] = ".error_message";
class WindowDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input, int64_t window_size,
int64_t window_shift, int64_t window_stride, bool drop_remainder)
: DatasetBase(DatasetContext(ctx)),
input_(input),
window_size_(window_size),
window_shift_(window_shift),
window_stride_(window_stride),
drop_remainder_(drop_remainder),
output_dtypes_(input_->output_dtypes().size(), {DT_VARIANT}),
output_shapes_(input_->output_shapes().size(), TensorShape({})),
traceme_metadata_(
{{"window_size",
strings::Printf("%lld", static_cast<long long>(window_size))},
{"window_shift",
strings::Printf("%lld", static_cast<long long>(window_shift))},
{"window_stride", strings::Printf("%lld", static_cast<long long>(
window_stride))}}) {
input_->Ref();
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix)});
}
const DataTypeVector& output_dtypes() const override {
return output_dtypes_;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return output_shapes_;
}
string DebugString() const override {
name_utils::DatasetDebugStringParams params;
params.set_args(window_size_, window_shift_, window_stride_,
drop_remainder_);
return name_utils::DatasetDebugString(kDatasetType, params);
}
int64_t CardinalityInternal(CardinalityOptions options) const override {
int64_t n = input_->Cardinality(options);
if (n == kInfiniteCardinality || n == kUnknownCardinality) {
return n;
}
int64_t cardinality = 0;
if (drop_remainder_) {
int64_t rest_elements = n - ((window_size_ - 1) * window_stride_ + 1);
cardinality = rest_elements < 0 ? 0 : rest_elements / window_shift_ + 1;
} else {
cardinality = n / window_shift_ + (n % window_shift_ == 0 ? 0 : 1);
}
return cardinality;
}
Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(input_);
return absl::OkStatus();
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* window_size_node = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(window_size_, &window_size_node));
Node* window_shift_node = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(window_shift_, &window_shift_node));
Node* window_stride_node = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(window_stride_, &window_stride_node));
Node* drop_remainder_node = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(drop_remainder_, &drop_remainder_node));
TF_RETURN_IF_ERROR(
b->AddDataset(this,
{input_graph_node, window_size_node, window_shift_node,
window_stride_node, drop_remainder_node},
output));
return absl::OkStatus();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
Status Initialize(IteratorContext* ctx) override {
return dataset()->input_->MakeIterator(ctx, this, prefix(), &input_impl_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
const int64_t window_size = dataset()->window_size_;
const int64_t window_shift = dataset()->window_shift_;
const int64_t window_stride = dataset()->window_stride_;
std::vector<std::vector<Tensor>> window_elements;
Status status = absl::OkStatus();
{
const size_t target_size = TargetBufferSize(window_size, window_stride);
mutex_lock l(mu_);
if (!input_impl_ &&
(buffer_.empty() ||
(dataset()->drop_remainder_ && buffer_.size() < target_size))) {
*end_of_sequence = true;
return absl::OkStatus();
}
if (input_impl_) {
*end_of_sequence = false;
for (size_t i = buffer_.size(); i < target_size && !*end_of_sequence;
++i) {
std::vector<Tensor> element;
Status status =
input_impl_->GetNext(ctx, &element, end_of_sequence);
if (!*end_of_sequence) {
RecordBufferEnqueue(ctx, element);
buffer_.emplace_back(std::move(element), status);
} else {
input_impl_.reset();
}
}
}
if (buffer_.empty() ||
(dataset()->drop_remainder_ && buffer_.size() < target_size)) {
DCHECK(*end_of_sequence);
return absl::OkStatus();
}
int num_elements = 1 + (buffer_.size() - 1) / window_stride;
window_elements.reserve(num_elements);
for (size_t i = 0; i < num_elements; ++i) {
status.Update(buffer_[window_stride * i].status);
if (!status.ok()) {
break;
}
window_elements.emplace_back(buffer_[window_stride * i].result);
}
int buffer_size = buffer_.size();
if (window_shift >= buffer_size) {
for (size_t i = buffer_size; input_impl_ && i < window_shift; ++i) {
bool end_of_input;
std::vector<Tensor> element;
input_impl_->GetNext(ctx, &element, &end_of_input).IgnoreError();
if (end_of_input) {
input_impl_.reset();
}
}
for (size_t i = 0; i < buffer_.size(); ++i) {
RecordBufferDequeue(ctx, buffer_.at(i).result);
}
buffer_.clear();
} else {
for (size_t i = 0; i < window_shift; ++i) {
RecordBufferDequeue(ctx, buffer_.at(i).result);
}
buffer_.erase(buffer_.begin(), buffer_.begin() + window_shift);
}
}
if (!status.ok()) {
return status;
}
const size_t num_tuple_components = window_elements[0].size();
const int64_t num_window_elements = window_elements.size();
*end_of_sequence = false;
for (size_t idx = 0; idx < num_tuple_components; ++idx) {
DatasetBase* window_dataset;
std::vector<std::vector<Tensor>> window_component_elements;
window_component_elements.reserve(num_window_elements);
for (size_t i = 0; i < num_window_elements; ++i) {
std::vector<Tensor> component_element;
component_element.push_back(std::move(window_elements[i][idx]));
window_component_elements.push_back(component_element);
}
DataTypeVector output_types({dataset()->input_->output_dtypes()[idx]});
std::vector<PartialTensorShape> output_shapes(
{dataset()->input_->output_shapes()[idx]});
TF_RETURN_IF_ERROR(NewWindow(window_component_elements, output_types,
output_shapes, &window_dataset));
out_tensors->emplace_back(DT_VARIANT, TensorShape({}));
TF_RETURN_IF_ERROR(
StoreDatasetInVariantTensor(window_dataset, &out_tensors->back()));
}
return absl::OkStatus();
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeKnownRatioNode(std::move(args),
dataset()->window_shift_);
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (!input_impl_) {
TF_RETURN_IF_ERROR(writer->WriteScalar(prefix(), kInputImplEmpty, ""));
} else {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));
}
TF_RETURN_IF_ERROR(
writer->WriteScalar(prefix(), kBufferSize, buffer_.size()));
for (int64_t i = 0; i < buffer_.size(); i++) {
TF_RETURN_IF_ERROR(WriteStatusLocked(writer, i, buffer_[i].status));
TF_RETURN_IF_ERROR(writer->WriteScalar(
prefix(), strings::StrCat(kBuffer, "[", i, "]", kSizeSuffix),
buffer_[i].result.size()));
for (int64_t j = 0; j < buffer_[i].result.size(); j++) {
TF_RETURN_IF_ERROR(writer->WriteTensor(
prefix(), strings::StrCat(kBuffer, "[", i, "][", j, "]"),
buffer_[i].result[j]));
}
}
return absl::OkStatus();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(prefix(), kInputImplEmpty)) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
int64_t buffer_size = 0;
TF_RETURN_IF_ERROR(
reader->ReadScalar(prefix(), kBufferSize, &buffer_size));
buffer_.resize(buffer_size);
for (int64_t i = 0; i < buffer_size; i++) {
int64_t vector_size;
TF_RETURN_IF_ERROR(ReadStatusLocked(reader, i, &buffer_[i].status));
TF_RETURN_IF_ERROR(reader->ReadScalar(
prefix(), strings::StrCat(kBuffer, "[", i, "]", kSizeSuffix),
&vector_size));
buffer_[i].result.resize(vector_size);
for (int64_t j = 0; j < vector_size; j++) {
TF_RETURN_IF_ERROR(
reader->ReadTensor(ctx->flr(), prefix(),
strings::StrCat(kBuffer, "[", i, "][", j, "]"),
&buffer_[i].result[j]));
}
}
return absl::OkStatus();
}
TraceMeMetadata GetTraceMeMetadata() const override {
return dataset()->traceme_metadata_;
}
private:
struct InvocationResult {
InvocationResult() = default;
InvocationResult(std::vector<Tensor>&& result, const Status& status)
: result(result), status(status) {}
std::vector<Tensor> result;
Status status;
};
Status WriteStatusLocked(IteratorStateWriter* writer, size_t index,
const Status& status)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
TF_RETURN_IF_ERROR(writer->WriteScalar(
prefix(), CodeKey(index), static_cast<int64_t>(status.code())));
if (!status.ok()) {
TF_RETURN_IF_ERROR(writer->WriteScalar(prefix(), ErrorMessageKey(index),
std::string(status.message())));
}
return absl::OkStatus();
}
Status ReadStatusLocked(IteratorStateReader* reader, size_t index,
Status* status) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
int64_t code_int;
TF_RETURN_IF_ERROR(
reader->ReadScalar(prefix(), CodeKey(index), &code_int));
absl::StatusCode code = static_cast<absl::StatusCode>(code_int);
if (code != absl::StatusCode::kOk) {
tstring error_message;
TF_RETURN_IF_ERROR(reader->ReadScalar(prefix(), ErrorMessageKey(index),
&error_message));
*status = Status(code, error_message);
} else {
*status = absl::OkStatus();
}
return absl::OkStatus();
}
string CodeKey(size_t index) {
return strings::StrCat(kBuffer, "[", index, "]", kCodeSuffix);
}
string ErrorMessageKey(size_t index) {
return strings::StrCat(kBuffer, "[", index, "]", kErrorMessage);
}
size_t TargetBufferSize(int64_t window_size, int64_t window_stride) {
return (window_size - 1) * window_stride + 1;
}
mutex mu_;
std::deque<InvocationResult> buffer_ TF_GUARDED_BY(mu_);
std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_);
};
const DatasetBase* const input_;
const int64_t window_size_;
const int64_t window_shift_;
const int64_t window_stride_;
const bool drop_remainder_;
const DataTypeVector output_dtypes_;
const std::vector<PartialTensorShape> output_shapes_;
const TraceMeMetadata traceme_metadata_;
};
WindowDatasetOp::WindowDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void WindowDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
int64_t window_size = 0;
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64_t>(ctx, kSize, &window_size));
OP_REQUIRES(
ctx, window_size > 0,
errors::InvalidArgument("Window size must be greater than zero."));
int64_t window_shift = 0;
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64_t>(ctx, kShift, &window_shift));
OP_REQUIRES(
ctx, window_shift > 0,
errors::InvalidArgument("Window shift must be greater than zero."));
int64_t window_stride = 0;
OP_REQUIRES_OK(ctx,
ParseScalarArgument<int64_t>(ctx, kStride, &window_stride));
OP_REQUIRES(
ctx, window_stride > 0,
errors::InvalidArgument("Window stride must be greater than zero."));
bool drop_remainder;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<bool>(ctx, kDropRemainder, &drop_remainder));
*output = new Dataset(ctx, input, window_size, window_shift, window_stride,
drop_remainder);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("WindowDataset").Device(DEVICE_CPU),
WindowDatasetOp);
}
}
} | #include "tensorflow/core/kernels/data/window_dataset_op.h"
#include <string>
#include <utility>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "xla/tsl/lib/core/status_test_util.h"
#include "tensorflow/core/data/dataset_test_base.h"
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/data/serialization_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/framework/variant_tensor_data.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace data {
namespace {
constexpr char kNodeName[] = "window_dataset";
class WindowDatasetParams : public DatasetParams {
public:
template <typename T>
WindowDatasetParams(T input_dataset_params, int64_t size, int64_t shift,
int64_t stride, bool drop_remainder,
DataTypeVector output_dtypes,
std::vector<PartialTensorShape> output_shapes,
string node_name)
: DatasetParams(std::move(output_dtypes), std::move(output_shapes),
std::move(node_name)),
size_(size),
shift_(shift),
stride_(stride),
drop_remainder_(drop_remainder) {
input_dataset_params_.push_back(std::make_unique<T>(input_dataset_params));
iterator_prefix_ =
name_utils::IteratorPrefix(input_dataset_params.dataset_type(),
input_dataset_params.iterator_prefix());
}
std::vector<Tensor> GetInputTensors() const override {
return {CreateTensor<int64_t>(TensorShape({}), {size_}),
CreateTensor<int64_t>(TensorShape({}), {shift_}),
CreateTensor<int64_t>(TensorShape({}), {stride_}),
CreateTensor<bool>(TensorShape({}), {drop_remainder_})};
}
Status GetInputNames(std::vector<string>* input_names) const override {
input_names->clear();
input_names->emplace_back(WindowDatasetOp::kInputDataset);
input_names->emplace_back(WindowDatasetOp::kSize);
input_names->emplace_back(WindowDatasetOp::kShift);
input_names->emplace_back(WindowDatasetOp::kStride);
input_names->emplace_back(WindowDatasetOp::kDropRemainder);
return absl::OkStatus();
}
Status GetAttributes(AttributeVector* attr_vector) const override {
attr_vector->clear();
attr_vector->emplace_back("output_types", output_dtypes_);
attr_vector->emplace_back("output_shapes", output_shapes_);
attr_vector->emplace_back("metadata", "");
return absl::OkStatus();
}
string dataset_type() const override { return WindowDatasetOp::kDatasetType; }
private:
int64_t size_;
int64_t shift_;
int64_t stride_;
bool drop_remainder_;
};
class WindowDatasetOpTest : public DatasetOpsTestBase {};
WindowDatasetParams WindowDatasetParams1() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
2,
1,
false,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams2() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
2,
2,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams3() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
8,
3,
1,
false,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams4() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
8,
3,
1,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams5() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
8,
1,
false,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams6() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
8,
1,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams7() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
2,
8,
false,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams8() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
2,
8,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams9() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
4,
2,
2,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParams10() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
5,
2,
2,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParamsWithInvalidWindowSize() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
0,
2,
2,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParamswithInvalidWindowShift() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
0,
2,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
WindowDatasetParams WindowDatasetParamsWithInvalidWindowStride() {
return WindowDatasetParams(RangeDatasetParams(0, 7, 1),
2,
2,
0,
true,
{DT_VARIANT},
{PartialTensorShape({})},
kNodeName);
}
template <typename T>
struct GetNextTestCase {
T dataset_params;
std::vector<std::vector<Tensor>> expected_outputs;
};
std::vector<GetNextTestCase<WindowDatasetParams>> GetNextTestCases() {
return {{WindowDatasetParams1(),
{CreateTensors<int64_t>(TensorShape{}, {{0}, {1}}),
CreateTensors<int64_t>(TensorShape{}, {{2}, {3}}),
CreateTensors<int64_t>(TensorShape{}, {{4}, {5}}),
CreateTensors<int64_t>(TensorShape{}, {{6}})}},
{WindowDatasetParams2(),
{CreateTensors<int64_t>(TensorShape{}, {{0}, {2}}),
CreateTensors<int64_t>(TensorShape{}, {{2}, {4}}),
CreateTensors<int64_t>(TensorShape{}, {{4}, {6}})}},
{WindowDatasetParams3(),
{CreateTensors<int64_t>(TensorShape({}),
{{0}, {1}, {2}, {3}, {4}, {5}, {6}}),
CreateTensors<int64_t>(TensorShape({}), {{3}, {4}, {5}, {6}}),
CreateTensors<int64_t>(TensorShape({}), {{6}})}},
{WindowDatasetParams4(),
{}},
{WindowDatasetParams5(),
{CreateTensors<int64_t>(TensorShape({}), {{0}, {1}})}},
{WindowDatasetParams6(),
{CreateTensors<int64_t>(TensorShape({}), {{0}, {1}})}},
{WindowDatasetParams7(),
{CreateTensors<int64_t>(TensorShape({}), {{0}}),
CreateTensors<int64_t>(TensorShape({}), {{2}}),
CreateTensors<int64_t>(TensorShape({}), {{4}}),
CreateTensors<int64_t>(TensorShape({}), {{6}})}},
{WindowDatasetParams8(),
{}},
{WindowDatasetParams9(),
{CreateTensors<int64_t>(TensorShape({}), {{0}, {2}, {4}, {6}})}},
{WindowDatasetParams10(),
{}}};
}
class ParameterizedGetNextTest : public WindowDatasetOpTest,
public ::testing::WithParamInterface<
GetNextTestCase<WindowDatasetParams>> {};
TEST_P(ParameterizedGetNextTest, GetNext) {
auto test_case = GetParam();
TF_ASSERT_OK(Initialize(test_case.dataset_params));
bool end_of_sequence = false;
auto expected_outputs_it = test_case.expected_outputs.begin();
while (!end_of_sequence) {
std::vector<Tensor> out_tensors;
TF_EXPECT_OK(iterator_->GetNext(iterator_ctx_.get(), &out_tensors,
&end_of_sequence));
if (!end_of_sequence) {
for (const auto& window_dataset_tensor : out_tensors) {
DatasetBase* window_dataset;
TF_ASSERT_OK(GetDatasetFromVariantTensor(window_dataset_tensor,
&window_dataset));
std::unique_ptr<IteratorBase> window_dataset_iterator;
TF_ASSERT_OK(window_dataset->MakeIterator(
iterator_ctx_.get(), nullptr,
test_case.dataset_params.iterator_prefix(),
&window_dataset_iterator));
bool end_of_window_dataset = false;
std::vector<Tensor> window_elements;
while (!end_of_window_dataset) {
std::vector<Tensor> next_element;
TF_EXPECT_OK(window_dataset_iterator->GetNext(
iterator_ctx_.get(), &next_element, &end_of_window_dataset));
window_elements.insert(window_elements.end(), next_element.begin(),
next_element.end());
}
EXPECT_LT(expected_outputs_it, test_case.expected_outputs.end());
TF_EXPECT_OK(ExpectEqual(window_elements, *expected_outputs_it, false));
expected_outputs_it++;
}
}
}
EXPECT_EQ(expected_outputs_it, test_case.expected_outputs.end());
}
INSTANTIATE_TEST_CASE_P(WindowDatasetOpTest, ParameterizedGetNextTest,
::testing::ValuesIn(GetNextTestCases()));
TEST_F(WindowDatasetOpTest, DatasetTypeString) {
auto dataset_params = WindowDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetTypeString(
name_utils::OpName(WindowDatasetOp::kDatasetType)));
}
TEST_F(WindowDatasetOpTest, DatasetNodeName) {
auto dataset_params = WindowDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name()));
}
TEST_F(WindowDatasetOpTest, DatasetOutputDtypes) {
auto dataset_params = WindowDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetOutputDtypes(dataset_params.output_dtypes()));
}
TEST_F(WindowDatasetOpTest, DatasetOutputShapes) {
auto dataset_params = WindowDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetOutputShapes(dataset_params.output_shapes()));
}
std::vector<CardinalityTestCase<WindowDatasetParams>>
DatasetCardinalityTestCases() {
return {{WindowDatasetParams1(),
4},
{WindowDatasetParams2(),
3},
{WindowDatasetParams3(),
3},
{WindowDatasetParams4(),
0},
{WindowDatasetParams5(),
1},
{WindowDatasetParams6(),
1},
{WindowDatasetParams7(),
4},
{WindowDatasetParams8(),
0},
{WindowDatasetParams9(),
1},
{WindowDatasetParams10(),
0}};
}
DATASET_CARDINALITY_TEST_P(WindowDatasetOpTest, WindowDatasetParams,
DatasetCardinalityTestCases())
TEST_F(WindowDatasetOpTest, IteratorOutputDtypes) {
auto dataset_params = WindowDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorOutputDtypes(dataset_params.output_dtypes()));
}
TEST_F(WindowDatasetOpTest, IteratorOutputShapes) {
auto dataset_params = WindowDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorOutputShapes(dataset_params.output_shapes()));
}
TEST_F(WindowDatasetOpTest, IteratorOutputPrefix) {
auto dataset_params = WindowDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix(
WindowDatasetOp::kDatasetType, dataset_params.iterator_prefix())));
}
template <typename T>
struct IteratorSaveAndRestoreTestCase {
T dataset_params;
std::vector<int> breakpoints;
std::vector<std::vector<Tensor>> expected_outputs;
};
std::vector<IteratorSaveAndRestoreTestCase<WindowDatasetParams>>
IteratorSaveAndRestoreTestCases() {
return {{WindowDatasetParams1(),
{0, 1, 9},
{CreateTensors<int64_t>(TensorShape{}, {{0}, {1}}),
CreateTensors<int64_t>(TensorShape{}, {{2}, {3}}),
CreateTensors<int64_t>(TensorShape{}, {{4}, {5}}),
CreateTensors<int64_t>(TensorShape{}, {{6}})}},
{WindowDatasetParams2(),
{0, 1, 9},
{CreateTensors<int64_t>(TensorShape{}, {{0}, {2}}),
CreateTensors<int64_t>(TensorShape{}, {{2}, {4}}),
CreateTensors<int64_t>(TensorShape{}, {{4}, {6}})}},
{WindowDatasetParams3(),
{0, 1, 9},
{CreateTensors<int64_t>(TensorShape({}),
{{0}, {1}, {2}, {3}, {4}, {5}, {6}}),
CreateTensors<int64_t>(TensorShape({}), {{3}, {4}, {5}, {6}}),
CreateTensors<int64_t>(TensorShape({}), {{6}})}},
{WindowDatasetParams4(),
{0, 1, 9},
{}},
{WindowDatasetParams5(),
{0, 1, 9},
{CreateTensors<int64_t>(TensorShape({}), {{0}, {1}})}},
{WindowDatasetParams6(),
{0, 1, 9},
{CreateTensors<int64_t>(TensorShape({}), {{0}, {1}})}},
{WindowDatasetParams7(),
{0, 1, 9},
{CreateTensors<int64_t>(TensorShape({}), {{0}}),
CreateTensors<int64_t>(TensorShape({}), {{2}}),
CreateTensors<int64_t>(TensorShape({}), {{4}}),
CreateTensors<int64_t>(TensorShape({}), {{6}})}},
{WindowDatasetParams8(),
{0, 1, 9},
{}},
{WindowDatasetParams9(),
{0, 1, 9},
{CreateTensors<int64_t>(TensorShape({}), {{0}, {2}, {4}, {6}})}},
{WindowDatasetParams10(),
{0, 1, 9},
{}}};
}
class ParameterizedIteratorSaveAndRestoreTest
: public WindowDatasetOpTest,
public ::testing::WithParamInterface<
IteratorSaveAndRestoreTestCase<WindowDatasetParams>> {};
TEST_P(ParameterizedIteratorSaveAndRestoreTest, IteratorSaveAndRestore) {
auto test_case = GetParam();
TF_ASSERT_OK(Initialize(test_case.dataset_params));
std::unique_ptr<SerializationContext> serialization_ctx;
TF_ASSERT_OK(CreateSerializationContext(&serialization_ctx));
std::unique_ptr<SerializationContext> window_serialization_ctx;
TF_ASSERT_OK(CreateSerializationContext(&window_serialization_ctx));
bool end_of_sequence = false;
auto expected_outputs_it = test_case.expected_outputs.begin();
int cur_iteration = 0;
for (int breakpoint : test_case.breakpoints) {
VariantTensorDataWriter writer;
TF_EXPECT_OK(iterator_->Save(serialization_ctx.get(), &writer));
std::vector<const VariantTensorData*> data;
writer.GetData(&data);
VariantTensorDataReader reader(data);
TF_EXPECT_OK(RestoreIterator(iterator_ctx_.get(), &reader,
test_case.dataset_params.iterator_prefix(),
*dataset_, &iterator_));
while (cur_iteration <= breakpoint) {
while (!end_of_sequence) {
std::vector<Tensor> out_tensors;
TF_EXPECT_OK(iterator_->GetNext(iterator_ctx_.get(), &out_tensors,
&end_of_sequence));
if (!end_of_sequence) {
for (const auto& window_dataset_tensor : out_tensors) {
DatasetBase* window_dataset;
TF_ASSERT_OK(GetDatasetFromVariantTensor(window_dataset_tensor,
&window_dataset));
std::unique_ptr<IteratorBase> window_dataset_iterator;
TF_ASSERT_OK(window_dataset->MakeIterator(
iterator_ctx_.get(), nullptr,
test_case.dataset_params.iterator_prefix(),
&window_dataset_iterator));
bool end_of_window_dataset = false;
std::vector<Tensor> window_elements;
VariantTensorDataWriter window_dataset_writer;
std::vector<const VariantTensorData*> window_dataset_data;
TF_EXPECT_OK(window_dataset_iterator->Save(
window_serialization_ctx.get(), &window_dataset_writer));
window_dataset_writer.GetData(&window_dataset_data);
VariantTensorDataReader window_reader(window_dataset_data);
while (!end_of_window_dataset) {
std::vector<Tensor> next_element;
TF_EXPECT_OK(window_dataset_iterator->GetNext(
iterator_ctx_.get(), &next_element, &end_of_window_dataset));
}
TF_EXPECT_OK(
RestoreIterator(iterator_ctx_.get(), &window_reader,
test_case.dataset_params.iterator_prefix(),
*window_dataset, &window_dataset_iterator));
end_of_window_dataset = false;
while (!end_of_window_dataset) {
std::vector<Tensor> next_element;
TF_EXPECT_OK(window_dataset_iterator->GetNext(
iterator_ctx_.get(), &next_element, &end_of_window_dataset));
window_elements.insert(window_elements.end(),
next_element.begin(), next_element.end());
}
EXPECT_LT(expected_outputs_it, test_case.expected_outputs.end());
TF_EXPECT_OK(
ExpectEqual(window_elements, *expected_outputs_it, false));
expected_outputs_it++;
}
}
}
cur_iteration++;
}
}
EXPECT_EQ(expected_outputs_it, test_case.expected_outputs.end());
}
INSTANTIATE_TEST_CASE_P(WindowDatasetOpTest,
ParameterizedIteratorSaveAndRestoreTest,
::testing::ValuesIn(IteratorSaveAndRestoreTestCases()));
TEST_F(WindowDatasetOpTest, InvalidArguments) {
std::vector<WindowDatasetParams> dataset_params_vec(
{WindowDatasetParamsWithInvalidWindowSize(),
WindowDatasetParamswithInvalidWindowShift(),
WindowDatasetParamsWithInvalidWindowStride()});
for (const auto& dataset_params : dataset_params_vec) {
EXPECT_EQ(Initialize(dataset_params).code(),
absl::StatusCode::kInvalidArgument);
}
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/data/window_dataset_op.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/data/window_dataset_op_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
8c9a6d30-6696-4abf-84bf-5fb88854d093 | cpp | google/quiche | quiche_time_utils | quiche/common/platform/api/quiche_time_utils.h | quiche/common/platform/api/quiche_time_utils_test.cc | #ifndef QUICHE_COMMON_PLATFORM_API_QUICHE_TIME_UTILS_H_
#define QUICHE_COMMON_PLATFORM_API_QUICHE_TIME_UTILS_H_
#include <cstdint>
#include "quiche_platform_impl/quiche_time_utils_impl.h"
namespace quiche {
inline std::optional<int64_t> QuicheUtcDateTimeToUnixSeconds(
int year, int month, int day, int hour, int minute, int second) {
return QuicheUtcDateTimeToUnixSecondsImpl(year, month, day, hour, minute,
second);
}
}
#endif | #include "quiche/common/platform/api/quiche_time_utils.h"
#include <optional>
#include "quiche/common/platform/api/quiche_test.h"
namespace quiche {
namespace {
TEST(QuicheTimeUtilsTest, Basic) {
EXPECT_EQ(1, QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 0, 0, 1));
EXPECT_EQ(365 * 86400, QuicheUtcDateTimeToUnixSeconds(1971, 1, 1, 0, 0, 0));
EXPECT_EQ(1152966896,
QuicheUtcDateTimeToUnixSeconds(2006, 7, 15, 12, 34, 56));
EXPECT_EQ(1591130001, QuicheUtcDateTimeToUnixSeconds(2020, 6, 2, 20, 33, 21));
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 2, 29, 0, 0, 1));
EXPECT_NE(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1972, 2, 29, 0, 0, 1));
}
TEST(QuicheTimeUtilsTest, Bounds) {
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 32, 0, 0, 1));
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 4, 31, 0, 0, 1));
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 0, 0, 0, 1));
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 13, 1, 0, 0, 1));
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 0, 1, 0, 0, 1));
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 24, 0, 0));
EXPECT_EQ(std::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 0, 60, 0));
}
TEST(QuicheTimeUtilsTest, LeapSecond) {
EXPECT_EQ(QuicheUtcDateTimeToUnixSeconds(2015, 6, 30, 23, 59, 60),
QuicheUtcDateTimeToUnixSeconds(2015, 7, 1, 0, 0, 0));
EXPECT_EQ(QuicheUtcDateTimeToUnixSeconds(2015, 6, 30, 25, 59, 60),
std::nullopt);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_time_utils.h | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_time_utils_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
b157befa-2457-49ea-98c8-27c339742c71 | cpp | tensorflow/tensorflow | pjrt_c_api_cpu | third_party/xla/xla/pjrt/c/pjrt_c_api_cpu.cc | third_party/xla/xla/pjrt/c/pjrt_c_api_cpu_test.cc | #include "xla/pjrt/c/pjrt_c_api_cpu.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_cpu_internal.h"
const PJRT_Api* GetPjrtApi() { return pjrt::cpu_plugin::GetCpuPjrtApi(); } | #include "xla/pjrt/c/pjrt_c_api_cpu.h"
#include "xla/pjrt/c/pjrt_c_api_test.h"
#include "xla/pjrt/c/pjrt_c_api_wrapper_impl.h"
namespace pjrt {
namespace {
const bool kUnused = (RegisterPjRtCApiTestFactory([]() { return GetPjrtApi(); },
"cpu"),
true);
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/pjrt/c/pjrt_c_api_cpu.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/pjrt/c/pjrt_c_api_cpu_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
429e12ca-dd05-4f23-8bf5-04fa9872c11b | cpp | tensorflow/tensorflow | op_stats_combiner | tensorflow/core/profiler/convert/op_stats_combiner.cc | tensorflow/core/profiler/convert/op_stats_combiner_test.cc | #include "tensorflow/core/profiler/convert/op_stats_combiner.h"
#include <algorithm>
#include <cstddef>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/profiler/convert/op_metrics_db_combiner.h"
#include "tensorflow/core/profiler/convert/xplane_to_tf_functions.h"
#include "tensorflow/core/profiler/protobuf/diagnostics.pb.h"
#include "tensorflow/core/profiler/protobuf/hardware_types.pb.h"
#include "tensorflow/core/profiler/protobuf/kernel_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/op_metrics.pb.h"
#include "tensorflow/core/profiler/protobuf/op_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/power_metrics.pb.h"
#include "tensorflow/core/profiler/protobuf/steps_db.pb.h"
#include "tensorflow/core/profiler/protobuf/topology.pb.h"
#include "tensorflow/core/profiler/utils/hardware_type_utils.h"
#include "tensorflow/core/profiler/utils/kernel_stats_utils.h"
#include "tensorflow/core/profiler/utils/step_intersection.h"
namespace tensorflow {
namespace profiler {
namespace {
void CombinePerCoreStepInfo(
int src_host_id, const PerCoreStepInfo& src, bool use_incomplete_step,
PerCoreStepInfo* dst,
OpMetricsDbCombiner* hlo_metrics_db_complete_steps_only_combiner,
OpMetricsDbCombiner* hlo_metrics_db_per_step_combiner) {
CombineCoreIdMap(src_host_id, src.step_info_per_core(),
dst->mutable_step_info_per_core());
uint32 new_step_num = dst->step_num();
for (auto& percore_stepinfo : *dst->mutable_step_info_per_core()) {
auto& stepinfo = percore_stepinfo.second;
stepinfo.set_step_num(new_step_num);
}
if (!use_incomplete_step) {
hlo_metrics_db_complete_steps_only_combiner->Combine(src.hlo_metrics_db());
}
hlo_metrics_db_per_step_combiner->Combine(src.hlo_metrics_db());
CombineCoreIdMap(src_host_id, src.all_reduce_db_per_core(),
dst->mutable_all_reduce_db_per_core());
CombineCoreIdMap(src_host_id, src.core_id_to_replica_id_map(),
dst->mutable_core_id_to_replica_id_map());
}
void CombineStepDatabase(
int src_host_id, const StepIntersection& step_intersection,
const StepDatabaseResult& src, StepDatabaseResult* dst,
OpMetricsDbCombiner* hlo_metrics_db_complete_steps_only_combiner,
std::vector<OpMetricsDbCombiner>* hlo_metrics_db_per_step_combiners) {
if (src.use_incomplete_step()) dst->set_use_incomplete_step(true);
uint32 src_first_step_idx = step_intersection.FirstStepIndex(src_host_id);
for (uint32 i = 0; i < step_intersection.NumSteps(); i++) {
CombinePerCoreStepInfo(
src_host_id, src.step_sequence(src_first_step_idx + i),
src.use_incomplete_step(), dst->mutable_step_sequence(i),
hlo_metrics_db_complete_steps_only_combiner,
&(*hlo_metrics_db_per_step_combiners)[i]);
}
}
void CombinePowerMetrics(const RunEnvironment& src, RunEnvironment* dst) {
const size_t src_hosts = src.hostnames_size();
const size_t dst_hosts = dst->hostnames_size();
const double src_weight = src_hosts * 1.0 / (src_hosts + dst_hosts);
const double dst_weight = dst_hosts * 1.0 / (src_hosts + dst_hosts);
for (const auto& src_metric : src.power_metrics().power_component_metrics()) {
for (auto& dst_metric :
*dst->mutable_power_metrics()->mutable_power_component_metrics()) {
if (src_metric.component_name() != dst_metric.component_name()) continue;
dst_metric.set_max_power(
std::max(src_metric.max_power(), dst_metric.max_power()));
dst_metric.set_avg_power(src_metric.avg_power() * src_weight +
dst_metric.avg_power() * dst_weight);
}
}
}
void CombineRunEnvironment(const RunEnvironment& src, RunEnvironment* dst) {
dst->mutable_hostnames()->insert(src.hostnames().begin(),
src.hostnames().end());
dst->set_host_count(dst->hostnames_size());
if (src.device_type() != "CPU" && src.device_type() != "Device") {
dst->set_device_type(src.device_type());
dst->set_device_core_count(src.device_core_count() +
dst->device_core_count());
dst->set_replica_count(std::max(src.replica_count(), dst->replica_count()));
dst->set_num_cores_per_replica(
std::max(src.num_cores_per_replica(), dst->num_cores_per_replica()));
*dst->mutable_system_topology() = src.system_topology();
} else if (dst->device_type().empty()) {
dst->set_device_type(src.device_type());
}
dst->set_task_count(src.task_count() + dst->task_count());
if (src.host_independent_job_info().profile_duration_ms() > 0) {
(*dst->mutable_host_independent_job_info()) =
src.host_independent_job_info();
}
for (const auto& job_info : src.host_dependent_job_info()) {
*(dst->add_host_dependent_job_info()) = job_info;
}
dst->set_host_trace_level(src.host_trace_level());
dst->set_is_training(src.is_training());
CombinePowerMetrics(src, dst);
}
void CombinePerfEnv(const PerfEnv& src, PerfEnv* dst) {
if (src.peak_tera_flops_per_second() > 0) {
dst->set_peak_tera_flops_per_second(src.peak_tera_flops_per_second());
}
if (src.peak_bws_giga_bytes_per_second_size() > 0 &&
dst->peak_bws_giga_bytes_per_second_size() == 0) {
*dst->mutable_peak_bws_giga_bytes_per_second() =
src.peak_bws_giga_bytes_per_second();
}
if (src.ridge_point() > 0) {
dst->set_ridge_point(src.ridge_point());
}
}
void CombineDiagnostics(const Diagnostics& src, Diagnostics* dst) {
dst->mutable_info()->MergeFrom(src.info());
dst->mutable_warnings()->MergeFrom(src.warnings());
dst->mutable_errors()->MergeFrom(src.errors());
}
void CombineOpStats(
bool no_accelerator_in_system, int src_host_id, HardwareType hardware_type,
const StepIntersection& step_intersection, const OpStats& src, OpStats* dst,
OpMetricsDbCombiner* host_op_metrics_db_combiner,
OpMetricsDbCombiner* device_op_metrics_db_combiner,
OpMetricsDbCombiner* hlo_metrics_db_complete_steps_only_combiner,
std::vector<OpMetricsDbCombiner>* hlo_metrics_db_per_step_combiners) {
host_op_metrics_db_combiner->Combine(src.host_op_metrics_db(),
false);
device_op_metrics_db_combiner->Combine(src.device_op_metrics_db());
if (!IsCoordinator(no_accelerator_in_system, hardware_type)) {
CombineStepDatabase(src_host_id, step_intersection, src.step_db(),
dst->mutable_step_db(),
hlo_metrics_db_complete_steps_only_combiner,
hlo_metrics_db_per_step_combiners);
}
CombineRunEnvironment(src.run_environment(), dst->mutable_run_environment());
CombinePerfEnv(src.perf_env(), dst->mutable_perf_env());
CombineDiagnostics(src.diagnostics(), dst->mutable_diagnostics());
dst->mutable_kernel_stats_db()->mutable_reports()->MergeFrom(
src.kernel_stats_db().reports());
CombineTfFunctionDb(src.tf_function_db(), dst->mutable_tf_function_db());
CombineCoreIdMap(src_host_id, src.core_id_to_details(),
dst->mutable_core_id_to_details());
dst->mutable_performance_counter_result()
->set_matrix_unit_utilization_percent(
dst->performance_counter_result().matrix_unit_utilization_percent() +
src.performance_counter_result().matrix_unit_utilization_percent());
}
}
bool IsCoordinator(bool no_accelerator_in_system, HardwareType hardware_type) {
return !HasDevice(hardware_type) && !no_accelerator_in_system;
}
bool NoAcceleratorInSystem(const std::vector<OpStatsInfo>& all_op_stats_info) {
for (const auto& op_stats_info : all_op_stats_info) {
if (HasDevice(op_stats_info.hardware_type)) {
return false;
}
}
return true;
}
uint32 GlobalCoreId(int host_id, uint32 device_ordinal) {
constexpr uint32 kMaxDevicesPerHost = 1000;
return host_id * kMaxDevicesPerHost + device_ordinal;
}
StepIntersection ComputeStepIntersectionToMergeOpStats(
const std::vector<OpStatsInfo>& all_op_stats_info,
uint32 max_step_per_host) {
bool no_accelerator_in_system = NoAcceleratorInSystem(all_op_stats_info);
absl::flat_hash_map<uint32, const StepDatabaseResult*> per_host_step_db;
for (const auto& op_stats_info : all_op_stats_info) {
if (IsCoordinator(no_accelerator_in_system, op_stats_info.hardware_type))
continue;
per_host_step_db[op_stats_info.src_host_id] =
&op_stats_info.op_stats->step_db();
}
return StepIntersection(max_step_per_host, per_host_step_db);
}
void CombineAllOpStats(const std::vector<OpStatsInfo>& all_op_stats_info,
const StepIntersection& step_intersection,
OpStats* combined_op_stats) {
if (all_op_stats_info.size() == 1) {
*combined_op_stats = *all_op_stats_info[0].op_stats;
return;
}
StepDatabaseResult* combined_step_db = combined_op_stats->mutable_step_db();
for (uint32 dst_step_num : step_intersection.DstStepNumbers()) {
combined_step_db->add_step_sequence()->set_step_num(dst_step_num);
}
combined_step_db->set_num_steps_dropped(step_intersection.StepsDropped());
combined_step_db->set_empty_intersect(step_intersection.EmptyIntersect());
OpMetricsDbCombiner host_op_metrics_db_combiner(
combined_op_stats->mutable_host_op_metrics_db());
OpMetricsDbCombiner device_op_metrics_db_combiner(
combined_op_stats->mutable_device_op_metrics_db());
OpMetricsDbCombiner hlo_metrics_db_complete_steps_only_combiner(
combined_op_stats->mutable_hlo_metrics_db_complete_steps_only());
std::vector<OpMetricsDbCombiner> hlo_metrics_db_per_step_combiners;
hlo_metrics_db_per_step_combiners.reserve(
combined_step_db->step_sequence_size());
for (PerCoreStepInfo& step_info :
*combined_step_db->mutable_step_sequence()) {
hlo_metrics_db_per_step_combiners.emplace_back(
step_info.mutable_hlo_metrics_db());
}
bool no_accelerator_in_system = NoAcceleratorInSystem(all_op_stats_info);
for (const auto& op_stats_info : all_op_stats_info) {
CombineOpStats(no_accelerator_in_system, op_stats_info.src_host_id,
op_stats_info.hardware_type, step_intersection,
*op_stats_info.op_stats, combined_op_stats,
&host_op_metrics_db_combiner, &device_op_metrics_db_combiner,
&hlo_metrics_db_complete_steps_only_combiner,
&hlo_metrics_db_per_step_combiners);
}
SortAndKeepTopKDurationKernelReportsInDb(
combined_op_stats->mutable_kernel_stats_db());
combined_op_stats->mutable_performance_counter_result()
->set_matrix_unit_utilization_percent(
combined_op_stats->performance_counter_result()
.matrix_unit_utilization_percent() /
all_op_stats_info.size());
}
}
} | #include "tensorflow/core/profiler/convert/op_stats_combiner.h"
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/protobuf/hardware_types.pb.h"
#include "tensorflow/core/profiler/protobuf/op_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/steps_db.pb.h"
#include "tensorflow/core/profiler/utils/step_intersection.h"
namespace tensorflow {
namespace profiler {
namespace {
TEST(CombineAllOpStatsTest, CombineRunEnvironment) {
OpStats dst_op_stats, op_stats_1, op_stats_2;
op_stats_1.mutable_run_environment()
->mutable_host_independent_job_info()
->set_profile_duration_ms(100);
op_stats_2.mutable_run_environment()
->mutable_host_independent_job_info()
->set_profile_duration_ms(0);
OpStatsInfo op_stats_info_1(&op_stats_1, TPU, 0),
op_stats_info_2(&op_stats_2, TPU, 0);
std::vector<OpStatsInfo> all_op_stats_info = {op_stats_info_1,
op_stats_info_2};
StepDatabaseResult dummy_step_db_result;
absl::flat_hash_map<uint32 , const StepDatabaseResult*> result;
result.insert({0, &dummy_step_db_result});
StepIntersection dummy_step_intersection = StepIntersection(1, result);
CombineAllOpStats(all_op_stats_info, dummy_step_intersection, &dst_op_stats);
EXPECT_EQ(100, dst_op_stats.run_environment()
.host_independent_job_info()
.profile_duration_ms());
}
TEST(CombineAllOpStatsTest, CombineRunEnvironmentWithUnknownDevice) {
OpStats dst_op_stats, op_stats_1, op_stats_2;
op_stats_1.mutable_run_environment()->set_device_type("TPU");
op_stats_2.mutable_run_environment()->set_device_type("Device");
OpStatsInfo op_stats_info_1(&op_stats_1, TPU, 0),
op_stats_info_2(&op_stats_2, TPU, 0);
std::vector<OpStatsInfo> all_op_stats_info = {op_stats_info_1,
op_stats_info_2};
StepDatabaseResult dummy_step_db_result;
absl::flat_hash_map<uint32 , const StepDatabaseResult*> result;
result.insert({0, &dummy_step_db_result});
StepIntersection dummy_step_intersection = StepIntersection(1, result);
CombineAllOpStats(all_op_stats_info, dummy_step_intersection, &dst_op_stats);
EXPECT_EQ("TPU", dst_op_stats.run_environment().device_type());
}
TEST(CombineAllOpStatsTest, CombinePerfEnvOrderZero) {
OpStats dst_op_stats1, dst_op_stats2, op_stats_1, op_stats_2;
op_stats_1.mutable_perf_env()->set_peak_tera_flops_per_second(100);
op_stats_2.mutable_perf_env()->set_peak_tera_flops_per_second(0);
absl::flat_hash_map<uint32 , const StepDatabaseResult*> result;
StepIntersection dummy_step_intersection = StepIntersection(1, result);
OpStatsInfo op_stats_info_1(&op_stats_1, TPU, 0),
op_stats_info_2(&op_stats_2, TPU, 0);
std::vector<OpStatsInfo> all_op_stats_info = {op_stats_info_1,
op_stats_info_2};
CombineAllOpStats(all_op_stats_info, dummy_step_intersection, &dst_op_stats1);
EXPECT_EQ(100, dst_op_stats1.perf_env().peak_tera_flops_per_second());
all_op_stats_info = {
op_stats_info_2,
op_stats_info_1,
};
CombineAllOpStats(all_op_stats_info, dummy_step_intersection, &dst_op_stats2);
EXPECT_EQ(100, dst_op_stats2.perf_env().peak_tera_flops_per_second());
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/profiler/convert/op_stats_combiner.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/profiler/convert/op_stats_combiner_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
5bb9930c-5eb7-4105-82de-1bfb82725b8c | cpp | tensorflow/tensorflow | function_optimization_registry | tensorflow/core/common_runtime/function_optimization_registry.cc | tensorflow/core/common_runtime/function_optimization_registry_test.cc | #include "tensorflow/core/common_runtime/function_optimization_registry.h"
#include <string>
#include "tensorflow/core/framework/metrics.h"
namespace tensorflow {
void FunctionOptimizationPassRegistry::Init(
std::unique_ptr<FunctionOptimizationPass> pass) {
DCHECK(!pass_) << "Only one pass should be set.";
pass_ = std::move(pass);
}
Status FunctionOptimizationPassRegistry::Run(
const std::string& function_name, const DeviceSet& device_set,
const ConfigProto& config_proto,
const FunctionOptimizationPass::FunctionOptions& function_options,
std::unique_ptr<Graph>* graph, FunctionLibraryDefinition* flib_def,
std::vector<std::string>* control_ret_node_names,
bool* control_rets_updated) {
if (!pass_) return absl::OkStatus();
tensorflow::metrics::ScopedCounter<2> timings(
tensorflow::metrics::GetGraphOptimizationCounter(),
{"GraphOptimizationPass", "FunctionOptimizationPassRegistry"});
return pass_->Run(function_name, device_set, config_proto, function_options,
graph, flib_def, control_ret_node_names,
control_rets_updated);
}
FunctionOptimizationPassRegistry& FunctionOptimizationPassRegistry::Global() {
static FunctionOptimizationPassRegistry* kGlobalRegistry =
new FunctionOptimizationPassRegistry;
return *kGlobalRegistry;
}
} | #include "tensorflow/core/common_runtime/function_optimization_registry.h"
#include <memory>
#include <string>
#include "tensorflow/core/common_runtime/device_set.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/protobuf/config.pb.h"
namespace tensorflow {
class PassingFunctionPass : public FunctionOptimizationPass {
public:
static bool ran_;
Status Run(const std::string& function_name, const DeviceSet& device_set,
const ConfigProto& config_proto,
const FunctionOptions& function_options,
std::unique_ptr<Graph>* graph, FunctionLibraryDefinition* flib_def,
std::vector<std::string>* control_ret_node_names,
bool* control_rets_updated) override {
ran_ = true;
return absl::OkStatus();
}
};
bool PassingFunctionPass::ran_ = false;
TEST(FunctionOptimizationPassRegistry, PassNoError) {
EXPECT_FALSE(PassingFunctionPass::ran_);
FunctionOptimizationPassRegistry::Global().Init(
std::make_unique<PassingFunctionPass>());
DeviceSet device_set;
ConfigProto config_proto;
FunctionOptimizationPass::FunctionOptions function_options;
Status status = FunctionOptimizationPassRegistry::Global().Run(
"test_func", device_set, config_proto, function_options,
nullptr,
nullptr,
nullptr, nullptr);
EXPECT_EQ(status, absl::OkStatus());
EXPECT_TRUE(PassingFunctionPass::ran_);
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/common_runtime/function_optimization_registry.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/common_runtime/function_optimization_registry_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
74dff902-ed21-4c41-9e79-1b623a9d17d4 | cpp | google/arolla | utility_operators | arolla/qexpr/operators/core/utility_operators.cc | arolla/qexpr/operators/core/utility_operators_test.cc | #include "arolla/qexpr/operators/core/utility_operators.h"
#include <memory>
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "arolla/memory/frame.h"
#include "arolla/qexpr/bound_operators.h"
#include "arolla/qexpr/eval_context.h"
#include "arolla/qexpr/operators.h"
#include "arolla/qexpr/qexpr_operator_signature.h"
#include "arolla/qtype/qtype.h"
namespace arolla {
namespace {
class CopyOperator : public QExprOperator {
public:
explicit CopyOperator(QTypePtr type)
: QExprOperator(QExprOperatorSignature::Get({type}, type)) {}
private:
absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind(
absl::Span<const TypedSlot> input_slots,
TypedSlot output_slot) const final {
return MakeBoundOperator(
[input_slot = input_slots[0], output_slot = output_slot](
EvaluationContext*, FramePtr frame) {
input_slot.CopyTo(frame, output_slot, frame);
});
}
};
}
OperatorPtr MakeCopyOp(QTypePtr type) {
return OperatorPtr(std::make_unique<CopyOperator>(type));
}
} | #include "arolla/qexpr/operators/core/utility_operators.h"
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "arolla/memory/frame.h"
#include "arolla/qexpr/eval_context.h"
#include "arolla/qexpr/operators.h"
#include "arolla/qexpr/qexpr_operator_signature.h"
#include "arolla/qtype/base_types.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/qtype/tuple_qtype.h"
#include "arolla/qtype/typed_slot.h"
namespace arolla {
namespace {
using ::testing::Eq;
TEST(UtilityOperatorsTest, Identity) {
auto i32 = GetQType<int>();
auto copy_op = MakeCopyOp(i32);
ASSERT_EQ(copy_op->signature(), QExprOperatorSignature::Get({i32}, i32));
FrameLayout::Builder layout_builder;
auto i0_slot = layout_builder.AddSlot<int>();
auto i1_slot = layout_builder.AddSlot<int>();
ASSERT_OK_AND_ASSIGN(
auto copy_bound_op0,
copy_op->Bind(ToTypedSlots(i0_slot), TypedSlot::FromSlot(i1_slot)));
auto memory_layout = std::move(layout_builder).Build();
RootEvaluationContext root_ctx(&memory_layout);
EvaluationContext ctx(root_ctx);
root_ctx.Set(i0_slot, 7);
copy_bound_op0->Run(&ctx, root_ctx.frame());
EXPECT_OK(ctx.status());
EXPECT_THAT(root_ctx.Get(i1_slot), Eq(7));
}
TEST(UtilityOperatorsTest, MakeTuple) {
auto i32 = GetQType<int>();
auto f64 = GetQType<double>();
auto tuple_qtype = MakeTupleQType({i32, f64});
ASSERT_OK_AND_ASSIGN(auto copy_op,
OperatorRegistry::GetInstance()->LookupOperator(
"core.make_tuple", {i32, f64}, tuple_qtype));
ASSERT_EQ(copy_op->signature(),
QExprOperatorSignature::Get({i32, f64}, tuple_qtype));
FrameLayout::Builder layout_builder;
auto tuple0_slot = AddSlot(tuple_qtype, &layout_builder);
ASSERT_EQ(tuple0_slot.SubSlotCount(), 2);
ASSERT_OK_AND_ASSIGN(auto i0_slot, tuple0_slot.SubSlot(0).ToSlot<int>());
ASSERT_OK_AND_ASSIGN(auto d0_slot, tuple0_slot.SubSlot(1).ToSlot<double>());
auto tuple1_slot = AddSlot(tuple_qtype, &layout_builder);
ASSERT_EQ(tuple1_slot.SubSlotCount(), 2);
ASSERT_OK_AND_ASSIGN(auto i1_slot, tuple1_slot.SubSlot(0).ToSlot<int>());
ASSERT_OK_AND_ASSIGN(auto d1_slot, tuple1_slot.SubSlot(1).ToSlot<double>());
ASSERT_OK_AND_ASSIGN(
auto copy_bound_op,
copy_op->Bind(ToTypedSlots(i0_slot, d0_slot), {tuple1_slot}));
auto memory_layout = std::move(layout_builder).Build();
RootEvaluationContext root_ctx(&memory_layout);
EvaluationContext ctx(root_ctx);
root_ctx.Set(i0_slot, 7);
root_ctx.Set(d0_slot, 4.5);
copy_bound_op->Run(&ctx, root_ctx.frame());
EXPECT_OK(ctx.status());
EXPECT_THAT(root_ctx.Get(i1_slot), Eq(7));
EXPECT_THAT(root_ctx.Get(d1_slot), Eq(4.5));
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/utility_operators.cc | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/utility_operators_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
1acdc449-82ca-466a-ac4b-e2a65acee19e | cpp | tensorflow/tensorflow | gcs_throttle | third_party/xla/third_party/tsl/tsl/platform/cloud/gcs_throttle.cc | third_party/xla/third_party/tsl/tsl/platform/cloud/gcs_throttle_test.cc | #include "tsl/platform/cloud/gcs_throttle.h"
#include <algorithm>
namespace tsl {
namespace {
EnvTime* get_default_env_time() {
static EnvTime* default_env_time = new EnvTime;
return default_env_time;
}
}
GcsThrottle::GcsThrottle(EnvTime* env_time)
: last_updated_secs_(env_time ? env_time->GetOverridableNowSeconds()
: EnvTime::NowSeconds()),
available_tokens_(0),
env_time_(env_time ? env_time : get_default_env_time()) {}
bool GcsThrottle::AdmitRequest() {
mutex_lock l(mu_);
UpdateState();
if (available_tokens_ < config_.tokens_per_request) {
return false || !config_.enabled;
}
available_tokens_ -= config_.tokens_per_request;
return true;
}
void GcsThrottle::RecordResponse(size_t num_bytes) {
mutex_lock l(mu_);
UpdateState();
available_tokens_ -= request_bytes_to_tokens(num_bytes);
}
void GcsThrottle::SetConfig(GcsThrottleConfig config) {
mutex_lock l(mu_);
config_ = config;
available_tokens_ = config.initial_tokens;
last_updated_secs_ = env_time_->GetOverridableNowSeconds();
}
void GcsThrottle::UpdateState() {
int64_t now = env_time_->GetOverridableNowSeconds();
uint64 delta_secs =
std::max(int64_t{0}, now - static_cast<int64_t>(last_updated_secs_));
available_tokens_ += delta_secs * config_.token_rate;
available_tokens_ = std::min(available_tokens_, config_.bucket_size);
last_updated_secs_ = now;
}
} | #include "tsl/platform/cloud/gcs_throttle.h"
#include "xla/tsl/lib/core/status_test_util.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
class TestTime : public EnvTime {
public:
uint64 GetOverridableNowNanos() const override {
return now_micros_ * kMicrosToNanos;
}
void SetTime(uint64 now_micros) { now_micros_ = now_micros; }
void AdvanceSeconds(int64_t secs) { now_micros_ += secs * kSecondsToMicros; }
private:
uint64 now_micros_ = 1234567890000000ULL;
};
class GcsThrottleTest : public ::testing::Test {
protected:
GcsThrottleTest() : throttle_(&time_) {
config_.enabled = true;
throttle_.SetConfig(config_);
}
GcsThrottleConfig config_;
TestTime time_;
GcsThrottle throttle_;
};
TEST_F(GcsThrottleTest, ReplenishTokens) {
EXPECT_EQ(0, throttle_.available_tokens());
time_.AdvanceSeconds(1);
EXPECT_EQ(100000, throttle_.available_tokens());
time_.AdvanceSeconds(2);
EXPECT_EQ(300000, throttle_.available_tokens());
}
TEST_F(GcsThrottleTest, RejectRequest) {
EXPECT_EQ(0, throttle_.available_tokens());
time_.AdvanceSeconds(1);
EXPECT_TRUE(throttle_.AdmitRequest());
EXPECT_EQ(99900, throttle_.available_tokens());
for (int i = 1; i < 1000; i++) {
EXPECT_TRUE(throttle_.AdmitRequest());
}
EXPECT_FALSE(throttle_.AdmitRequest());
}
TEST_F(GcsThrottleTest, MarkResponses) {
time_.AdvanceSeconds(1);
EXPECT_TRUE(throttle_.AdmitRequest());
throttle_.RecordResponse(128000000);
EXPECT_EQ(-25100, throttle_.available_tokens());
EXPECT_FALSE(throttle_.AdmitRequest());
time_.AdvanceSeconds(1);
EXPECT_TRUE(throttle_.AdmitRequest())
<< "Available tokens: " << throttle_.available_tokens();
}
TEST_F(GcsThrottleTest, Skippingtime_) {
EXPECT_EQ(0, throttle_.available_tokens());
time_.AdvanceSeconds(90);
EXPECT_EQ(9000000, throttle_.available_tokens());
}
TEST_F(GcsThrottleTest, BucketLimit) {
time_.AdvanceSeconds(120);
EXPECT_EQ(10000000, throttle_.available_tokens());
}
TEST_F(GcsThrottleTest, ReverseTime) {
time_.AdvanceSeconds(1);
EXPECT_EQ(100000, throttle_.available_tokens());
time_.AdvanceSeconds(-3600);
EXPECT_EQ(100000, throttle_.available_tokens());
time_.AdvanceSeconds(1);
EXPECT_EQ(200000, throttle_.available_tokens());
}
TEST(GcsThrottleDisabledTest, Disabled) {
TestTime time;
GcsThrottle throttle(&time);
ASSERT_FALSE(throttle.is_enabled());
EXPECT_EQ(0, throttle.available_tokens());
time.AdvanceSeconds(1);
EXPECT_EQ(100000, throttle.available_tokens());
EXPECT_TRUE(throttle.AdmitRequest());
EXPECT_EQ(99900, throttle.available_tokens());
time.AdvanceSeconds(1);
EXPECT_EQ(199900, throttle.available_tokens());
throttle.RecordResponse(128000000);
EXPECT_LT(0, throttle.available_tokens());
EXPECT_TRUE(throttle.AdmitRequest());
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/third_party/tsl/tsl/platform/cloud/gcs_throttle.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/third_party/tsl/tsl/platform/cloud/gcs_throttle_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
37982d4d-cc04-490b-a3c7-68edcd3f1dc4 | cpp | tensorflow/tensorflow | gpu_bfc_allocator | tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc | tensorflow/core/common_runtime/gpu/gpu_bfc_allocator_test.cc | #include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h"
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include "xla/tsl/framework/bfc_allocator.h"
#include "tsl/platform/logging.h"
namespace tensorflow {
namespace {
bool GetAllowGrowthValue(bool orig_value) {
const char* force_allow_growth_string =
std::getenv("TF_FORCE_GPU_ALLOW_GROWTH");
if (force_allow_growth_string == nullptr) {
return orig_value;
}
if (strcmp("false", force_allow_growth_string) == 0) {
if (orig_value) {
LOG(WARNING)
<< "Overriding orig_value setting because the"
<< " TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original"
<< " config value was " << orig_value << ".";
}
return false;
} else if (strcmp("true", force_allow_growth_string) == 0) {
if (!orig_value) {
LOG(WARNING)
<< "Overriding orig_value setting because the"
<< " TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original"
<< " config value was " << orig_value << ".";
}
return true;
}
LOG(ERROR)
<< "The TF_FORCE_GPU_ALLOW_GROWTH environment variable is set but could"
<< " not be parsed: \"" << force_allow_growth_string << "\". Valid"
<< " values are \"true\" or \"false\". Using original config value"
<< " of " << orig_value << ".";
return orig_value;
}
bool GetGarbageCollectionValue() {
const char* enable_gpu_garbage_collection =
std::getenv("TF_ENABLE_GPU_GARBAGE_COLLECTION");
if (enable_gpu_garbage_collection == nullptr) {
return true;
}
if (strcmp("false", enable_gpu_garbage_collection) == 0) {
return false;
} else if (strcmp("true", enable_gpu_garbage_collection) == 0) {
return true;
}
LOG(ERROR)
<< "The TF_ENABLE_GPU_GARBAGE_COLLECTION environment variable is set but"
<< " could not be parsed: \"" << enable_gpu_garbage_collection << "\"."
<< " Valid values are \"true\" or \"false\"."
<< " Using the default value \"true\".";
return true;
}
}
GPUBFCAllocator::GPUBFCAllocator(
std::unique_ptr<tsl::SubAllocator> sub_allocator, size_t total_memory,
const std::string& name, const Options& opts)
: BFCAllocator(std::move(sub_allocator), total_memory, name, [&] {
BFCAllocator::Options o;
o.allow_growth = GetAllowGrowthValue(opts.allow_growth);
o.allow_retry_on_failure = opts.allow_retry_on_failure;
if (opts.garbage_collection.has_value()) {
o.garbage_collection = *opts.garbage_collection;
} else {
o.garbage_collection = GetGarbageCollectionValue();
}
o.fragmentation_fraction = opts.fragmentation_fraction;
return o;
}()) {}
} | #if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \
(defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)
#include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h"
#include <algorithm>
#include <optional>
#include <vector>
#include "xla/stream_executor/gpu/gpu_driver.h"
#include "xla/stream_executor/gpu/gpu_init.h"
#include "xla/stream_executor/stream_executor.h"
#include "xla/tsl/framework/device_id.h"
#include "xla/tsl/lib/gtl/inlined_vector.h"
#include "xla/tsl/lib/random/simple_philox.h"
#include "tensorflow/core/common_runtime/device/device_mem_allocator.h"
#include "tensorflow/core/framework/typed_allocator.h"
#include "tensorflow/core/protobuf/bfc_memory_map.pb.h"
#include "tensorflow/core/protobuf/config.pb.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/test.h"
#include "tsl/platform/test_benchmark.h"
#include "tsl/platform/threadpool.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace {
using stream_executor::GPUMachineManager;
using tensorflow::BinSummary;
using tensorflow::DeviceMemAllocator;
using tensorflow::GPUBFCAllocator;
using tensorflow::GPUOptions;
using tensorflow::TypedAllocator;
void CheckStats(Allocator* a, int64_t num_allocs, int64_t bytes_in_use,
int64_t peak_bytes_in_use, int64_t largest_alloc_size) {
std::optional<AllocatorStats> stats = a->GetStats();
EXPECT_TRUE(stats);
if (!stats) {
return;
}
LOG(INFO) << "Alloc stats: " << std::endl << stats->DebugString();
EXPECT_EQ(stats->bytes_in_use, bytes_in_use);
EXPECT_EQ(stats->peak_bytes_in_use, peak_bytes_in_use);
EXPECT_EQ(stats->num_allocs, num_allocs);
EXPECT_EQ(stats->largest_alloc_size, largest_alloc_size);
}
class GPUBFCAllocatorTest
: public ::testing::TestWithParam<std::unique_ptr<SubAllocator> (*)(
size_t)> {};
std::unique_ptr<SubAllocator> CreateGPUMemAllocator(size_t) {
PlatformDeviceId gpu_id(0);
return absl::WrapUnique(new DeviceMemAllocator(
GPUMachineManager()->ExecutorForDevice(gpu_id.value()).value(), gpu_id,
stream_executor::MemoryType::kDevice, {}, {}));
}
std::unique_ptr<SubAllocator> CreateSubAllocator(
size_t virtual_address_space_size = 1ull << 32) {
return CreateGPUMemAllocator(virtual_address_space_size);
}
auto TestSuiteValues() { return ::testing::Values(&CreateGPUMemAllocator); }
TEST_P(GPUBFCAllocatorTest, NoDups) {
GPUBFCAllocator a(GetParam()(1ull << 32), 1 << 30, "GPU_0_bfc", {});
CheckStats(&a, 0, 0, 0, 0);
std::vector<void*> ptrs;
for (int s = 1; s < 1024; s++) {
void* raw = a.AllocateRaw(1, s);
ptrs.push_back(raw);
}
CheckStats(&a, 1023, 654336, 654336, 1024);
std::sort(ptrs.begin(), ptrs.end());
for (size_t i = 1; i < ptrs.size(); i++) {
ASSERT_NE(ptrs[i], ptrs[i - 1]);
size_t req_size = a.RequestedSize(ptrs[i - 1]);
ASSERT_GT(req_size, 0);
ASSERT_GE(static_cast<char*>(ptrs[i]) - static_cast<char*>(ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < ptrs.size(); i++) {
a.DeallocateRaw(ptrs[i]);
}
CheckStats(&a, 1023, 0, 654336, 1024);
}
TEST_P(GPUBFCAllocatorTest, AllocationsAndDeallocations) {
GPUBFCAllocator a(GetParam()(1ull << 32), 1 << 30, "GPU_0_bfc", {});
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rand(&philox);
std::vector<void*> initial_ptrs;
for (int s = 1; s < 256; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576);
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
std::vector<void*> existing_ptrs;
for (size_t i = 0; i < initial_ptrs.size(); i++) {
if (i % 2 == 1) {
a.DeallocateRaw(initial_ptrs[i]);
} else {
existing_ptrs.push_back(initial_ptrs[i]);
}
}
void* out_of_memory_ptr = a.AllocateRaw(1, (1 << 30) + 1);
CHECK_EQ(out_of_memory_ptr, nullptr);
for (int s = 1; s < 256; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576);
void* raw = a.AllocateRaw(1, size);
existing_ptrs.push_back(raw);
}
std::sort(existing_ptrs.begin(), existing_ptrs.end());
for (size_t i = 1; i < existing_ptrs.size(); i++) {
CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]);
size_t req_size = a.RequestedSize(existing_ptrs[i - 1]);
ASSERT_GT(req_size, 0);
ASSERT_GE(static_cast<char*>(existing_ptrs[i]) -
static_cast<char*>(existing_ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < existing_ptrs.size(); i++) {
a.DeallocateRaw(existing_ptrs[i]);
}
}
TEST_P(GPUBFCAllocatorTest, ExerciseCoalescing) {
GPUBFCAllocator a(GetParam()(1ull << 32), 1 << 30, "GPU_0_bfc", {});
CheckStats(&a, 0, 0, 0, 0);
float* first_ptr = TypedAllocator::Allocate<float>(&a, 1024, {});
a.DeallocateRaw(first_ptr);
CheckStats(&a, 1, 0, 4096, 4096);
for (int i = 0; i < 1024; ++i) {
float* t1 = TypedAllocator::Allocate<float>(&a, 1024, {});
int64_t* t2 = TypedAllocator::Allocate<int64_t>(&a, 1048576, {});
double* t3 = TypedAllocator::Allocate<double>(&a, 2048, {});
float* t4 = TypedAllocator::Allocate<float>(&a, 10485760, {});
a.DeallocateRaw(t1);
a.DeallocateRaw(t2);
a.DeallocateRaw(t3);
a.DeallocateRaw(t4);
}
CheckStats(&a, 4097, 0,
1024 * sizeof(float) + 1048576 * sizeof(int64_t) +
2048 * sizeof(double) + 10485760 * sizeof(float),
10485760 * sizeof(float));
float* first_ptr_after = TypedAllocator::Allocate<float>(&a, 1024, {});
EXPECT_EQ(first_ptr, first_ptr_after);
a.DeallocateRaw(first_ptr_after);
}
TEST_P(GPUBFCAllocatorTest, AllocateZeroBufSize) {
GPUBFCAllocator a(GetParam()(1ull << 32), 1 << 30, "GPU_0_bfc", {});
float* ptr = TypedAllocator::Allocate<float>(&a, 0, {});
EXPECT_EQ(nullptr, ptr);
}
TEST_P(GPUBFCAllocatorTest, TracksSizes) {
GPUBFCAllocator a(GetParam()(1ull << 32), 1 << 30, "GPU_0_bfc", {});
EXPECT_EQ(true, a.TracksAllocationSizes());
}
TEST_P(GPUBFCAllocatorTest, AllocatedVsRequested) {
GPUBFCAllocator a(GetParam()(1ull << 32), 1 << 30, "GPU_0_bfc", {});
float* t1 = TypedAllocator::Allocate<float>(&a, 1, {});
EXPECT_EQ(4, a.RequestedSize(t1));
EXPECT_EQ(256, a.AllocatedSize(t1));
a.DeallocateRaw(t1);
}
TEST_P(GPUBFCAllocatorTest, TestCustomMemoryLimit) {
GPUBFCAllocator a(GetParam()(1ull << 32), 2 << 20, "GPU_0_bfc", {});
float* first_ptr = TypedAllocator::Allocate<float>(&a, 1 << 6, {});
float* second_ptr = TypedAllocator::Allocate<float>(&a, 2 << 20, {});
EXPECT_NE(nullptr, first_ptr);
EXPECT_EQ(nullptr, second_ptr);
a.DeallocateRaw(first_ptr);
}
TEST_P(GPUBFCAllocatorTest, AllocationsAndDeallocationsWithGrowth) {
GPUOptions options;
options.set_allow_growth(true);
GPUBFCAllocator a(GetParam()(1ull << 32), 1LL << 31, "GPU_0_bfc", {});
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rand(&philox);
const int32_t max_mem = 1 << 27;
std::vector<void*> initial_ptrs;
for (int s = 1; s < 10; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % max_mem, 100), max_mem);
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
std::vector<void*> existing_ptrs;
for (size_t i = 0; i < initial_ptrs.size(); i++) {
if (i % 2 == 1) {
a.DeallocateRaw(initial_ptrs[i]);
} else {
existing_ptrs.push_back(initial_ptrs[i]);
}
}
const int32_t max_mem_2 = 1 << 26;
for (int s = 1; s < 10; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % max_mem_2, 100), max_mem_2);
void* raw = a.AllocateRaw(1, size);
existing_ptrs.push_back(raw);
}
std::sort(existing_ptrs.begin(), existing_ptrs.end());
for (size_t i = 1; i < existing_ptrs.size(); i++) {
CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]);
size_t req_size = a.RequestedSize(existing_ptrs[i - 1]);
ASSERT_GT(req_size, 0);
ASSERT_GE(static_cast<char*>(existing_ptrs[i]) -
static_cast<char*>(existing_ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < existing_ptrs.size(); i++) {
a.DeallocateRaw(existing_ptrs[i]);
}
std::optional<AllocatorStats> stats = a.GetStats();
if (stats) {
LOG(INFO) << "Alloc stats: \n" << stats->DebugString();
}
}
TEST_P(GPUBFCAllocatorTest, DISABLED_AllocatorReceivesZeroMemory) {
GPUBFCAllocator a(GetParam()(1ul << 62), 1UL << 60, "GPU_0_bfc", {});
GPUBFCAllocator b(GetParam()(1ul << 62), 1UL << 60, "GPU_0_bfc", {});
void* amem = a.AllocateRaw(1, 1);
void* bmem = b.AllocateRaw(1, 1 << 30);
a.DeallocateRaw(amem);
b.DeallocateRaw(bmem);
}
INSTANTIATE_TEST_SUITE_P(GPUBFCAllocatorTestSuite, GPUBFCAllocatorTest,
TestSuiteValues());
static void BM_Allocation(::testing::benchmark::State& state) {
GPUBFCAllocator a(CreateSubAllocator(1ul << 36), 1uLL << 33, "GPU_0_bfc", {});
std::vector<size_t> sizes = {256, 4096, 16384, 524288,
512, 1048576, 10485760, 104857600,
1048576000, 2048576000};
int size_index = 0;
for (auto s : state) {
size_t bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
a.DeallocateRaw(p);
}
}
BENCHMARK(BM_Allocation);
static void BM_AllocationThreaded(::testing::benchmark::State& state) {
int num_threads = state.range(0);
int sub_iters = 500;
for (auto s : state) {
state.PauseTiming();
GPUBFCAllocator a(CreateSubAllocator(1ul << 36), 1uLL << 33, "GPU_0_bfc",
{});
thread::ThreadPool pool(Env::Default(), "test", num_threads);
std::atomic_int_fast32_t count(sub_iters);
mutex done_lock;
condition_variable done;
bool done_flag = false;
state.ResumeTiming();
for (int t = 0; t < num_threads; t++) {
pool.Schedule([&a, &count, &done_lock, &done, &done_flag, sub_iters]() {
std::vector<int> sizes = {256, 4096, 16384, 524288,
512, 1048576, 10485760, 104857600};
int size_index = 0;
for (int i = 0; i < sub_iters; i++) {
int bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
a.DeallocateRaw(p);
if (count.fetch_sub(1) == 1) {
mutex_lock l(done_lock);
done_flag = true;
done.notify_all();
break;
}
}
});
}
mutex_lock l(done_lock);
if (!done_flag) {
done.wait(l);
}
}
}
BENCHMARK(BM_AllocationThreaded)->Arg(1)->Arg(4)->Arg(16);
static void BM_AllocationDelayed(::testing::benchmark::State& state) {
int delay = state.range(0);
GPUBFCAllocator a(CreateSubAllocator(1ull << 32), 1 << 30, "GPU_0_bfc", {});
std::vector<int> sizes = {256, 4096, 16384, 4096, 512, 1024, 1024};
int size_index = 0;
std::vector<void*> ptrs;
ptrs.reserve(delay);
for (int i = 0; i < delay; i++) {
ptrs.push_back(nullptr);
}
int pindex = 0;
for (auto s : state) {
if (ptrs[pindex] != nullptr) {
a.DeallocateRaw(ptrs[pindex]);
ptrs[pindex] = nullptr;
}
int bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
ptrs[pindex] = p;
pindex = (pindex + 1) % ptrs.size();
}
for (int i = 0; i < ptrs.size(); i++) {
if (ptrs[i] != nullptr) {
a.DeallocateRaw(ptrs[i]);
}
}
}
BENCHMARK(BM_AllocationDelayed)->Arg(1)->Arg(10)->Arg(100)->Arg(1000);
}
class GPUBFCAllocatorPrivateMethodsTest
: public ::testing::TestWithParam<std::unique_ptr<SubAllocator> (*)(
size_t)> {
protected:
void SetUp() override { CHECK_EQ(unsetenv("TF_FORCE_GPU_ALLOW_GROWTH"), 0); }
void TestBinDebugInfo() {
GPUBFCAllocator a(GetParam()(1ull << 32), 1 << 30, "GPU_0_bfc", {});
std::vector<void*> initial_ptrs;
std::vector<size_t> initial_ptrs_allocated_sizes;
const int kNumTestSizes = 5;
const int kNumChunksPerSize = 2;
for (int i = 0; i < kNumTestSizes; i++) {
for (int j = 0; j < kNumChunksPerSize; j++) {
size_t size = 256 << i;
void* raw = a.AllocateRaw(1, size);
ASSERT_NE(raw, nullptr);
initial_ptrs.push_back(raw);
initial_ptrs_allocated_sizes.push_back(a.AllocatedSize(raw));
}
}
std::array<BFCAllocator::BinDebugInfo, BFCAllocator::kNumBins> bin_infos;
{
absl::MutexLock l(&a.mutex_);
bin_infos = a.get_bin_debug_info();
}
{
MemoryDump md = a.RecordMemoryMap();
EXPECT_EQ(md.chunk_size(), 1 + (kNumTestSizes * kNumChunksPerSize));
for (int i = 0; i < BFCAllocator::kNumBins; i++) {
const BFCAllocator::BinDebugInfo& bin_info = bin_infos[i];
const BinSummary& bin_summary = md.bin_summary(i);
if (i < kNumTestSizes) {
const size_t requested_size = 2 * (256 << i);
EXPECT_EQ(requested_size,
a.RequestedSize(initial_ptrs[2 * i]) +
a.RequestedSize(initial_ptrs[2 * i + 1]));
size_t allocated_size = initial_ptrs_allocated_sizes[2 * i] +
initial_ptrs_allocated_sizes[2 * i + 1];
EXPECT_EQ(bin_info.total_bytes_in_use, allocated_size);
EXPECT_EQ(bin_summary.total_bytes_in_use(), allocated_size);
EXPECT_EQ(bin_info.total_bytes_in_bin, allocated_size);
EXPECT_EQ(bin_summary.total_bytes_in_bin(), allocated_size);
EXPECT_EQ(bin_info.total_requested_bytes_in_use, requested_size);
EXPECT_EQ(bin_info.total_chunks_in_use, kNumChunksPerSize);
EXPECT_EQ(bin_summary.total_chunks_in_use(), kNumChunksPerSize);
EXPECT_EQ(bin_info.total_chunks_in_bin, kNumChunksPerSize);
EXPECT_EQ(bin_summary.total_chunks_in_bin(), kNumChunksPerSize);
} else {
EXPECT_EQ(bin_info.total_bytes_in_use, 0);
EXPECT_EQ(bin_summary.total_bytes_in_use(), 0);
EXPECT_EQ(bin_info.total_requested_bytes_in_use, 0);
EXPECT_EQ(bin_info.total_chunks_in_use, 0);
EXPECT_EQ(bin_summary.total_chunks_in_use(), 0);
if (i == BFCAllocator::kNumBins - 1) {
EXPECT_GT(bin_info.total_bytes_in_bin, 0);
EXPECT_GT(bin_summary.total_bytes_in_bin(), 0);
EXPECT_EQ(bin_info.total_chunks_in_bin, 1);
EXPECT_EQ(bin_summary.total_chunks_in_bin(), 1);
} else {
EXPECT_EQ(bin_info.total_bytes_in_bin, 0);
EXPECT_EQ(bin_summary.total_bytes_in_bin(), 0);
EXPECT_EQ(bin_info.total_chunks_in_bin, 0);
EXPECT_EQ(bin_summary.total_chunks_in_bin(), 0);
}
}
}
}
for (size_t i = 1; i < initial_ptrs.size(); i += 2) {
a.DeallocateRaw(initial_ptrs[i]);
initial_ptrs[i] = nullptr;
}
{
absl::MutexLock l(&a.mutex_);
bin_infos = a.get_bin_debug_info();
}
for (int i = 0; i < BFCAllocator::kNumBins; i++) {
const BFCAllocator::BinDebugInfo& bin_info = bin_infos[i];
if (i < 5) {
size_t requested_size = 256 << i;
EXPECT_EQ(requested_size, a.RequestedSize(initial_ptrs[2 * i]));
EXPECT_EQ(bin_info.total_bytes_in_use,
initial_ptrs_allocated_sizes[2 * i]);
EXPECT_GE(bin_info.total_bytes_in_bin,
initial_ptrs_allocated_sizes[2 * i]);
EXPECT_EQ(bin_info.total_requested_bytes_in_use, requested_size);
EXPECT_EQ(bin_info.total_chunks_in_use, 1);
EXPECT_GE(bin_info.total_chunks_in_bin, 1);
} else {
EXPECT_EQ(bin_info.total_bytes_in_use, 0);
EXPECT_EQ(bin_info.total_requested_bytes_in_use, 0);
EXPECT_EQ(bin_info.total_chunks_in_use, 0);
}
}
}
void TestForceAllowGrowth() {
unsetenv("TF_FORCE_GPU_ALLOW_GROWTH");
GPUBFCAllocator::Options opts;
opts.allow_growth = true;
GPUBFCAllocator unset_flag_allocator(GetParam()(1ull << 32), 1LL << 31,
"GPU_0_bfc", opts);
EXPECT_EQ(GPUBFCAllocator::RoundedBytes(size_t{2 << 20}),
unset_flag_allocator.curr_region_allocation_bytes_);
setenv("TF_FORCE_GPU_ALLOW_GROWTH", "unparseable", 1);
GPUBFCAllocator unparsable_flag_allocator(GetParam()(1ull << 32), 1LL << 31,
"GPU_1_bfc", opts);
EXPECT_EQ(GPUBFCAllocator::RoundedBytes(size_t{2 << 20}),
unparsable_flag_allocator.curr_region_allocation_bytes_);
setenv("TF_FORCE_GPU_ALLOW_GROWTH", "true", 1);
opts.allow_growth = false;
GPUBFCAllocator force_allow_growth_allocator(GetParam()(1ull << 32),
1LL << 31, "GPU_2_bfc", opts);
EXPECT_EQ(GPUBFCAllocator::RoundedBytes(size_t{2 << 20}),
force_allow_growth_allocator.curr_region_allocation_bytes_);
setenv("TF_FORCE_GPU_ALLOW_GROWTH", "false", 1);
opts.allow_growth = true;
GPUBFCAllocator force_no_allow_growth_allocator(
GetParam()(1ull << 32), 1LL << 31, "GPU_3_bfc", opts);
EXPECT_EQ(GPUBFCAllocator::RoundedBytes(1LL << 31),
force_no_allow_growth_allocator.curr_region_allocation_bytes_);
}
};
TEST_P(GPUBFCAllocatorPrivateMethodsTest, BinDebugInfo) { TestBinDebugInfo(); }
TEST_P(GPUBFCAllocatorPrivateMethodsTest, ForceAllowGrowth) {
TestForceAllowGrowth();
}
INSTANTIATE_TEST_SUITE_P(GPUBFCAllocatorPrivateMethodTestSuite,
GPUBFCAllocatorPrivateMethodsTest, TestSuiteValues());
class GPUBFCAllocatorTest_SubAllocatorSpecific : public ::testing::Test {};
TEST_F(GPUBFCAllocatorTest_SubAllocatorSpecific,
PhysicalAllocatorOomsFragmentation) {
GPUBFCAllocator::Options options;
options.allow_growth = true;
constexpr size_t k512MiB = 512ull << 20;
GPUBFCAllocator a(CreateGPUMemAllocator( 0), k512MiB, "GPU_0_bfc",
options);
const size_t size = 1LL << 22;
std::vector<void*> initial_ptrs;
for (size_t s = 0; s < 128; s++) {
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
for (int i = 0; i < 127; ++i) {
a.DeallocateRaw(initial_ptrs[i]);
}
void* big_alloc = a.AllocateRaw(1, k512MiB - size);
EXPECT_EQ(big_alloc, nullptr);
}
class GPUBFCAllocatorPrivateMethodsTest_SubAllocatorSpecific
: public ::testing::Test {
protected:
void SetUp() override { CHECK_EQ(unsetenv("TF_FORCE_GPU_ALLOW_GROWTH"), 0); }
void TestRegionDeallocation() {
GPUBFCAllocator::Options options;
options.allow_growth = true;
GPUBFCAllocator a(CreateGPUMemAllocator( 0), 1LL << 31,
"GPU_0_bfc", options);
const size_t size = 1LL << 22;
std::vector<void*> initial_ptrs;
for (size_t s = 0; s < 128; s++) {
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
{
absl::MutexLock l(&a.mutex_);
EXPECT_LT(1, a.region_manager_.regions().size());
}
for (size_t i = 0; i < initial_ptrs.size() - 1; i++) {
a.DeallocateRaw(initial_ptrs[i]);
}
EXPECT_EQ(true, a.DeallocateFreeRegions(0));
{
absl::MutexLock l(&a.mutex_);
EXPECT_EQ(1, a.region_manager_.regions().size());
}
size_t num_chunks_in_bins = 0;
for (int i = 0; i < BFCAllocator::kNumBins; i++) {
BFCAllocator::Bin* bin = a.BinFromIndex(i);
num_chunks_in_bins += bin->free_chunks.size();
}
EXPECT_EQ(1, num_chunks_in_bins);
}
};
TEST_F(GPUBFCAllocatorPrivateMethodsTest_SubAllocatorSpecific,
TestRegionDeallocation) {
TestRegionDeallocation();
}
}
#endif | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
e116ea05-6142-4a01-912a-9c43073b8666 | cpp | tensorflow/tensorflow | slicing | third_party/xla/xla/hlo/builder/lib/slicing.cc | third_party/xla/xla/hlo/builder/lib/slicing_test.cc | #include "xla/hlo/builder/lib/slicing.h"
#include <algorithm>
#include <cstdint>
#include <functional>
#include <limits>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/hlo/builder/lib/arithmetic.h"
#include "xla/hlo/builder/lib/constants.h"
#include "xla/hlo/builder/xla_builder.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/statusor.h"
namespace xla {
XlaOp SliceInMinorDims(XlaOp x, absl::Span<const int64_t> start,
absl::Span<const int64_t> end) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_RET_CHECK(start.size() == end.size());
int64_t n_minor_dims = start.size();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = shape.dimensions().subspan(
0,
n_dims - n_minor_dims);
std::vector<int64_t> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + major_dims.size());
std::vector<int64_t> padded_end(n_dims);
std::copy(major_dims.begin(), major_dims.end(), padded_end.begin());
std::copy(end.begin(), end.end(), padded_end.begin() + major_dims.size());
std::vector<int64_t> strides(n_dims, 1);
return Slice(x, padded_start, padded_end, strides);
});
}
XlaOp UpdateSlice(XlaOp x, XlaOp update, absl::Span<const int64_t> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
const int64_t start_size = start.size();
TF_RET_CHECK(start_size == n_dims);
std::vector<int32_t> start_as_int32(start.begin(), start.end());
std::vector<XlaOp> start_ops(start.size());
for (int i = 0, end = start.size(); i < end; ++i) {
start_ops[i] = ConstantR0(builder, start_as_int32[i]);
}
return DynamicUpdateSlice(x, update, start_ops);
});
}
XlaOp UpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const int64_t> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
const int64_t n_minor_dims = start.size();
TF_RET_CHECK(n_minor_dims <= n_dims);
std::vector<int64_t> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + (n_dims - n_minor_dims));
return UpdateSlice(x, update, padded_start);
});
}
namespace {
std::vector<int64_t> ConcatVectors(absl::Span<const int64_t> xs,
absl::Span<const int64_t> ys) {
std::vector<int64_t> output(xs.size() + ys.size());
std::copy(xs.begin(), xs.end(), output.begin());
std::copy(ys.begin(), ys.end(), output.begin() + xs.size());
return output;
}
absl::StatusOr<std::vector<XlaOp>> PrependZerosInMajorDims(
XlaOp x, absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
auto zero = ConstantR0<int32_t>(builder, 0);
std::vector<XlaOp> padded_starts(n_dims, zero);
for (int i = 0; i < starts.size(); ++i) {
padded_starts[n_dims - starts.size() + i] = starts[i];
}
return padded_starts;
}
}
XlaOp DynamicSliceInMinorDims(XlaOp x, absl::Span<const XlaOp> starts,
absl::Span<const int64_t> sizes) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
int64_t n_minor_dims = starts.size();
TF_RET_CHECK(n_minor_dims == sizes.size());
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = shape.dimensions().subspan(
0,
n_dims - sizes.size());
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
auto padded_sizes = ConcatVectors(major_dims, sizes);
return DynamicSlice(x, padded_starts, padded_sizes);
});
}
XlaOp DynamicUpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
return DynamicUpdateSlice(x, update, padded_starts);
});
}
XlaOp TorchGather(XlaOp input, XlaOp index, int64_t dim, bool sparse) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
if (ShapeUtil::ElementHasBitWidth(index_shape, 64) &&
input_shape.dimensions(dim) < std::numeric_limits<uint32_t>::max()) {
index = ConvertElementType(index, U32);
index_shape.set_element_type(U32);
}
if (index_shape.rank() == 1) {
return TorchIndexSelect(input, index, 0);
}
if (!sparse) {
std::vector<int64_t> index_broadcast_dims;
std::vector<int64_t> input_broadcast_dims;
std::vector<int64_t> sizes;
sizes.reserve(index_shape.rank());
for (int64_t i = 0; i < index_shape.rank(); ++i) {
if (i < dim) {
input_broadcast_dims.push_back(i);
index_broadcast_dims.push_back(i);
} else if (i == dim) {
sizes.push_back(input_shape.dimensions(i));
input_broadcast_dims.push_back(i);
index_broadcast_dims.push_back(i + 1);
} else {
input_broadcast_dims.push_back(i + 1);
index_broadcast_dims.push_back(i + 1);
}
sizes.push_back(index_shape.dimensions(i));
}
auto mask = Eq(
BroadcastInDim(index, sizes, index_broadcast_dims),
Iota(builder, ShapeUtil::MakeShape(index_shape.element_type(), sizes),
dim));
auto masked_input = Select(
mask, BroadcastInDim(input, sizes, input_broadcast_dims),
Zeros(builder,
ShapeUtil::MakeShape(input_shape.element_type(), sizes)));
return Reduce(masked_input, Zero(builder, input_shape.element_type()),
CreateScalarIdentityWithZeroComputation(
input_shape.element_type(), builder),
{dim});
}
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
to_concat.reserve(input_shape.rank());
for (int64_t i = 0; i < input_shape.rank(); ++i) {
if (i == dim) {
to_concat.push_back(Reshape(index, index_shape.dimensions()));
} else {
to_concat.push_back(Iota(builder, index_shape, i));
}
}
XlaOp gather_indices = ConcatInDim(builder, to_concat, input_shape.rank());
std::vector<int64_t> slice_sizes(input_shape.rank(), 1);
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(input_shape.rank());
for (int64_t i = 0; i < input_shape.rank(); ++i) {
gather_dnums.add_collapsed_slice_dims(i);
gather_dnums.add_start_index_map(i);
}
return Gather(input, gather_indices, gather_dnums, slice_sizes);
});
}
XlaOp TorchScatterDense(XlaOp input, XlaOp index, XlaOp src, int64_t dim,
const std::function<XlaOp(XlaOp, XlaOp)>& combiner) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
std::vector<int64_t> index_broadcast_dims;
std::vector<int64_t> sizes;
const auto rank = index_shape.rank();
sizes.reserve(rank + 1);
for (int64_t i = 0; i < index_shape.rank(); ++i) {
if (i < dim) {
index_broadcast_dims.push_back(i);
} else {
if (i == dim) {
sizes.push_back(input_shape.dimensions(i));
}
index_broadcast_dims.push_back(i + 1);
}
sizes.push_back(index_shape.dimensions(i));
}
auto mask =
Eq(BroadcastInDim(index, sizes, index_broadcast_dims),
Iota(builder,
ShapeUtil::MakeShape(index_shape.element_type(), sizes), dim));
auto masked_src =
Select(mask, BroadcastInDim(src, sizes, index_broadcast_dims),
Zeros(builder,
ShapeUtil::MakeShape(input_shape.element_type(), sizes)));
return combiner(
input,
Reduce(masked_src, Zero(builder, input_shape.element_type()),
CreateScalarComputation("reducer", input_shape.element_type(),
builder, combiner),
{dim + 1}));
});
}
XlaOp TorchIndexSelect(XlaOp input, XlaOp index, int64_t dim,
int64_t batch_dims) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
if (dim < batch_dims) {
return InvalidArgument(
"Gather dim must be greater than or equal to the number of batch "
"dims");
}
if (ShapeUtil::ElementHasBitWidth(index_shape, 64) &&
input_shape.dimensions(dim) < std::numeric_limits<uint32_t>::max()) {
index = ConvertElementType(index, U32);
index_shape.set_element_type(U32);
}
std::vector<int64_t> slice_sizes = SpanToVector(input_shape.dimensions());
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(index_shape.rank());
if (batch_dims > 0) {
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
to_concat.reserve(batch_dims + 1);
xla::Shape iota_shape = xla::ShapeUtil::MakeStaticShape(index_shape);
for (int64_t batch_dim = 0; batch_dim < batch_dims; ++batch_dim) {
to_concat.push_back(Iota(builder, iota_shape, batch_dim));
}
to_concat.push_back(Reshape(index, index_shape.dimensions()));
index = ConcatInDim(builder, to_concat, gather_dnums.index_vector_dim());
}
for (int64_t i = 0; i < input_shape.rank(); ++i) {
if (i < batch_dims || i == dim) {
slice_sizes[i] = std::min<int64_t>(slice_sizes[i], 1);
gather_dnums.add_collapsed_slice_dims(i);
gather_dnums.add_start_index_map(i);
} else {
if (i < dim) {
gather_dnums.add_offset_dims(i);
} else {
gather_dnums.add_offset_dims(i + gather_dnums.index_vector_dim() -
(1 + batch_dims));
}
}
}
return Gather(input, index, gather_dnums, slice_sizes);
});
}
} | #include "xla/hlo/builder/lib/slicing.h"
#include "xla/array2d.h"
#include "xla/array3d.h"
#include "xla/error_spec.h"
#include "xla/hlo/builder/xla_builder.h"
#include "xla/literal.h"
#include "xla/shape_util.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
using SlicingTest = xla::ClientLibraryTestBase;
xla::Array2D<float> BValsRight() {
return {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
}
xla::Array2D<float> BValsLeft() {
return {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
}
xla::Array2D<float> AValsFull() {
return {{2, 0, 1, 2}, {3, 6, 0, 1}, {4, 7, 9, 0}, {5, 8, 10, 11}};
}
xla::Array3D<float> BatchedAValsFull() {
return {{
{2, 0, 1, 2},
{3, 6, 0, 1},
{4, 7, 9, 0},
{5, 8, 10, 11},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 456, 106},
{12, 48, 106, 62},
}};
}
XLA_TEST_F(SlicingTest, Simple2dLookup) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, x, y;
auto a_data = CreateR2Parameter<float>(BValsRight(), 0, "a", &builder, &a);
auto x_data = CreateR0Parameter<int>(2, 1, "x", &builder, &x);
auto y_data = CreateR0Parameter<int>(1, 2, "y", &builder, &y);
DynamicSliceInMinorDims(a, {x, y}, {1, 1});
ComputeAndCompareR2<float>(&builder, {{10}},
{a_data.get(), x_data.get(), y_data.get()},
xla::ErrorSpec(1e-2, 1e-2));
}
XLA_TEST_F(SlicingTest, Simple3dLookup) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, index;
auto a_data =
CreateR3Parameter<float>(BatchedAValsFull(), 0, "a", &builder, &a);
auto index_data = CreateR0Parameter<int>(1, 1, "index", &builder, &index);
DynamicSliceInMinorDims(a, {index, xla::ConstantR0<int32_t>(&builder, 0)},
{1, 4});
ComputeAndCompareR3<float>(&builder, {{{3, 6, 0, 1}}, {{24, 61, 82, 48}}},
{a_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, NestedLookup) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, index;
auto a_data =
CreateR3Parameter<float>(BatchedAValsFull(), 0, "a", &builder, &a);
auto index_data = CreateR0Parameter<int>(1, 1, "index", &builder, &index);
auto slice = DynamicSliceInMinorDims(
a, {index, xla::ConstantR0<int32_t>(&builder, 0)}, {1, 4});
DynamicSliceInMinorDims(slice, {xla::ConstantR0<int32_t>(&builder, 0), index},
{1, 1});
ComputeAndCompareR3<float>(&builder, {{{6}}, {{61}}},
{a_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, SimpleSliceUpdate) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, b, x, y;
auto a_data = CreateR2Parameter<float>(AValsFull(), 0, "a", &builder, &a);
auto b_data = CreateR2Parameter<float>({{9, 1, -10}}, 1, "b", &builder, &b);
auto x_data = CreateR0Parameter<int>(2, 2, "x", &builder, &x);
auto y_data = CreateR0Parameter<int>(1, 3, "y", &builder, &y);
DynamicUpdateSliceInMinorDims(a, b, {x, y});
xla::Array2D<float> expected(
{{{2, 0, 1, 2}, {3, 6, 0, 1}, {4, 9, 1, -10}, {5, 8, 10, 11}}});
ComputeAndCompareR2<float>(
&builder, expected,
{a_data.get(), b_data.get(), x_data.get(), y_data.get()});
}
XLA_TEST_F(SlicingTest, NestedSliceUpdate) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, b, x, y;
auto a_data = CreateR2Parameter<float>(AValsFull(), 0, "a", &builder, &a);
auto b_data = CreateR2Parameter<float>({{1, -10}}, 1, "b", &builder, &b);
auto x_data = CreateR0Parameter<int>(2, 2, "x", &builder, &x);
auto y_data = CreateR0Parameter<int>(1, 3, "y", &builder, &y);
auto z = xla::ConstantR0<int32_t>(&builder, 0);
auto slice = DynamicSliceInMinorDims(a, {x, z}, {1, 4});
auto inner = DynamicUpdateSliceInMinorDims(slice, b, {z, y});
DynamicUpdateSlice(a, inner, {x, z});
xla::Array2D<float> expected(
{{{2, 0, 1, 2}, {3, 6, 0, 1}, {4, 1, -10, 0}, {5, 8, 10, 11}}});
ComputeAndCompareR2<float>(
&builder, expected,
{a_data.get(), b_data.get(), x_data.get(), y_data.get()});
}
XLA_TEST_F(SlicingTest, TorchGatherSparse) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<int>({{1, 2}, {3, 4}}, 0, "input", &builder, &input);
auto index_data =
CreateR2Parameter<int>({{0, 0}, {1, 0}}, 1, "index", &builder, &index);
TorchGather(input, index, 1);
ComputeAndCompareR2<int>(&builder, {{1, 1}, {4, 3}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchGatherDense) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<int>({{1, 2}, {3, 4}}, 0, "input", &builder, &input);
auto index_data =
CreateR2Parameter<int>({{0, 0}, {1, 0}}, 1, "index", &builder, &index);
TorchGather(input, index, 1, false);
ComputeAndCompareR2<int>(&builder, {{1, 1}, {4, 3}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchScatterDense) {
xla::XlaBuilder builder(TestName());
xla::XlaOp src, index, input;
auto input_data = CreateR2Parameter<int>({{0, 0, 0}, {0, 0, 0}}, 0, "input",
&builder, &input);
auto index_data =
CreateR2Parameter<int>({{1, 0}, {1, 2}}, 1, "index", &builder, &index);
auto src_data =
CreateR2Parameter<int>({{1, 2}, {3, 4}}, 2, "src", &builder, &src);
TorchScatterDense(input, index, src, 1,
[](XlaOp l, XlaOp r) { return l + r; });
ComputeAndCompareR2<int>(
&builder, {{2, 1, 0}, {0, 3, 4}},
{input_data.get(), index_data.get(), src_data.get()});
}
XLA_TEST_F(SlicingTest, TorchIndexSelectOn0) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<float>({{0.1427, 0.0231, -0.5414, -1.0009},
{-0.4664, 0.2647, -0.1228, -1.1068},
{-1.1734, -0.6571, 0.7230, -0.6004}},
0, "input", &builder, &input);
auto index_data =
CreateR1Parameter<int>({0, 2}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 0);
ComputeAndCompareR2<float>(
&builder,
{{0.1427, 0.0231, -0.5414, -1.0009}, {-1.1734, -0.6571, 0.7230, -0.6004}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchIndexSelectOn0Size1) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data = CreateR2Parameter<float>(
{{-1.1734, -0.6571, 0.7230, -0.6004}}, 0, "input", &builder, &input);
auto index_data =
CreateR1Parameter<int>({0, 0, 0, 0, 0, 0}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 0);
ComputeAndCompareR2<float>(&builder,
{{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchIndexSelectOn1) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<float>({{0.1427, 0.0231, -0.5414, -1.0009},
{-0.4664, 0.2647, -0.1228, -1.1068},
{-1.1734, -0.6571, 0.7230, -0.6004}},
0, "input", &builder, &input);
auto index_data =
CreateR1Parameter<int>({0, 2}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 1);
ComputeAndCompareR2<float>(
&builder, {{0.1427, -0.5414}, {-0.4664, -0.1228}, {-1.1734, 0.7230}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, EmptyIndexSelect) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<float>({{0}, {0}, {0}}, 0, "input", &builder, &input);
auto index_data = CreateR1Parameter<int>({}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 1);
ComputeAndCompareR2<float>(&builder, {{}, {}, {}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, DoubleEmptyIndexSelect) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
Literal l(ShapeUtil::MakeShape(F32, {0, 1, 2, 0}));
Literal i(ShapeUtil::MakeShape(S32, {0}));
TF_ASSERT_OK_AND_ASSIGN(
auto input_data,
CreateParameterAndTransferLiteral(0, l, "input", &builder, &input));
TF_ASSERT_OK_AND_ASSIGN(
auto index_data,
CreateParameterAndTransferLiteral(1, i, "index", &builder, &index));
TorchIndexSelect(input, index, 0);
ComputeAndCompareLiteral(&builder, l, {input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, EmptyIndexSelectNonZero) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
Literal l(ShapeUtil::MakeShape(F32, {0, 2}));
TF_ASSERT_OK_AND_ASSIGN(
auto input_data,
CreateParameterAndTransferLiteral(0, l, "input", &builder, &input));
auto index_data =
CreateR1Parameter<int>({0, 0, 0}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 0);
ComputeAndCompareR2<float>(&builder,
{{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, BatchTorchIndexSelectOn0) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR3Parameter<int>({{{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}},
{{3, 2, 1, 0}, {7, 6, 5, 4}, {11, 10, 9, 8}}},
0, "input", &builder, &input);
auto index_data =
CreateR2Parameter<int>({{0, 2}, {1, 2}}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 1, 1);
ComputeAndCompareR3<int>(
&builder,
{{{0, 1, 2, 3}, {8, 9, 10, 11}}, {{7, 6, 5, 4}, {11, 10, 9, 8}}},
{input_data.get(), index_data.get()});
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/hlo/builder/lib/slicing.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/hlo/builder/lib/slicing_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
f12c6805-40c7-43da-a825-1cf3263758dd | cpp | tensorflow/tensorflow | select | tensorflow/lite/experimental/shlo/legacy/src/select.cc | tensorflow/lite/experimental/shlo/legacy/test/select_test.cc | #include <cstddef>
#include <type_traits>
#include "absl/status/status.h"
#include "tensorflow/lite/experimental/shlo/legacy/include/shlo.h"
#include "tensorflow/lite/experimental/shlo/legacy/src/dispatch.h"
#include "tensorflow/lite/experimental/shlo/legacy/src/storage.h"
#include "tensorflow/lite/experimental/shlo/legacy/src/util.h"
namespace stablehlo {
namespace {
template <typename Value>
absl::Status CheckParameters(const Tensor& pred, const Value& on_true,
const Value& on_false, Value& result) {
if (!(pred.rank() == 0 or pred.shape() == on_true.shape())) {
return absl::InvalidArgumentError(
"Constraint violation: rank(pred) = 0 or shape(pred) = "
"shape(on_true)");
} else if (!(on_true.baseline_type() == on_false.baseline_type() and
on_true.baseline_type() == result.baseline_type())) {
return absl::InvalidArgumentError(
"Constraint violation: baseline_type(on_true) = "
"baseline_type(on_false) = baseline_type(result)");
} else if (pred.element_type() != ElementType::kI1) {
return absl::InvalidArgumentError("Expected boolean tensor as predicate");
}
if constexpr (std::is_same_v<Value, QuantizedTensor>) {
if (!(on_true.is_per_tensor_quantized() and
on_false.is_per_tensor_quantized() and
result.is_per_tensor_quantized())) {
return absl::InvalidArgumentError("Expected per-tensor quantization");
}
}
if (pred.layout().has_strides() || on_true.layout().has_strides() ||
on_false.layout().has_strides() || result.layout().has_strides()) {
return absl::InvalidArgumentError("Stides not supported yet");
}
return absl::OkStatus();
}
template <ElementType storage_type, ElementType expressed_type, typename Value>
absl::Status Select(const Tensor& pred, const Value& on_true,
const Value& on_false, Value& result) {
if (auto check = CheckParameters(pred, on_true, on_false, result);
!check.ok()) {
return check;
}
using P = Storage<ElementType::kI1>;
using S = Storage<storage_type>;
const bool pred_is_tensor = (pred.rank() > 0);
const size_t n = result.num_elements();
auto pred_buffer = pred.buffer();
auto on_true_buffer = on_true.buffer();
auto on_false_buffer = on_false.buffer();
auto result_buffer = result.buffer();
if constexpr (std::is_same_v<Value, Tensor>) {
if (storage_type != result.element_type()) {
return absl::InvalidArgumentError("Unexpected tensor element type");
}
bool selection_value;
for (size_t i = 0; i < n; ++i) {
if (pred_is_tensor || (i == 0)) {
selection_value = P::Get(pred_buffer, i);
}
auto input_buffer = selection_value ? on_true_buffer : on_false_buffer;
auto result_value = S::Get(input_buffer, i);
S::Set(result_buffer, i, result_value);
}
} else {
static_assert(std::is_same_v<Value, QuantizedTensor>);
if (storage_type != result.storage_type()) {
return absl::InvalidArgumentError("Unexpected storage type");
} else if (expressed_type != result.expressed_type()) {
return absl::InvalidArgumentError("Unexpected expressed type");
}
using ET = typename Storage<expressed_type>::Type;
const QuantizedParameter& on_true_quant_param =
on_true.type().element_type().parameters(0);
const QuantizedParameter& on_false_quant_param =
on_false.type().element_type().parameters(0);
const QuantizedParameter& result_quant_param =
result.type().element_type().parameters(0);
ET result_scale_inv = ET(1.0) / static_cast<ET>(result_quant_param.scale);
bool selection_value;
for (size_t i = 0; i < n; ++i) {
if (pred_is_tensor || (i == 0)) {
selection_value = P::Get(pred_buffer, i);
}
const void* input_buffer;
const QuantizedParameter* input_quant_param;
if (selection_value) {
input_buffer = on_true_buffer;
input_quant_param = &on_true_quant_param;
} else {
input_buffer = on_false_buffer;
input_quant_param = &on_false_quant_param;
}
auto input_storage = S::Get(input_buffer, i);
auto result_storage =
DequantizeOpQuantizePartial<storage_type, expressed_type>(
input_storage, *input_quant_param, result_scale_inv,
result_quant_param.zero_point, [](auto x) { return x; });
S::Set(result_buffer, i, result_storage);
}
if (auto status = CompleteQuantization<storage_type>(result);
!status.ok()) {
return status;
}
}
return absl::OkStatus();
}
}
absl::Status Select(const Tensor& pred, const Tensor& on_true,
const Tensor& on_false, Tensor& result) {
DISPATCH_BOOL_INT_FLOAT(Select, result.element_type(), pred, on_true,
on_false, result);
}
absl::Status Select(const Tensor& pred, const QuantizedTensor& on_true,
const QuantizedTensor& on_false, QuantizedTensor& result) {
DISPATCH_QUANTIZED(Select, result.storage_type(), result.expressed_type(),
pred, on_true, on_false, result);
}
} | #include <initializer_list>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/experimental/shlo/legacy/include/shlo.h"
#include "tensorflow/lite/experimental/shlo/legacy/src/debug.h"
#include "tensorflow/lite/experimental/shlo/legacy/src/storage.h"
#include "tensorflow/lite/experimental/shlo/legacy/test/util.h"
namespace stablehlo {
namespace testing {
template <ElementType element_type>
void test(std::initializer_list<DimensionSize>&& shape,
std::vector<typename Storage<ElementType::kI1>::Type>&& pred_values,
std::vector<typename Storage<element_type>::Type>&& on_true_values,
std::vector<typename Storage<element_type>::Type>&& on_false_values,
std::vector<typename Storage<element_type>::Type>&& expected_values) {
Shape pred_shape = (pred_values.size() > 1) ? Shape(shape) : Shape();
Tensor pred(TensorType(std::move(pred_shape), ElementType::kI1),
pred_values.data());
Tensor on_true(TensorType(Shape(shape), element_type), on_true_values.data());
Tensor on_false(TensorType(Shape(shape), element_type),
on_false_values.data());
Tensor expected(TensorType(Shape(shape), element_type),
expected_values.data());
std::vector<typename Storage<element_type>::Type> result_values(
expected_values.size());
Tensor result(TensorType(Shape(shape), element_type), result_values.data());
ASSERT_OK(Select(pred, on_true, on_false, result));
EXPECT_EQ(result, expected) << "pred: " << pred << "\non_true: " << on_true
<< "\nnon_false: " << on_false;
}
template <ElementType storage_type, ElementType expressed_type>
void test(
QuantizedParameter&& quantized_parameter,
std::initializer_list<DimensionSize>&& shape,
std::vector<typename Storage<ElementType::kI1>::Type>&& pred_values,
std::vector<typename Storage<expressed_type>::Type>&& on_true_values,
std::vector<typename Storage<expressed_type>::Type>&& on_false_values,
std::vector<typename Storage<expressed_type>::Type>&& expected_values) {
Shape pred_shape = (pred_values.size() > 1) ? Shape(shape) : Shape();
Tensor pred(TensorType(std::move(pred_shape), ElementType::kI1),
pred_values.data());
auto on_true_quant_values = QuantizeVector<storage_type, expressed_type>(
on_true_values, quantized_parameter);
auto on_false_quant_values = QuantizeVector<storage_type, expressed_type>(
on_false_values, quantized_parameter);
auto expected_quant_values = QuantizeVector<storage_type, expressed_type>(
expected_values, quantized_parameter);
std::vector<typename Storage<storage_type>::Type> result_quant_values(
expected_quant_values.size());
QuantizedTensorElementType element_type(storage_type, expressed_type,
std::move(quantized_parameter));
QuantizedTensor on_true(
QuantizedTensorType(Shape(shape),
QuantizedTensorElementType(element_type)),
on_true_quant_values.data());
QuantizedTensor on_false(
QuantizedTensorType(Shape(shape),
QuantizedTensorElementType(element_type)),
on_false_quant_values.data());
QuantizedTensor expected(
QuantizedTensorType(Shape(shape),
QuantizedTensorElementType(element_type)),
expected_quant_values.data());
QuantizedTensor result(
QuantizedTensorType(Shape(shape),
QuantizedTensorElementType(element_type)),
result_quant_values.data());
ASSERT_OK(Select(pred, on_true, on_false, result));
EXPECT_EQ(result, expected) << "pred: " << pred << "\non_true: " << on_true
<< "\nnon_false: " << on_false;
}
TEST(Select, Unquantized) {
test<ElementType::kI1>({2}, {true}, {true, false}, {false, true},
{true, false});
test<ElementType::kSI8>({2}, {false}, {1, 2}, {-1, -2}, {-1, -2});
test<ElementType::kSI16>({2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kSI32>({2}, {false}, {1, 2}, {-1, -2}, {-1, -2});
test<ElementType::kBF16>({2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kF16>({2}, {false}, {1, 2}, {-1, -2}, {-1, -2});
test<ElementType::kF32>({2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kI1>({2}, {true, false}, {true, true}, {false, false},
{true, false});
test<ElementType::kSI8>({2}, {true, false}, {1, 2}, {-1, -2}, {1, -2});
test<ElementType::kSI16>({2}, {true, false}, {1, 2}, {-1, -2}, {1, -2});
test<ElementType::kSI32>({2}, {true, false}, {1, 2}, {-1, -2}, {1, -2});
test<ElementType::kBF16>({2}, {true, false}, {1, 2}, {-1, -2}, {1, -2});
test<ElementType::kF16>({2}, {true, false}, {1, 2}, {-1, -2}, {1, -2});
test<ElementType::kF32>({2}, {true, false}, {1, 2}, {-1, -2}, {1, -2});
}
TEST(Select, Quantized) {
test<ElementType::kSI8, ElementType::kBF16>(
{.scale = 0.1, .zero_point = 0}, {2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kSI8, ElementType::kF16>({.scale = 0.1, .zero_point = 0},
{2}, {false}, {1, 2}, {-1, -2},
{-1, -2});
test<ElementType::kSI8, ElementType::kF32>(
{.scale = 0.1, .zero_point = 0}, {2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kSI8, ElementType::kBF16>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI8, ElementType::kF16>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI8, ElementType::kF32>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI16, ElementType::kBF16>(
{.scale = 0.1, .zero_point = 0}, {2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kSI16, ElementType::kF16>({.scale = 0.1, .zero_point = 0},
{2}, {false}, {1, 2}, {-1, -2},
{-1, -2});
test<ElementType::kSI16, ElementType::kF32>(
{.scale = 0.1, .zero_point = 0}, {2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kSI16, ElementType::kBF16>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI16, ElementType::kF16>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI16, ElementType::kF32>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI32, ElementType::kBF16>(
{.scale = 0.1, .zero_point = 0}, {2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kSI32, ElementType::kF16>({.scale = 0.1, .zero_point = 0},
{2}, {false}, {1, 2}, {-1, -2},
{-1, -2});
test<ElementType::kSI32, ElementType::kF32>(
{.scale = 0.1, .zero_point = 0}, {2}, {true}, {1, 2}, {-1, -2}, {1, 2});
test<ElementType::kSI32, ElementType::kBF16>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI32, ElementType::kF16>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
test<ElementType::kSI32, ElementType::kF32>({.scale = 0.1, .zero_point = 0},
{2}, {true, false}, {1, 2},
{-1, -2}, {1, -2});
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/experimental/shlo/legacy/src/select.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/experimental/shlo/legacy/test/select_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
b291c2ed-7b74-4ed8-8198-339942ef74bb | cpp | google/cel-cpp | new | internal/new.cc | internal/new_test.cc | #include "internal/new.h"
#include <cstddef>
#include <cstdlib>
#include <new>
#include <utility>
#ifdef _MSC_VER
#include <malloc.h>
#endif
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#include "absl/log/absl_check.h"
#include "absl/numeric/bits.h"
#include "internal/align.h"
#if defined(__cpp_aligned_new) && __cpp_aligned_new >= 201606L
#define CEL_INTERNAL_HAVE_ALIGNED_NEW 1
#endif
#if defined(__cpp_sized_deallocation) && __cpp_sized_deallocation >= 201309L
#define CEL_INTERNAL_HAVE_SIZED_DELETE 1
#endif
namespace cel::internal {
namespace {
[[noreturn, maybe_unused]] void ThrowStdBadAlloc() {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::bad_alloc();
#else
std::abort();
#endif
}
}
void* New(size_t size) { return ::operator new(size); }
void* AlignedNew(size_t size, std::align_val_t alignment) {
ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment)));
#ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW
return ::operator new(size, alignment);
#else
if (static_cast<size_t>(alignment) <= kDefaultNewAlignment) {
return New(size);
}
#if defined(_MSC_VER)
void* ptr = _aligned_malloc(size, static_cast<size_t>(alignment));
if (ABSL_PREDICT_FALSE(size != 0 && ptr == nullptr)) {
ThrowStdBadAlloc();
}
return ptr;
#else
void* ptr = std::aligned_alloc(static_cast<size_t>(alignment), size);
if (ABSL_PREDICT_FALSE(size != 0 && ptr == nullptr)) {
ThrowStdBadAlloc();
}
return ptr;
#endif
#endif
}
std::pair<void*, size_t> SizeReturningNew(size_t size) {
return std::pair{::operator new(size), size};
}
std::pair<void*, size_t> SizeReturningAlignedNew(size_t size,
std::align_val_t alignment) {
ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment)));
#ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW
return std::pair{::operator new(size, alignment), size};
#else
return std::pair{AlignedNew(size, alignment), size};
#endif
}
void Delete(void* ptr) noexcept { ::operator delete(ptr); }
void SizedDelete(void* ptr, size_t size) noexcept {
#ifdef CEL_INTERNAL_HAVE_SIZED_DELETE
::operator delete(ptr, size);
#else
::operator delete(ptr);
#endif
}
void AlignedDelete(void* ptr, std::align_val_t alignment) noexcept {
ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment)));
#ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW
::operator delete(ptr, alignment);
#else
if (static_cast<size_t>(alignment) <= kDefaultNewAlignment) {
Delete(ptr, size);
} else {
#if defined(_MSC_VER)
_aligned_free(ptr);
#else
std::free(ptr);
#endif
}
#endif
}
void SizedAlignedDelete(void* ptr, size_t size,
std::align_val_t alignment) noexcept {
ABSL_DCHECK(absl::has_single_bit(static_cast<size_t>(alignment)));
#ifdef CEL_INTERNAL_HAVE_ALIGNED_NEW
#ifdef CEL_INTERNAL_HAVE_SIZED_DELETE
::operator delete(ptr, size, alignment);
#else
::operator delete(ptr, alignment);
#endif
#else
AlignedDelete(ptr, alignment);
#endif
}
} | #include "internal/new.h"
#include <cstddef>
#include <cstdint>
#include <new>
#include <tuple>
#include "internal/testing.h"
namespace cel::internal {
namespace {
using ::testing::Ge;
using ::testing::NotNull;
TEST(New, Basic) {
void* p = New(sizeof(uint64_t));
EXPECT_THAT(p, NotNull());
Delete(p);
}
TEST(AlignedNew, Basic) {
void* p =
AlignedNew(alignof(std::max_align_t) * 2,
static_cast<std::align_val_t>(alignof(std::max_align_t) * 2));
EXPECT_THAT(p, NotNull());
AlignedDelete(p,
static_cast<std::align_val_t>(alignof(std::max_align_t) * 2));
}
TEST(SizeReturningNew, Basic) {
void* p;
size_t n;
std::tie(p, n) = SizeReturningNew(sizeof(uint64_t));
EXPECT_THAT(p, NotNull());
EXPECT_THAT(n, Ge(sizeof(uint64_t)));
SizedDelete(p, n);
}
TEST(SizeReturningAlignedNew, Basic) {
void* p;
size_t n;
std::tie(p, n) = SizeReturningAlignedNew(
alignof(std::max_align_t) * 2,
static_cast<std::align_val_t>(alignof(std::max_align_t) * 2));
EXPECT_THAT(p, NotNull());
EXPECT_THAT(n, Ge(alignof(std::max_align_t) * 2));
SizedAlignedDelete(
p, n, static_cast<std::align_val_t>(alignof(std::max_align_t) * 2));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/new.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/internal/new_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
532dfe70-788a-4603-8e3b-05d98d46586b | cpp | google/arolla | derived_qtype_cast_operator | arolla/expr/derived_qtype_cast_operator.cc | arolla/expr/derived_qtype_cast_operator_test.cc | #include "arolla/expr/derived_qtype_cast_operator.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "absl/types/span.h"
#include "arolla/expr/basic_expr_operator.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/qtype/derived_qtype.h"
#include "arolla/qtype/qtype.h"
#include "arolla/util/fingerprint.h"
namespace arolla::expr {
absl::StatusOr<QTypePtr> DerivedQTypeUpcastOperator::GetOutputQType(
QTypePtr derived_qtype, QTypePtr value_qtype) {
if (value_qtype == derived_qtype) {
return DecayDerivedQType(derived_qtype);
}
return absl::InvalidArgumentError(
absl::StrFormat("expected %s, got value: %s", derived_qtype->name(),
value_qtype->name()));
}
DerivedQTypeUpcastOperator::DerivedQTypeUpcastOperator(QTypePtr derived_qtype)
: BasicExprOperator(
absl::StrFormat("derived_qtype.upcast[%s]", derived_qtype->name()),
ExprOperatorSignature{{"value"}},
"Casts a derived value to the base type.",
FingerprintHasher("arolla::expr::DerivedQTypeUpcastOperator")
.Combine(derived_qtype)
.Finish()),
derived_qtype_(derived_qtype) {}
absl::StatusOr<QTypePtr> DerivedQTypeUpcastOperator::GetOutputQType(
absl::Span<const QTypePtr> input_qtypes) const {
return DerivedQTypeUpcastOperator::GetOutputQType(derived_qtype_,
input_qtypes[0]);
}
QTypePtr DerivedQTypeUpcastOperator::derived_qtype() const {
return derived_qtype_;
}
absl::StatusOr<QTypePtr> DerivedQTypeDowncastOperator::GetOutputQType(
QTypePtr derived_qtype, QTypePtr value_qtype) {
const auto* base_qtype = DecayDerivedQType(derived_qtype);
if (value_qtype == base_qtype) {
return derived_qtype;
}
return absl::InvalidArgumentError(absl::StrFormat(
"expected %s, got value: %s", base_qtype->name(), value_qtype->name()));
}
DerivedQTypeDowncastOperator::DerivedQTypeDowncastOperator(
QTypePtr derived_qtype)
: BasicExprOperator(
absl::StrFormat("derived_qtype.downcast[%s]", derived_qtype->name()),
ExprOperatorSignature{{"value"}},
"Casts a base qtype value to the derived qtype.",
FingerprintHasher("arolla::expr::DerivedQTypeDowncastOperator")
.Combine(derived_qtype)
.Finish()),
derived_qtype_(derived_qtype) {}
absl::StatusOr<QTypePtr> DerivedQTypeDowncastOperator::GetOutputQType(
absl::Span<const QTypePtr> input_qtypes) const {
return DerivedQTypeDowncastOperator::GetOutputQType(derived_qtype_,
input_qtypes[0]);
}
QTypePtr DerivedQTypeDowncastOperator::derived_qtype() const {
return derived_qtype_;
}
} | #include "arolla/expr/derived_qtype_cast_operator.h"
#include <memory>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/no_destructor.h"
#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/testing/testing.h"
#include "arolla/qtype/base_types.h"
#include "arolla/qtype/derived_qtype.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/qtype/typed_value.h"
#include "arolla/util/repr.h"
#include "arolla/util/testing/repr_token_eq.h"
namespace arolla::expr {
namespace {
using ::absl_testing::StatusIs;
using ::arolla::testing::InvokeExprOperator;
using ::arolla::testing::ReprTokenEq;
using ::testing::HasSubstr;
struct TimeQType final : BasicDerivedQType {
TimeQType()
: BasicDerivedQType(ConstructorArgs{
.name = "TIME",
.base_qtype = GetQType<float>(),
}) {}
ReprToken UnsafeReprToken(const void* source) const override {
auto result = GetBaseQType()->UnsafeReprToken(source);
result.str += "s";
return result;
}
static QTypePtr get() {
static const absl::NoDestructor<TimeQType> result;
return result.get();
}
};
struct DistanceQType final : BasicDerivedQType {
DistanceQType()
: BasicDerivedQType(ConstructorArgs{
.name = "DISTANCE",
.base_qtype = GetQType<float>(),
}) {}
ReprToken UnsafeReprToken(const void* source) const override {
auto result = GetBaseQType()->UnsafeReprToken(source);
result.str += "m";
return result;
}
static QTypePtr get() {
static const absl::NoDestructor<DistanceQType> result;
return result.get();
}
};
TEST(DerivedQTypeCastOperatorTests, UpcastDistance_WithDistanceInput) {
ExprOperatorPtr upcast_distance =
std::make_shared<DerivedQTypeUpcastOperator>(DistanceQType::get());
ASSERT_OK_AND_ASSIGN(
auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get()));
ASSERT_OK_AND_ASSIGN(auto f32,
InvokeExprOperator<TypedValue>(upcast_distance, d));
EXPECT_EQ(f32.GetType(), GetQType<float>());
EXPECT_THAT(f32.GenReprToken(),
ReprTokenEq("6.28", ReprToken::kSafeForNegation));
}
TEST(DerivedQTypeCastOperatorTests, UpcastDistance_WithFloat32Input) {
ExprOperatorPtr upcast_distance =
std::make_shared<DerivedQTypeUpcastOperator>(DistanceQType::get());
EXPECT_THAT(InvokeExprOperator<TypedValue>(upcast_distance, 6.28f),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("expected DISTANCE, got value: FLOAT32")));
}
TEST(DerivedQTypeCastOperatorTests, UpcastFloat32_WithDistanceInput) {
ExprOperatorPtr upcast_float32 =
std::make_shared<DerivedQTypeUpcastOperator>(GetQType<float>());
ASSERT_OK_AND_ASSIGN(
auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get()));
EXPECT_THAT(InvokeExprOperator<TypedValue>(upcast_float32, d),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("expected FLOAT32, got value: DISTANCE")));
}
TEST(DerivedQTypeCastOperatorTests, UpcastFloat32_WithFloat32Input) {
ExprOperatorPtr upcast_float32 =
std::make_shared<DerivedQTypeUpcastOperator>(GetQType<float>());
ASSERT_OK_AND_ASSIGN(auto f32,
InvokeExprOperator<TypedValue>(upcast_float32, 6.28f));
EXPECT_EQ(f32.GetType(), GetQType<float>());
EXPECT_THAT(f32.GenReprToken(),
ReprTokenEq("6.28", ReprToken::kSafeForNegation));
}
TEST(DerivedQTypeCastOperatorTests, DowncastDistance_WithDistanceInput) {
ExprOperatorPtr downcast_distance =
std::make_shared<DerivedQTypeDowncastOperator>(DistanceQType::get());
ASSERT_OK_AND_ASSIGN(
auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get()));
EXPECT_THAT(InvokeExprOperator<TypedValue>(downcast_distance, d),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("expected FLOAT32, got value: DISTANCE")));
}
TEST(DerivedQTypeCastOperatorTests, DowncastDistance_WithFloat32Input) {
ExprOperatorPtr downcast_distance =
std::make_shared<DerivedQTypeDowncastOperator>(DistanceQType::get());
ASSERT_OK_AND_ASSIGN(
auto d, InvokeExprOperator<TypedValue>(downcast_distance, 6.28f));
EXPECT_EQ(d.GetType(), DistanceQType::get());
EXPECT_THAT(d.GenReprToken(),
ReprTokenEq("6.28m", ReprToken::kSafeForNegation));
}
TEST(DerivedQTypeCastOperatorTests, DowncastFloat32_WithDistanceInput) {
ExprOperatorPtr downcast_float32 =
std::make_shared<DerivedQTypeDowncastOperator>(GetQType<float>());
ASSERT_OK_AND_ASSIGN(
auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get()));
EXPECT_THAT(InvokeExprOperator<TypedValue>(downcast_float32, d),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("expected FLOAT32, got value: DISTANCE")));
}
TEST(DerivedQTypeCastOperatorTests, DowncastFloat32_WithFloat32Input) {
ExprOperatorPtr downcast_float32 =
std::make_shared<DerivedQTypeDowncastOperator>(GetQType<float>());
ASSERT_OK_AND_ASSIGN(auto f32,
InvokeExprOperator<TypedValue>(downcast_float32, 6.28f));
EXPECT_EQ(f32.GetType(), GetQType<float>());
EXPECT_THAT(f32.GenReprToken(),
ReprTokenEq("6.28", ReprToken::kSafeForNegation));
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/derived_qtype_cast_operator.cc | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/derived_qtype_cast_operator_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
4a4ecea8-5f00-46ff-b387-1843c5c83db4 | cpp | google/langsvr | buffer_reader | src/buffer_reader.cc | src/buffer_reader_test.cc | #include "langsvr/buffer_reader.h"
#include <cstring>
namespace langsvr {
BufferReader::~BufferReader() = default;
size_t BufferReader::Read(std::byte* out, size_t count) {
size_t n = std::min(count, bytes_remaining_);
memcpy(out, data_, n);
data_ += n;
bytes_remaining_ -= n;
return n;
}
} | #include "langsvr/buffer_reader.h"
#include "gtest/gtest.h"
namespace langsvr {
namespace {
template <typename... ARGS>
auto Data(ARGS&&... args) {
return std::vector{std::byte{static_cast<uint8_t>(args)}...};
}
TEST(BufferReaderTest, String) {
BufferReader reader{"hello world"};
auto first = reader.String(5);
ASSERT_EQ(first, Success);
EXPECT_EQ(first.Get(), "hello");
auto second = reader.String(6);
ASSERT_EQ(second, Success);
EXPECT_EQ(second.Get(), " world");
auto third = reader.String(1);
EXPECT_NE(third, Success);
}
}
} | https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/buffer_reader.cc | https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/buffer_reader_test.cc | 303c526231a90049a3e384549720f3fbd453cf66 |
e8ad88dc-6c07-443c-8df2-ecbfd02997c0 | cpp | tensorflow/tensorflow | register | tensorflow/lite/core/kernels/register.cc | tensorflow/lite/core/kernels/register_test.cc | #include "tensorflow/lite/core/kernels/register.h"
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/core/kernels/builtin_op_kernels.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/tflite_with_xnnpack_optional.h"
namespace tflite {
namespace ops {
namespace custom {
TfLiteRegistration* Register_NUMERIC_VERIFY();
TfLiteRegistration* Register_AUDIO_SPECTROGRAM();
TfLiteRegistration* Register_MFCC();
TfLiteRegistration* Register_DETECTION_POSTPROCESS();
}
namespace builtin {
BuiltinOpResolver::BuiltinOpResolver() {
AddBuiltin(BuiltinOperator_ABS, Register_ABS(), 1,
5);
AddBuiltin(BuiltinOperator_HARD_SWISH, Register_HARD_SWISH());
AddBuiltin(BuiltinOperator_RELU, Register_RELU(), 1,
3);
AddBuiltin(BuiltinOperator_RELU_N1_TO_1, Register_RELU_N1_TO_1());
AddBuiltin(BuiltinOperator_RELU_0_TO_1, Register_RELU_0_TO_1());
AddBuiltin(BuiltinOperator_RELU6, Register_RELU6(), 1,
3);
AddBuiltin(BuiltinOperator_TANH, Register_TANH(), 1,
3);
AddBuiltin(BuiltinOperator_LOGISTIC, Register_LOGISTIC(),
1,
3);
AddBuiltin(BuiltinOperator_AVERAGE_POOL_2D, Register_AVERAGE_POOL_2D(),
1,
3);
AddBuiltin(BuiltinOperator_MAX_POOL_2D, Register_MAX_POOL_2D(),
1,
3);
AddBuiltin(BuiltinOperator_L2_POOL_2D, Register_L2_POOL_2D());
AddBuiltin(BuiltinOperator_CONV_2D, Register_CONV_2D(),
1,
8);
AddBuiltin(BuiltinOperator_DEPTHWISE_CONV_2D, Register_DEPTHWISE_CONV_2D(),
1,
7);
AddBuiltin(BuiltinOperator_SVDF, Register_SVDF(),
1,
4);
AddBuiltin(BuiltinOperator_RNN, Register_RNN(),
1,
3);
AddBuiltin(BuiltinOperator_BIDIRECTIONAL_SEQUENCE_RNN,
Register_BIDIRECTIONAL_SEQUENCE_RNN(),
1,
3);
AddBuiltin(BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_RNN,
Register_UNIDIRECTIONAL_SEQUENCE_RNN(),
1,
3);
AddBuiltin(BuiltinOperator_EMBEDDING_LOOKUP, Register_EMBEDDING_LOOKUP(),
1,
4);
AddBuiltin(BuiltinOperator_EMBEDDING_LOOKUP_SPARSE,
Register_EMBEDDING_LOOKUP_SPARSE());
AddBuiltin(BuiltinOperator_FULLY_CONNECTED, Register_FULLY_CONNECTED(),
1,
13);
AddBuiltin(BuiltinOperator_LSH_PROJECTION, Register_LSH_PROJECTION());
AddBuiltin(BuiltinOperator_HASHTABLE_LOOKUP, Register_HASHTABLE_LOOKUP());
AddBuiltin(BuiltinOperator_SOFTMAX, Register_SOFTMAX(),
1,
3);
AddBuiltin(BuiltinOperator_CONCATENATION, Register_CONCATENATION(),
1,
4);
AddBuiltin(BuiltinOperator_ADD, Register_ADD(),
1,
5);
AddBuiltin(BuiltinOperator_SPACE_TO_BATCH_ND, Register_SPACE_TO_BATCH_ND(),
1,
4);
AddBuiltin(BuiltinOperator_BATCH_TO_SPACE_ND, Register_BATCH_TO_SPACE_ND(),
1,
4);
AddBuiltin(BuiltinOperator_MUL, Register_MUL(), 1,
7);
AddBuiltin(BuiltinOperator_L2_NORMALIZATION, Register_L2_NORMALIZATION(),
1,
2);
AddBuiltin(BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION,
Register_LOCAL_RESPONSE_NORMALIZATION());
AddBuiltin(BuiltinOperator_LSTM, Register_LSTM(), 1,
4);
AddBuiltin(BuiltinOperator_BIDIRECTIONAL_SEQUENCE_LSTM,
Register_BIDIRECTIONAL_SEQUENCE_LSTM(), 1,
3);
AddBuiltin(BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM,
Register_UNIDIRECTIONAL_SEQUENCE_LSTM(), 1,
4);
AddBuiltin(BuiltinOperator_PAD, Register_PAD(), 1,
4);
AddBuiltin(BuiltinOperator_PADV2, Register_PADV2(), 1,
4);
AddBuiltin(BuiltinOperator_RESHAPE, Register_RESHAPE());
AddBuiltin(BuiltinOperator_RESIZE_BILINEAR, Register_RESIZE_BILINEAR(),
1,
4);
AddBuiltin(BuiltinOperator_RESIZE_NEAREST_NEIGHBOR,
Register_RESIZE_NEAREST_NEIGHBOR(),
1,
4);
AddBuiltin(BuiltinOperator_SKIP_GRAM, Register_SKIP_GRAM());
AddBuiltin(BuiltinOperator_SPACE_TO_DEPTH, Register_SPACE_TO_DEPTH(),
1,
2);
AddBuiltin(BuiltinOperator_DEPTH_TO_SPACE, Register_DEPTH_TO_SPACE(),
1,
2);
AddBuiltin(BuiltinOperator_GATHER, Register_GATHER(),
1,
7);
AddBuiltin(BuiltinOperator_TRANSPOSE, Register_TRANSPOSE(),
1,
6);
AddBuiltin(BuiltinOperator_MEAN, Register_MEAN(),
1,
3);
AddBuiltin(BuiltinOperator_DIV, Register_DIV(),
1,
2);
AddBuiltin(BuiltinOperator_SUB, Register_SUB(),
1,
5);
AddBuiltin(BuiltinOperator_SPLIT, Register_SPLIT(),
1,
4);
AddBuiltin(BuiltinOperator_SPLIT_V, Register_SPLIT_V(),
1,
2);
AddBuiltin(BuiltinOperator_SQUEEZE, Register_SQUEEZE(),
1,
2);
AddBuiltin(BuiltinOperator_STRIDED_SLICE, Register_STRIDED_SLICE(),
1,
8);
AddBuiltin(BuiltinOperator_EXP, Register_EXP(),
1,
2);
AddBuiltin(BuiltinOperator_TOPK_V2, Register_TOPK_V2(),
1,
3);
AddBuiltin(BuiltinOperator_LOG, Register_LOG(),
1,
2);
AddBuiltin(BuiltinOperator_LOG_SOFTMAX, Register_LOG_SOFTMAX(),
1,
2);
AddBuiltin(BuiltinOperator_CAST, Register_CAST(),
1,
6);
AddBuiltin(BuiltinOperator_DEQUANTIZE, Register_DEQUANTIZE(),
1,
6);
AddBuiltin(BuiltinOperator_PRELU, Register_PRELU());
AddBuiltin(BuiltinOperator_MAXIMUM, Register_MAXIMUM(),
1,
4);
AddBuiltin(BuiltinOperator_MINIMUM, Register_MINIMUM(),
1,
4);
AddBuiltin(BuiltinOperator_ARG_MAX, Register_ARG_MAX(),
1,
3);
AddBuiltin(BuiltinOperator_ARG_MIN, Register_ARG_MIN(),
1,
3);
AddBuiltin(BuiltinOperator_GREATER, Register_GREATER(),
1,
2);
AddBuiltin(BuiltinOperator_GREATER_EQUAL, Register_GREATER_EQUAL(),
1,
3);
AddBuiltin(BuiltinOperator_LESS, Register_LESS(),
1,
3);
AddBuiltin(BuiltinOperator_LESS_EQUAL, Register_LESS_EQUAL(),
1,
2);
AddBuiltin(BuiltinOperator_FLOOR, Register_FLOOR());
AddBuiltin(BuiltinOperator_CEIL, Register_CEIL());
AddBuiltin(BuiltinOperator_ROUND, Register_ROUND());
AddBuiltin(BuiltinOperator_NEG, Register_NEG());
AddBuiltin(BuiltinOperator_SELECT, Register_SELECT(),
1,
4);
AddBuiltin(BuiltinOperator_SELECT_V2, Register_SELECT_V2(),
1,
2);
AddBuiltin(BuiltinOperator_SLICE, Register_SLICE(),
1,
6);
AddBuiltin(BuiltinOperator_SIN, Register_SIN());
AddBuiltin(BuiltinOperator_COS, Register_COS());
AddBuiltin(BuiltinOperator_TRANSPOSE_CONV, Register_TRANSPOSE_CONV(),
1,
5);
AddBuiltin(BuiltinOperator_TILE, Register_TILE(),
1,
3);
AddBuiltin(BuiltinOperator_SUM, Register_SUM(),
1,
2);
AddBuiltin(BuiltinOperator_REDUCE_PROD, Register_REDUCE_PROD(),
1,
2);
AddBuiltin(BuiltinOperator_REDUCE_MAX, Register_REDUCE_MAX(),
1,
3);
AddBuiltin(BuiltinOperator_REDUCE_MIN, Register_REDUCE_MIN(),
1,
3);
AddBuiltin(BuiltinOperator_REDUCE_ANY, Register_REDUCE_ANY());
AddBuiltin(BuiltinOperator_REDUCE_ALL, Register_REDUCE_ALL());
AddBuiltin(BuiltinOperator_EXPAND_DIMS, Register_EXPAND_DIMS());
AddBuiltin(BuiltinOperator_SPARSE_TO_DENSE, Register_SPARSE_TO_DENSE(),
1,
3);
AddBuiltin(BuiltinOperator_EQUAL, Register_EQUAL(),
1,
4);
AddBuiltin(BuiltinOperator_NOT_EQUAL, Register_NOT_EQUAL(),
1,
3);
AddBuiltin(BuiltinOperator_SQRT, Register_SQRT());
AddBuiltin(BuiltinOperator_RSQRT, Register_RSQRT(),
1,
3);
AddBuiltin(BuiltinOperator_SHAPE, Register_SHAPE());
AddBuiltin(BuiltinOperator_RANK, Register_RANK());
AddBuiltin(BuiltinOperator_POW, Register_POW());
AddBuiltin(BuiltinOperator_FAKE_QUANT, Register_FAKE_QUANT(), 1, 2);
AddBuiltin(BuiltinOperator_PACK, Register_PACK(),
1,
4);
AddBuiltin(BuiltinOperator_ONE_HOT, Register_ONE_HOT());
AddBuiltin(BuiltinOperator_LOGICAL_OR, Register_LOGICAL_OR());
AddBuiltin(BuiltinOperator_LOGICAL_AND, Register_LOGICAL_AND());
AddBuiltin(BuiltinOperator_LOGICAL_NOT, Register_LOGICAL_NOT());
AddBuiltin(BuiltinOperator_UNPACK, Register_UNPACK(),
1,
4);
AddBuiltin(BuiltinOperator_FLOOR_DIV, Register_FLOOR_DIV(),
1,
3);
AddBuiltin(BuiltinOperator_SQUARE, Register_SQUARE());
AddBuiltin(BuiltinOperator_ZEROS_LIKE, Register_ZEROS_LIKE());
AddBuiltin(BuiltinOperator_FLOOR_MOD, Register_FLOOR_MOD(),
1,
2);
AddBuiltin(BuiltinOperator_RANGE, Register_RANGE(),
1,
2);
AddBuiltin(BuiltinOperator_LEAKY_RELU, Register_LEAKY_RELU(),
1,
2);
AddBuiltin(BuiltinOperator_SQUARED_DIFFERENCE, Register_SQUARED_DIFFERENCE(),
1,
2);
AddBuiltin(BuiltinOperator_FILL, Register_FILL(),
1,
4);
AddBuiltin(BuiltinOperator_MIRROR_PAD, Register_MIRROR_PAD(),
1,
3);
AddBuiltin(BuiltinOperator_UNIQUE, Register_UNIQUE());
AddBuiltin(BuiltinOperator_REVERSE_V2, Register_REVERSE_V2(),
1,
3);
AddBuiltin(BuiltinOperator_ADD_N, Register_ADD_N());
AddBuiltin(BuiltinOperator_GATHER_ND, Register_GATHER_ND(),
1,
5);
AddBuiltin(BuiltinOperator_WHERE, Register_WHERE(),
1,
2);
AddBuiltin(BuiltinOperator_ELU, Register_ELU());
AddBuiltin(BuiltinOperator_REVERSE_SEQUENCE, Register_REVERSE_SEQUENCE());
AddBuiltin(BuiltinOperator_MATRIX_DIAG, Register_MATRIX_DIAG());
AddBuiltin(BuiltinOperator_QUANTIZE, Register_QUANTIZE(),
1,
3);
AddBuiltin(BuiltinOperator_MATRIX_SET_DIAG, Register_MATRIX_SET_DIAG());
AddBuiltin(BuiltinOperator_IF, tflite::ops::builtin::Register_IF());
AddBuiltin(BuiltinOperator_WHILE, tflite::ops::builtin::Register_WHILE());
AddBuiltin(BuiltinOperator_NON_MAX_SUPPRESSION_V4,
Register_NON_MAX_SUPPRESSION_V4());
AddBuiltin(BuiltinOperator_NON_MAX_SUPPRESSION_V5,
Register_NON_MAX_SUPPRESSION_V5());
AddBuiltin(BuiltinOperator_SCATTER_ND, Register_SCATTER_ND());
AddBuiltin(BuiltinOperator_DENSIFY, Register_DENSIFY());
AddBuiltin(BuiltinOperator_SEGMENT_SUM, Register_SEGMENT_SUM());
AddBuiltin(BuiltinOperator_BATCH_MATMUL, Register_BATCH_MATMUL(),
1,
4);
AddBuiltin(BuiltinOperator_CUMSUM, Register_CUMSUM());
AddBuiltin(BuiltinOperator_BROADCAST_TO, Register_BROADCAST_TO(),
2,
3);
AddBuiltin(BuiltinOperator_CALL_ONCE,
tflite::ops::builtin::Register_CALL_ONCE());
AddBuiltin(BuiltinOperator_RFFT2D, Register_RFFT2D());
AddBuiltin(BuiltinOperator_CONV_3D, Register_CONV_3D());
AddBuiltin(BuiltinOperator_IMAG, Register_IMAG());
AddBuiltin(BuiltinOperator_REAL, Register_REAL());
AddBuiltin(BuiltinOperator_COMPLEX_ABS, Register_COMPLEX_ABS());
AddBuiltin(BuiltinOperator_BROADCAST_ARGS, Register_BROADCAST_ARGS());
AddBuiltin(BuiltinOperator_HASHTABLE, Register_HASHTABLE());
AddBuiltin(BuiltinOperator_HASHTABLE_FIND, Register_HASHTABLE_FIND());
AddBuiltin(BuiltinOperator_HASHTABLE_IMPORT, Register_HASHTABLE_IMPORT());
AddBuiltin(BuiltinOperator_HASHTABLE_SIZE, Register_HASHTABLE_SIZE());
AddBuiltin(BuiltinOperator_CONV_3D_TRANSPOSE, Register_CONV_3D_TRANSPOSE());
AddBuiltin(BuiltinOperator_VAR_HANDLE, Register_VAR_HANDLE());
AddBuiltin(BuiltinOperator_READ_VARIABLE, Register_READ_VARIABLE());
AddBuiltin(BuiltinOperator_ASSIGN_VARIABLE, Register_ASSIGN_VARIABLE());
AddBuiltin(BuiltinOperator_MULTINOMIAL, Register_MULTINOMIAL());
AddBuiltin(BuiltinOperator_RANDOM_STANDARD_NORMAL,
Register_RANDOM_STANDARD_NORMAL());
AddBuiltin(BuiltinOperator_BUCKETIZE, Register_BUCKETIZE());
AddBuiltin(BuiltinOperator_RANDOM_UNIFORM, Register_RANDOM_UNIFORM());
AddBuiltin(BuiltinOperator_GELU, Register_GELU(),
1,
2);
AddBuiltin(BuiltinOperator_DYNAMIC_UPDATE_SLICE,
Register_DYNAMIC_UPDATE_SLICE(),
1,
2);
AddBuiltin(BuiltinOperator_UNSORTED_SEGMENT_PROD,
Register_UNSORTED_SEGMENT_PROD());
AddBuiltin(BuiltinOperator_UNSORTED_SEGMENT_MAX,
Register_UNSORTED_SEGMENT_MAX());
AddBuiltin(BuiltinOperator_UNSORTED_SEGMENT_MIN,
Register_UNSORTED_SEGMENT_MIN());
AddBuiltin(BuiltinOperator_UNSORTED_SEGMENT_SUM,
Register_UNSORTED_SEGMENT_SUM());
AddBuiltin(BuiltinOperator_ATAN2, Register_ATAN2());
AddBuiltin(BuiltinOperator_SIGN, Register_SIGN(),
1,
2);
AddBuiltin(BuiltinOperator_BITCAST, Register_BITCAST());
AddBuiltin(BuiltinOperator_BITWISE_XOR, Register_BITWISE_XOR());
AddBuiltin(BuiltinOperator_RIGHT_SHIFT, Register_RIGHT_SHIFT());
AddBuiltin(BuiltinOperator_STABLEHLO_SCATTER, Register_STABLEHLO_SCATTER());
AddBuiltin(BuiltinOperator_DILATE, Register_DILATE());
AddBuiltin(BuiltinOperator_STABLEHLO_RNG_BIT_GENERATOR,
Register_STABLEHLO_RNG_BIT_GENERATOR());
AddBuiltin(BuiltinOperator_REDUCE_WINDOW, Register_REDUCE_WINDOW());
AddBuiltin(BuiltinOperator_STABLEHLO_REDUCE_WINDOW,
Register_STABLEHLO_REDUCE_WINDOW());
AddBuiltin(BuiltinOperator_STABLEHLO_GATHER, Register_STABLEHLO_GATHER());
AddBuiltin(BuiltinOperator_STABLEHLO_ADD, Register_STABLEHLO_ADD());
AddBuiltin(BuiltinOperator_STABLEHLO_AND, Register_STABLEHLO_AND());
AddBuiltin(BuiltinOperator_STABLEHLO_MULTIPLY, Register_STABLEHLO_MULTIPLY());
AddBuiltin(BuiltinOperator_STABLEHLO_MAXIMUM, Register_STABLEHLO_MAXIMUM());
AddBuiltin(BuiltinOperator_STABLEHLO_MINIMUM, Register_STABLEHLO_MINIMUM());
AddBuiltin(BuiltinOperator_STABLEHLO_SHIFT_LEFT,
Register_STABLEHLO_SHIFT_LEFT());
AddBuiltin(BuiltinOperator_STABLEHLO_PAD, Register_STABLEHLO_PAD());
AddBuiltin(BuiltinOperator_STABLEHLO_COMPOSITE,
Register_STABLEHLO_COMPOSITE());
AddCustom("NumericVerify", tflite::ops::custom::Register_NUMERIC_VERIFY());
AddCustom("Mfcc", tflite::ops::custom::Register_MFCC());
AddCustom("AudioSpectrogram",
tflite::ops::custom::Register_AUDIO_SPECTROGRAM());
AddCustom("TFLite_Detection_PostProcess",
tflite::ops::custom::Register_DETECTION_POSTPROCESS());
may_directly_contain_user_defined_ops_ = false;
delegate_creators_.push_back([](TfLiteContext* context) {
return tflite::MaybeCreateXNNPACKDelegate(context,
XNNPackQS8Options::default_value);
});
}
BuiltinOpResolverWithXNNPACK::BuiltinOpResolverWithXNNPACK(
bool enable_xnnpack_unsigned_quantized) {
delegate_creators_.clear();
XNNPackQS8Options xnnpack_qs8_options = enable_xnnpack_unsigned_quantized
? XNNPackQS8Options::enabled
: XNNPackQS8Options::disabled;
delegate_creators_.push_back([xnnpack_qs8_options](TfLiteContext* context) {
return tflite::MaybeCreateXNNPACKDelegate(context, xnnpack_qs8_options);
});
}
}
}
} | #include "tensorflow/lite/core/kernels/register.h"
#include <memory>
#include <gtest/gtest.h>
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/mutable_op_resolver.h"
#include "tensorflow/lite/schema/schema_generated.h"
namespace tflite::ops::builtin {
namespace {
TEST(BuiltinOpResolverTest, SupportsAdd) {
BuiltinOpResolver builtin_op_resolver;
const TfLiteRegistration *add =
builtin_op_resolver.FindOp(::tflite::BuiltinOperator_ADD, 1);
ASSERT_NE(add, nullptr);
ASSERT_NE(add->init, nullptr);
ASSERT_NE(add->free, nullptr);
ASSERT_NE(add->prepare, nullptr);
ASSERT_NE(add->invoke, nullptr);
}
TEST(BuiltinOpResolverTest, CopySupportsAdd) {
BuiltinOpResolver builtin_op_resolver;
MutableOpResolver copy = builtin_op_resolver;
const TfLiteRegistration *add = copy.FindOp(::tflite::BuiltinOperator_ADD, 1);
ASSERT_NE(add, nullptr);
ASSERT_NE(add->init, nullptr);
ASSERT_NE(add->free, nullptr);
ASSERT_NE(add->prepare, nullptr);
ASSERT_NE(add->invoke, nullptr);
}
#if defined(TFLITE_WITHOUT_XNNPACK)
TEST(BuiltinOpResolverTest, HasXNNPACKDelegate_QS8) {
BuiltinOpResolver builtin_op_resolver;
ASSERT_EQ(builtin_op_resolver.GetDelegateCreators().size(), 1);
BuiltinOpResolver::TfLiteDelegateCreator delegate_creator =
builtin_op_resolver.GetDelegateCreators()[0];
std::unique_ptr<TfLiteDelegate, void (*)(TfLiteDelegate *)> delegate =
delegate_creator(nullptr);
const TfLiteXNNPackDelegateOptions *options =
TfLiteXNNPackDelegateGetOptions(delegate.get());
ASSERT_EQ(options->flags & TFLITE_XNNPACK_DELEGATE_FLAG_QU8,
TFLITE_XNNPACK_DELEGATE_FLAG_QU8);
ASSERT_EQ(options->flags & TFLITE_XNNPACK_DELEGATE_FLAG_QS8,
TFLITE_XNNPACK_DELEGATE_FLAG_QS8);
}
TEST(BuiltinOpResolverTest, HasXNNPACKDelegate_QS8_QU8) {
BuiltinOpResolver builtin_op_resolver;
ASSERT_EQ(builtin_op_resolver.GetDelegateCreators().size(), 1);
BuiltinOpResolver::TfLiteDelegateCreator delegate_creator =
builtin_op_resolver.GetDelegateCreators()[0];
std::unique_ptr<TfLiteDelegate, void (*)(TfLiteDelegate *)> delegate =
delegate_creator(nullptr);
const TfLiteXNNPackDelegateOptions *options =
TfLiteXNNPackDelegateGetOptions(delegate.get());
ASSERT_EQ(options->flags & TFLITE_XNNPACK_DELEGATE_FLAG_QU8,
TFLITE_XNNPACK_DELEGATE_FLAG_QU8);
ASSERT_EQ(options->flags & TFLITE_XNNPACK_DELEGATE_FLAG_QS8,
TFLITE_XNNPACK_DELEGATE_FLAG_QS8);
}
TEST(BuiltinOpResolverTest, Disable_QU8) {
BuiltinOpResolverWithXNNPACK builtin_op_resolver(false);
ASSERT_EQ(builtin_op_resolver.GetDelegateCreators().size(), 1);
BuiltinOpResolver::TfLiteDelegateCreator delegate_creator =
builtin_op_resolver.GetDelegateCreators()[0];
std::unique_ptr<TfLiteDelegate, void (*)(TfLiteDelegate *)> delegate =
delegate_creator(nullptr);
const TfLiteXNNPackDelegateOptions *options =
TfLiteXNNPackDelegateGetOptions(delegate.get());
ASSERT_EQ(options->flags & TFLITE_XNNPACK_DELEGATE_FLAG_QU8, 0);
ASSERT_EQ(options->flags & TFLITE_XNNPACK_DELEGATE_FLAG_QS8,
TFLITE_XNNPACK_DELEGATE_FLAG_QS8);
}
#endif
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/core/kernels/register.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/core/kernels/register_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
9ebf61e1-2594-4952-877e-18440a751526 | cpp | abseil/abseil-cpp | invoke | absl/base/internal/invoke.h | absl/base/invoke_test.cc | #ifndef ABSL_BASE_INTERNAL_INVOKE_H_
#define ABSL_BASE_INTERNAL_INVOKE_H_
#include "absl/base/config.h"
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L
#include <functional>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
using std::invoke;
using std::invoke_result_t;
using std::is_invocable_r;
}
ABSL_NAMESPACE_END
}
#else
#include <algorithm>
#include <type_traits>
#include <utility>
#include "absl/meta/type_traits.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
template <typename Derived>
struct StrippedAccept {
template <typename... Args>
struct Accept : Derived::template AcceptImpl<typename std::remove_cv<
typename std::remove_reference<Args>::type>::type...> {};
};
struct MemFunAndRef : StrippedAccept<MemFunAndRef> {
template <typename... Args>
struct AcceptImpl : std::false_type {};
template <typename MemFunType, typename C, typename Obj, typename... Args>
struct AcceptImpl<MemFunType C::*, Obj, Args...>
: std::integral_constant<bool, std::is_base_of<C, Obj>::value &&
absl::is_function<MemFunType>::value> {
};
template <typename MemFun, typename Obj, typename... Args>
static decltype((std::declval<Obj>().*
std::declval<MemFun>())(std::declval<Args>()...))
Invoke(MemFun&& mem_fun, Obj&& obj, Args&&... args) {
#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(11, 0)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
return (std::forward<Obj>(obj).*
std::forward<MemFun>(mem_fun))(std::forward<Args>(args)...);
#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(11, 0)
#pragma GCC diagnostic pop
#endif
}
};
struct MemFunAndPtr : StrippedAccept<MemFunAndPtr> {
template <typename... Args>
struct AcceptImpl : std::false_type {};
template <typename MemFunType, typename C, typename Ptr, typename... Args>
struct AcceptImpl<MemFunType C::*, Ptr, Args...>
: std::integral_constant<bool, !std::is_base_of<C, Ptr>::value &&
absl::is_function<MemFunType>::value> {
};
template <typename MemFun, typename Ptr, typename... Args>
static decltype(((*std::declval<Ptr>()).*
std::declval<MemFun>())(std::declval<Args>()...))
Invoke(MemFun&& mem_fun, Ptr&& ptr, Args&&... args) {
return ((*std::forward<Ptr>(ptr)).*
std::forward<MemFun>(mem_fun))(std::forward<Args>(args)...);
}
};
struct DataMemAndRef : StrippedAccept<DataMemAndRef> {
template <typename... Args>
struct AcceptImpl : std::false_type {};
template <typename R, typename C, typename Obj>
struct AcceptImpl<R C::*, Obj>
: std::integral_constant<bool, std::is_base_of<C, Obj>::value &&
!absl::is_function<R>::value> {};
template <typename DataMem, typename Ref>
static decltype(std::declval<Ref>().*std::declval<DataMem>()) Invoke(
DataMem&& data_mem, Ref&& ref) {
return std::forward<Ref>(ref).*std::forward<DataMem>(data_mem);
}
};
struct DataMemAndPtr : StrippedAccept<DataMemAndPtr> {
template <typename... Args>
struct AcceptImpl : std::false_type {};
template <typename R, typename C, typename Ptr>
struct AcceptImpl<R C::*, Ptr>
: std::integral_constant<bool, !std::is_base_of<C, Ptr>::value &&
!absl::is_function<R>::value> {};
template <typename DataMem, typename Ptr>
static decltype((*std::declval<Ptr>()).*std::declval<DataMem>()) Invoke(
DataMem&& data_mem, Ptr&& ptr) {
return (*std::forward<Ptr>(ptr)).*std::forward<DataMem>(data_mem);
}
};
struct Callable {
template <typename F, typename... Args>
static decltype(std::declval<F>()(std::declval<Args>()...)) Invoke(
F&& f, Args&&... args) {
return std::forward<F>(f)(std::forward<Args>(args)...);
}
};
template <typename... Args>
struct Invoker {
typedef typename std::conditional<
MemFunAndRef::Accept<Args...>::value, MemFunAndRef,
typename std::conditional<
MemFunAndPtr::Accept<Args...>::value, MemFunAndPtr,
typename std::conditional<
DataMemAndRef::Accept<Args...>::value, DataMemAndRef,
typename std::conditional<DataMemAndPtr::Accept<Args...>::value,
DataMemAndPtr, Callable>::type>::type>::
type>::type type;
};
template <typename F, typename... Args>
using invoke_result_t = decltype(Invoker<F, Args...>::type::Invoke(
std::declval<F>(), std::declval<Args>()...));
template <typename F, typename... Args>
invoke_result_t<F, Args...> invoke(F&& f, Args&&... args) {
return Invoker<F, Args...>::type::Invoke(std::forward<F>(f),
std::forward<Args>(args)...);
}
template <typename AlwaysVoid, typename, typename, typename...>
struct IsInvocableRImpl : std::false_type {};
template <typename R, typename F, typename... Args>
struct IsInvocableRImpl<
absl::void_t<absl::base_internal::invoke_result_t<F, Args...> >, R, F,
Args...>
: std::integral_constant<
bool,
std::is_convertible<absl::base_internal::invoke_result_t<F, Args...>,
R>::value ||
std::is_void<R>::value> {};
template <typename R, typename F, typename... Args>
using is_invocable_r = IsInvocableRImpl<void, R, F, Args...>;
}
ABSL_NAMESPACE_END
}
#endif
#endif | #include "absl/base/internal/invoke.h"
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
int Function(int a, int b) { return a - b; }
void VoidFunction(int& a, int& b) {
a += b;
b = a - b;
a -= b;
}
int ZeroArgFunction() { return -1937; }
int Sink(std::unique_ptr<int> p) {
return *p;
}
std::unique_ptr<int> Factory(int n) {
return make_unique<int>(n);
}
void NoOp() {}
struct ConstFunctor {
int operator()(int a, int b) const { return a - b; }
};
struct MutableFunctor {
int operator()(int a, int b) { return a - b; }
};
struct EphemeralFunctor {
int operator()(int a, int b) && { return a - b; }
};
struct OverloadedFunctor {
template <typename... Args>
std::string operator()(const Args&... args) & {
return StrCat("&", args...);
}
template <typename... Args>
std::string operator()(const Args&... args) const& {
return StrCat("const&", args...);
}
template <typename... Args>
std::string operator()(const Args&... args) && {
return StrCat("&&", args...);
}
};
struct Class {
int Method(int a, int b) { return a - b; }
int ConstMethod(int a, int b) const { return a - b; }
int RefMethod(int a, int b) & { return a - b; }
int RefRefMethod(int a, int b) && { return a - b; }
int NoExceptMethod(int a, int b) noexcept { return a - b; }
int VolatileMethod(int a, int b) volatile { return a - b; }
int member;
};
struct FlipFlop {
int ConstMethod() const { return member; }
FlipFlop operator*() const { return {-member}; }
int member;
};
template <typename F>
decltype(base_internal::invoke(std::declval<const F&>())) CallMaybeWithArg(
const F& f) {
return base_internal::invoke(f);
}
template <typename F>
decltype(base_internal::invoke(std::declval<const F&>(), 42)) CallMaybeWithArg(
const F& f) {
return base_internal::invoke(f, 42);
}
TEST(InvokeTest, Function) {
EXPECT_EQ(1, base_internal::invoke(Function, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Function, 3, 2));
}
TEST(InvokeTest, NonCopyableArgument) {
EXPECT_EQ(42, base_internal::invoke(Sink, make_unique<int>(42)));
}
TEST(InvokeTest, NonCopyableResult) {
EXPECT_THAT(base_internal::invoke(Factory, 42), ::testing::Pointee(42));
}
TEST(InvokeTest, VoidResult) { base_internal::invoke(NoOp); }
TEST(InvokeTest, ConstFunctor) {
EXPECT_EQ(1, base_internal::invoke(ConstFunctor(), 3, 2));
}
TEST(InvokeTest, MutableFunctor) {
MutableFunctor f;
EXPECT_EQ(1, base_internal::invoke(f, 3, 2));
EXPECT_EQ(1, base_internal::invoke(MutableFunctor(), 3, 2));
}
TEST(InvokeTest, EphemeralFunctor) {
EphemeralFunctor f;
EXPECT_EQ(1, base_internal::invoke(std::move(f), 3, 2));
EXPECT_EQ(1, base_internal::invoke(EphemeralFunctor(), 3, 2));
}
TEST(InvokeTest, OverloadedFunctor) {
OverloadedFunctor f;
const OverloadedFunctor& cf = f;
EXPECT_EQ("&", base_internal::invoke(f));
EXPECT_EQ("& 42", base_internal::invoke(f, " 42"));
EXPECT_EQ("const&", base_internal::invoke(cf));
EXPECT_EQ("const& 42", base_internal::invoke(cf, " 42"));
EXPECT_EQ("&&", base_internal::invoke(std::move(f)));
OverloadedFunctor f2;
EXPECT_EQ("&& 42", base_internal::invoke(std::move(f2), " 42"));
}
TEST(InvokeTest, ReferenceWrapper) {
ConstFunctor cf;
MutableFunctor mf;
EXPECT_EQ(1, base_internal::invoke(std::cref(cf), 3, 2));
EXPECT_EQ(1, base_internal::invoke(std::ref(cf), 3, 2));
EXPECT_EQ(1, base_internal::invoke(std::ref(mf), 3, 2));
}
TEST(InvokeTest, MemberFunction) {
std::unique_ptr<Class> p(new Class);
std::unique_ptr<const Class> cp(new Class);
std::unique_ptr<volatile Class> vp(new Class);
EXPECT_EQ(1, base_internal::invoke(&Class::Method, p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::Method, p.get(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::Method, *p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::RefMethod, p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::RefMethod, p.get(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::RefMethod, *p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::RefRefMethod, std::move(*p), 3,
2));
EXPECT_EQ(1, base_internal::invoke(&Class::NoExceptMethod, p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::NoExceptMethod, p.get(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::NoExceptMethod, *p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, p.get(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, *p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, cp, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, cp.get(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, *cp, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, p.get(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, *p, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, vp, 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, vp.get(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, *vp, 3, 2));
EXPECT_EQ(1,
base_internal::invoke(&Class::Method, make_unique<Class>(), 3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, make_unique<Class>(),
3, 2));
EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod,
make_unique<const Class>(), 3, 2));
}
TEST(InvokeTest, DataMember) {
std::unique_ptr<Class> p(new Class{42});
std::unique_ptr<const Class> cp(new Class{42});
EXPECT_EQ(42, base_internal::invoke(&Class::member, p));
EXPECT_EQ(42, base_internal::invoke(&Class::member, *p));
EXPECT_EQ(42, base_internal::invoke(&Class::member, p.get()));
base_internal::invoke(&Class::member, p) = 42;
base_internal::invoke(&Class::member, p.get()) = 42;
EXPECT_EQ(42, base_internal::invoke(&Class::member, cp));
EXPECT_EQ(42, base_internal::invoke(&Class::member, *cp));
EXPECT_EQ(42, base_internal::invoke(&Class::member, cp.get()));
}
TEST(InvokeTest, FlipFlop) {
FlipFlop obj = {42};
EXPECT_EQ(42, base_internal::invoke(&FlipFlop::ConstMethod, obj));
EXPECT_EQ(42, base_internal::invoke(&FlipFlop::member, obj));
}
TEST(InvokeTest, SfinaeFriendly) {
CallMaybeWithArg(NoOp);
EXPECT_THAT(CallMaybeWithArg(Factory), ::testing::Pointee(42));
}
TEST(IsInvocableRTest, CallableExactMatch) {
static_assert(
base_internal::is_invocable_r<int, decltype(Function), int, int>::value,
"Should be true for exact match of types on a free function");
}
TEST(IsInvocableRTest, CallableArgumentConversionMatch) {
static_assert(
base_internal::is_invocable_r<int, decltype(Function), char, int>::value,
"Should be true for convertible argument type");
}
TEST(IsInvocableRTest, CallableReturnConversionMatch) {
static_assert(base_internal::is_invocable_r<double, decltype(Function), int,
int>::value,
"Should be true for convertible return type");
}
TEST(IsInvocableRTest, CallableReturnVoid) {
static_assert(base_internal::is_invocable_r<void, decltype(VoidFunction),
int&, int&>::value,
"Should be true for void expected and actual return types");
static_assert(
base_internal::is_invocable_r<void, decltype(Function), int, int>::value,
"Should be true for void expected and non-void actual return types");
}
TEST(IsInvocableRTest, CallableRefQualifierMismatch) {
static_assert(!base_internal::is_invocable_r<void, decltype(VoidFunction),
int&, const int&>::value,
"Should be false for reference constness mismatch");
static_assert(!base_internal::is_invocable_r<void, decltype(VoidFunction),
int&&, int&>::value,
"Should be false for reference value category mismatch");
}
TEST(IsInvocableRTest, CallableArgumentTypeMismatch) {
static_assert(!base_internal::is_invocable_r<int, decltype(Function),
std::string, int>::value,
"Should be false for argument type mismatch");
}
TEST(IsInvocableRTest, CallableReturnTypeMismatch) {
static_assert(!base_internal::is_invocable_r<std::string, decltype(Function),
int, int>::value,
"Should be false for return type mismatch");
}
TEST(IsInvocableRTest, CallableTooFewArgs) {
static_assert(
!base_internal::is_invocable_r<int, decltype(Function), int>::value,
"Should be false for too few arguments");
}
TEST(IsInvocableRTest, CallableTooManyArgs) {
static_assert(!base_internal::is_invocable_r<int, decltype(Function), int,
int, int>::value,
"Should be false for too many arguments");
}
TEST(IsInvocableRTest, MemberFunctionAndReference) {
static_assert(base_internal::is_invocable_r<int, decltype(&Class::Method),
Class&, int, int>::value,
"Should be true for exact match of types on a member function "
"and class reference");
}
TEST(IsInvocableRTest, MemberFunctionAndPointer) {
static_assert(base_internal::is_invocable_r<int, decltype(&Class::Method),
Class*, int, int>::value,
"Should be true for exact match of types on a member function "
"and class pointer");
}
TEST(IsInvocableRTest, DataMemberAndReference) {
static_assert(base_internal::is_invocable_r<int, decltype(&Class::member),
Class&>::value,
"Should be true for exact match of types on a data member and "
"class reference");
}
TEST(IsInvocableRTest, DataMemberAndPointer) {
static_assert(base_internal::is_invocable_r<int, decltype(&Class::member),
Class*>::value,
"Should be true for exact match of types on a data member and "
"class pointer");
}
TEST(IsInvocableRTest, CallableZeroArgs) {
static_assert(
base_internal::is_invocable_r<int, decltype(ZeroArgFunction)>::value,
"Should be true for exact match for a zero-arg free function");
}
}
}
ABSL_NAMESPACE_END
} | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/invoke.h | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/invoke_test.cc | 03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4 |
2292926a-6678-41a1-8dd4-0c5f8f61af9c | cpp | tensorflow/tensorflow | collective_permute_decomposer | third_party/xla/xla/service/collective_permute_decomposer.cc | third_party/xla/xla/service/collective_permute_decomposer_test.cc | #include "xla/service/collective_permute_decomposer.h"
#include <cstdint>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.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/service/collective_ops_utils.h"
#include "xla/service/gpu/backend_configs.pb.h"
#include "xla/service/graphcycles/graphcycles.h"
#include "xla/shape_util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
namespace xla {
namespace {
using SourceTargetPair = std::pair<int64_t, int64_t>;
using SourceTargetPairs = std::vector<SourceTargetPair>;
bool HasCycles(const SourceTargetPairs& pairs) {
GraphCycles graph;
absl::flat_hash_map<int64_t, int32_t> replica_to_node_id;
auto get_node_id = [&](int64_t replica) {
auto it_and_inserted = replica_to_node_id.emplace(replica, -1);
auto it = it_and_inserted.first;
auto inserted = it_and_inserted.second;
if (inserted) {
it->second = graph.NewNode();
}
return it->second;
};
for (auto pair : pairs) {
auto source = get_node_id(pair.first);
auto target = get_node_id(pair.second);
VLOG(3) << "See source " << source << " -> target " << target;
if (!graph.InsertEdge(source, target)) {
VLOG(3) << "Detected cycles";
return true;
}
}
return false;
}
bool ShouldDecompose(const HloCollectivePermuteInstruction& collective_permute,
int64_t threshold_in_bytes) {
if (!collective_permute.channel_id().has_value()) {
return false;
}
const Shape& result_shape = collective_permute.shape();
if (!result_shape.IsArray()) {
return false;
}
if (ShapeUtil::ByteSizeOf(result_shape) < threshold_in_bytes) {
return false;
}
return !HasCycles(collective_permute.source_target_pairs());
}
bool MayPipeline(const HloCollectivePermuteInstruction& collective_permute) {
const HloInstruction* data = collective_permute.operand(0);
return (data->opcode() == HloOpcode::kGetTupleElement &&
data->operand(0)->opcode() == HloOpcode::kParameter);
}
absl::Status DecomposeCollectivePermute(
HloCollectivePermuteInstruction* collective_permute,
HloComputation* computation, const std::string& pipeline_decision) {
int64_t channel_id = collective_permute->channel_id().value();
HloInstruction* data = collective_permute->mutable_operand(0);
const Shape& data_shape = data->shape();
const OpMetadata& metadata = collective_permute->metadata();
const xla::FrontendAttributes& old_attributes =
collective_permute->frontend_attributes();
xla::FrontendAttributes attributes;
std::string source_target_pairs_string =
"{" +
absl::StrJoin(collective_permute->source_target_pairs(), ",",
absl::PairFormatter(
[](std::string* out, int64_t value) {
absl::StrAppend(out, "{", value);
},
",",
[](std::string* out, int64_t value) {
absl::StrAppend(out, value, "}");
})) +
"}";
attributes.mutable_map()->insert(old_attributes.map().begin(),
old_attributes.map().end());
(*attributes.mutable_map())[kSendRecvSourceTargetPairsAttr] =
source_target_pairs_string;
HloInstruction* after_all =
computation->AddInstruction(HloInstruction::CreateToken());
HloInstruction* recv = computation->AddInstruction(
HloInstruction::CreateRecv(data_shape, after_all, channel_id));
recv->add_frontend_attributes(attributes);
recv->set_metadata(metadata);
HloInstruction* send = computation->AddInstruction(
HloInstruction::CreateSend(data, after_all, channel_id));
send->add_frontend_attributes(attributes);
send->set_metadata(metadata);
HloInstruction* recv_done =
computation->AddInstruction(HloInstruction::CreateRecvDone(recv));
HloInstruction* send_done =
computation->AddInstruction(HloInstruction::CreateSendDone(send));
TF_RETURN_IF_ERROR(send->AddControlDependencyTo(recv_done));
HloInstruction* recv_data = computation->AddInstruction(
HloInstruction::CreateGetTupleElement(recv_done, 0));
TF_RETURN_IF_ERROR(collective_permute->ReplaceAllUsesWith(recv_data));
TF_RETURN_IF_ERROR(
computation->RemoveInstructionAndUnusedOperands(collective_permute));
if (!pipeline_decision.empty()) {
xla::FrontendAttributes attributes;
(*attributes.mutable_map())[kSendRecvPipelineAttr] = pipeline_decision;
send->add_frontend_attributes(attributes);
send_done->add_frontend_attributes(attributes);
recv->add_frontend_attributes(attributes);
recv_done->add_frontend_attributes(attributes);
}
return absl::OkStatus();
}
bool IsForwardCycle(const SourceTargetPair& backedge,
const SourceTargetPairs& others) {
int64_t num_pairs = others.size() + 1;
if (backedge.first != num_pairs - 1 || backedge.second != 0) {
return false;
}
for (int64_t i = 0; i < num_pairs - 1; ++i) {
const SourceTargetPair& pair = others[i];
if (pair.first != i || pair.second != i + 1) {
return false;
}
}
return true;
}
bool IsBackwardCycle(const SourceTargetPair& backedge,
const SourceTargetPairs& others) {
int64_t num_pairs = others.size() + 1;
if (backedge.first != 0 || backedge.second != num_pairs - 1) {
return false;
}
for (int64_t i = 0; i < num_pairs - 1; ++i) {
const SourceTargetPair& pair = others[i];
if (pair.first != i + 1 || pair.second != i) {
return false;
}
}
return true;
}
std::optional<std::pair<HloCollectivePermuteInstruction*,
HloCollectivePermuteInstruction*>>
CheckCyclePatterns(HloCollectivePermuteInstruction* cp0,
HloCollectivePermuteInstruction* cp1) {
const SourceTargetPairs& cp0_pairs = cp0->source_target_pairs();
const SourceTargetPairs& cp1_pairs = cp1->source_target_pairs();
if (cp0_pairs.size() == 1) {
if (IsForwardCycle(cp0_pairs.front(), cp1_pairs) ||
IsBackwardCycle(cp0_pairs.front(), cp1_pairs)) {
return std::make_pair(cp0, cp1);
}
}
if (cp1_pairs.size() == 1) {
if (IsForwardCycle(cp1_pairs.front(), cp0_pairs) ||
IsBackwardCycle(cp1_pairs.front(), cp0_pairs)) {
return std::make_pair(cp1, cp0);
}
}
return std::nullopt;
}
}
absl::StatusOr<bool> CollectivePermuteDecomposer::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
bool changed = false;
std::vector<HloComputation*> all_computations =
module->MakeComputationPostOrder(execution_threads);
absl::flat_hash_set<HloComputation*> while_bodies;
for (auto iter = all_computations.rbegin(); iter != all_computations.rend();
++iter) {
HloComputation* computation = *iter;
bool may_pipeline = while_bodies.contains(computation);
std::vector<HloCollectivePermuteInstruction*> cps_to_decompose;
HloCollectivePermuteInstruction* cp0_to_pipeline = nullptr;
HloCollectivePermuteInstruction* cp1_to_pipeline = nullptr;
for (HloInstruction* hlo : computation->MakeInstructionPostOrder()) {
if (hlo->opcode() == HloOpcode::kWhile) {
while_bodies.insert(hlo->while_body());
continue;
}
if (hlo->opcode() != HloOpcode::kCollectivePermute) {
continue;
}
HloCollectivePermuteInstruction* cp =
Cast<HloCollectivePermuteInstruction>(hlo);
if (!ShouldDecompose(*cp, threshold_in_bytes_)) {
continue;
}
cps_to_decompose.push_back(cp);
if (!while_bodies.contains(computation) || !may_pipeline) {
continue;
}
if (cp0_to_pipeline != nullptr && cp1_to_pipeline != nullptr) {
continue;
}
if (!MayPipeline(*cp)) {
continue;
}
if (cp0_to_pipeline == nullptr) {
cp0_to_pipeline = cp;
continue;
}
auto optional_pair = CheckCyclePatterns(cp0_to_pipeline, cp);
if (optional_pair.has_value()) {
cp0_to_pipeline = optional_pair.value().first;
cp1_to_pipeline = optional_pair.value().second;
}
}
for (HloCollectivePermuteInstruction* cp : cps_to_decompose) {
std::string pipeline_decision;
if (cp0_to_pipeline == cp) {
pipeline_decision = "0";
} else if (cp1_to_pipeline == cp) {
pipeline_decision = "1";
}
TF_RETURN_IF_ERROR(
DecomposeCollectivePermute(cp, computation, pipeline_decision));
}
if (!cps_to_decompose.empty()) {
changed = true;
}
}
return changed;
}
} | #include "xla/service/collective_permute_decomposer.h"
#include <memory>
#include <gmock/gmock.h>
#include <gtest/gtest.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/utils/hlo_matchers.h"
#include "xla/hlo/utils/hlo_query.h"
#include "xla/service/collective_ops_utils.h"
#include "xla/service/gpu/backend_configs.pb.h"
#include "xla/service/hlo_parser.h"
#include "xla/tests/hlo_test_base.h"
namespace xla {
namespace {
using ::testing::HasSubstr;
namespace op = xla::testing::opcode_matchers;
using CollectivePermuteDecomposerTest = HloTestBase;
TEST_F(CollectivePermuteDecomposerTest, WithCycleNotTransformed) {
const absl::string_view kModuleStr = R"(
HloModule test
ENTRY test_computation {
p = u32[] replica-id()
ROOT cp = u32[] collective-permute(p), channel_id=1,
source_target_pairs={{0,1}, {1,0}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectivePermuteDecomposerTest, WithContextDataNotTransformed) {
const char* const kModuleStr = R"(
HloModule test
ENTRY test_computation {
p = u32[] replica-id()
ROOT cp = (u32[], u32[], u32[], u32[]) collective-permute(p), channel_id=1,
source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectivePermuteDecomposerTest, TransformedExplicitChannelId) {
const char* const kModuleStr = R"(
HloModule test
ENTRY test_computation {
p = u32[] replica-id()
ROOT cp = u32[] collective-permute(p), channel_id=1,
source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}},
metadata={op_name="op1/op2/add" source_file="foo/bar/mysource.py" source_line=35}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_TRUE(changed);
auto check_metadata = [](const HloInstruction* inst) {
EXPECT_EQ(inst->metadata().op_name(), "op1/op2/add");
EXPECT_EQ(inst->metadata().source_file(), "foo/bar/mysource.py");
EXPECT_EQ(inst->metadata().source_line(), 35);
};
auto check_not_pipelined = [](const HloInstruction* instr) {
const FrontendAttributes& attributes = instr->frontend_attributes();
EXPECT_EQ(attributes.map().end(),
attributes.map().find(kSendRecvPipelineAttr));
};
HloInstruction* after_all = FindInstruction(module.get(), "after-all");
HloInstruction* recv = FindInstruction(module.get(), "recv");
EXPECT_EQ(recv->operand(0), after_all);
EXPECT_EQ(recv->channel_id().value(), 1);
EXPECT_THAT(
recv->ToString(),
HasSubstr(
"_xla_send_recv_source_target_pairs={{0,1},{1,2},{2,3},{3,4}}"));
check_metadata(recv);
check_not_pipelined(recv);
HloInstruction* recv_done = FindInstruction(module.get(), "recv-done");
EXPECT_EQ(recv_done->operand(0), recv);
HloInstruction* send = FindInstruction(module.get(), "send");
EXPECT_EQ(send->operand(1), after_all);
EXPECT_EQ(send->channel_id().value(), 1);
EXPECT_THAT(
send->ToString(),
HasSubstr(
"_xla_send_recv_source_target_pairs={{0,1},{1,2},{2,3},{3,4}}"));
check_metadata(send);
check_not_pipelined(send);
HloInstruction* send_done = FindInstruction(module.get(), "send-done");
EXPECT_EQ(send_done->operand(0), send);
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::GetTupleElement(recv_done, 0));
}
TEST_F(CollectivePermuteDecomposerTest, NotTransformedDefaultChannelId) {
const char* const kModuleStr = R"(
HloModule test
ENTRY test_computation {
p = u32[] replica-id()
ROOT cp = u32[] collective-permute(p),
source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectivePermuteDecomposerTest, ThresholdNotTransformed) {
const char* const kModuleStr = R"(
HloModule test
ENTRY test_computation {
p = u32[] replica-id()
ROOT cp = u32[] collective-permute(p), channel_id=1,
source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}},
metadata={op_name="op1/op2/add" source_file="foo/bar/mysource.py" source_line=35}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(8);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectivePermuteDecomposerTest, Pipeline1) {
const char* const kModuleStr = R"(
HloModule module
cond {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(param), index=0
ub = u32[] constant(2)
ROOT result = pred[] compare(count, ub), direction=LT
}
body {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(param), index=0
send-data = get-tuple-element(param), index=1
recv-data = u32[2] collective-permute(send-data), channel_id=1,
source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}},
frontend_attributes={_xla_other_attribute="xyz"}
c1 = u32[] constant(1)
new_count = u32[] add(count, c1)
r = u32[2] broadcast(c1), dimensions={}
s = u32[2] add(r, recv-data)
ROOT result = (u32[], u32[2]) tuple(new_count, s)
}
ENTRY test_computation {
c0 = u32[] constant(0)
c1 = u32[] constant(1)
r = u32[] replica-id()
a = u32[] add(c1, r)
init = u32[2] broadcast(a), dimensions={}
while_init = (u32[], u32[2]) tuple(c0, init)
while_result = (u32[], u32[2]) while(while_init), body=body, condition=cond
ROOT result = u32[2] get-tuple-element(while_result), index=1
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_TRUE(changed);
HloInstruction* recv = FindInstruction(module.get(), "recv");
EXPECT_EQ(recv->channel_id().value(), 1);
EXPECT_THAT(
recv->ToString(),
HasSubstr(
"_xla_send_recv_source_target_pairs={{0,1},{1,2},{2,3},{3,4}}"));
EXPECT_THAT(recv->ToString(), HasSubstr("_xla_send_recv_pipeline=\"0\""));
EXPECT_THAT(recv->ToString(), HasSubstr("_xla_other_attribute=\"xyz\""));
HloInstruction* recv_done = FindInstruction(module.get(), "recv-done");
EXPECT_THAT(recv_done->ToString(),
HasSubstr("_xla_send_recv_pipeline=\"0\""));
HloInstruction* send = FindInstruction(module.get(), "send");
EXPECT_EQ(send->channel_id().value(), 1);
EXPECT_THAT(
send->ToString(),
HasSubstr(
"_xla_send_recv_source_target_pairs={{0,1},{1,2},{2,3},{3,4}}"));
EXPECT_THAT(send->ToString(), HasSubstr("_xla_send_recv_pipeline=\"0\""));
EXPECT_THAT(send->ToString(), HasSubstr("_xla_other_attribute=\"xyz\""));
HloInstruction* send_done = FindInstruction(module.get(), "send-done");
EXPECT_THAT(send_done->ToString(),
HasSubstr("_xla_send_recv_pipeline=\"0\""));
EXPECT_FALSE(recv_done->control_predecessors().empty());
EXPECT_EQ(recv_done->control_predecessors()[0], send);
}
TEST_F(CollectivePermuteDecomposerTest, ForwardPipeline2) {
const char* const kModuleStr = R"(
HloModule module
cond {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(param), index=0
ub = u32[] constant(2)
ROOT result = pred[] compare(count, ub), direction=LT
}
body {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(param), index=0
send-data = get-tuple-element(param), index=1
recv-data.0 = u32[2] collective-permute(send-data), channel_id=1,
source_target_pairs={{3,0}}
recv-data.1 = u32[2] collective-permute(send-data), channel_id=2,
source_target_pairs={{0,1}, {1,2}, {2,3}}
replica = u32[] replica-id()
constant0 = u32[] constant(0)
compare0 = pred[] compare(replica, constant0), direction=EQ
compare = pred[2] broadcast(compare0), dimensions={}
recv-data = u32[2] select(compare, recv-data.0, recv-data.1)
c1 = u32[] constant(1)
new_count = u32[] add(count, c1)
r = u32[2] broadcast(c1), dimensions={}
s = u32[2] add(r, recv-data)
ROOT result = (u32[], u32[2]) tuple(new_count, s)
}
ENTRY test_computation {
c0 = u32[] constant(0)
c1 = u32[] constant(1)
r = u32[] replica-id()
a = u32[] add(c1, r)
init = u32[2] broadcast(a), dimensions={}
while_init = (u32[], u32[2]) tuple(c0, init)
while_result = (u32[], u32[2]) while(while_init), body=body, condition=cond
ROOT result = u32[2] get-tuple-element(while_result), index=1
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_TRUE(changed);
HloInstruction* recv = FindInstruction(module.get(), "recv");
EXPECT_EQ(recv->channel_id().value(), 1);
EXPECT_THAT(recv->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{3,0}}"));
EXPECT_THAT(recv->ToString(), HasSubstr("_xla_send_recv_pipeline=\"0\""));
HloInstruction* send = FindInstruction(module.get(), "send");
EXPECT_THAT(send->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{3,0}}"));
EXPECT_THAT(send->ToString(), HasSubstr("_xla_send_recv_pipeline=\"0\""));
HloInstruction* recv1 = FindInstruction(module.get(), "recv.1");
EXPECT_EQ(recv1->channel_id().value(), 2);
EXPECT_THAT(
recv1->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{0,1},{1,2},{2,3}}"));
EXPECT_THAT(recv1->ToString(), HasSubstr("_xla_send_recv_pipeline=\"1\""));
HloInstruction* recv_done1 = FindInstruction(module.get(), "recv-done.1");
EXPECT_THAT(recv_done1->ToString(),
HasSubstr("_xla_send_recv_pipeline=\"1\""));
HloInstruction* send1 = FindInstruction(module.get(), "send.1");
EXPECT_THAT(
send1->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{0,1},{1,2},{2,3}}"));
EXPECT_THAT(send1->ToString(), HasSubstr("_xla_send_recv_pipeline=\"1\""));
HloInstruction* send_done1 = FindInstruction(module.get(), "send-done.1");
EXPECT_THAT(send_done1->ToString(),
HasSubstr("_xla_send_recv_pipeline=\"1\""));
}
TEST_F(CollectivePermuteDecomposerTest, ForwardPipelineWithMatmul) {
const char* const kModuleStr = R"(
HloModule test
while_body {
inputs = (u32[], f32[2,2], f32[2,2]) parameter(0)
iter = u32[] get-tuple-element(inputs), index=0
iter_increment = u32[] constant(1)
next_iter = u32[] add(iter, iter_increment)
partition-id = u32[] partition-id()
zero = u32[] constant(0)
compare = pred[] compare(partition-id, zero), direction=EQ
broadcast = pred[2,2] broadcast(compare), dimensions={}
weights = f32[2,2] get-tuple-element(inputs), index=2
data = f32[2,2] get-tuple-element(inputs), index=1
cp_back = f32[2,2] collective-permute(data), channel_id=1,
source_target_pairs={{3,0}},
frontend_attributes={_xla_send_recv_validation="{{3,10}}"}
cp_forward = f32[2,2] collective-permute(data), channel_id=2,
source_target_pairs={{0,1},{1,2},{2,3}},
frontend_attributes={_xla_send_recv_validation="{{0,7},{1,8},{2,9}}"}
select = f32[2,2] select(broadcast, cp_back, cp_forward)
matmul = f32[2,2] dot(weights, select), lhs_contracting_dims={1},
rhs_contracting_dims={0}
ROOT result = (u32[], f32[2,2], f32[2,2]) tuple(next_iter, matmul, weights)
}
while_cond {
inputs = (u32[], f32[2,2], f32[2,2]) parameter(0)
iter = u32[] get-tuple-element(inputs), index=0
max_iter = u32[] constant(3)
ROOT compare = pred[] compare(iter, max_iter), direction=LT
}
ENTRY test_computation {
start_iter = u32[] constant(0)
input_data = f32[2,2] parameter(0)
input_weights = f32[2,2] parameter(1)
input = (u32[], f32[2,2], f32[2,2]) tuple(start_iter, input_data,
input_weights)
while_result = (u32[], f32[2,2], f32[2,2]) while(input),
condition=while_cond, body=while_body
ROOT data_out = f32[2,2] get-tuple-element(while_result), index=1
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_TRUE(changed);
HloModule* transformed_module = module.get();
HloComputation* while_body =
FindComputation(transformed_module, "while_body");
HloInstruction* recv_bwd = hlo_query::FindInstruction(while_body, "recv");
EXPECT_EQ(recv_bwd->channel_id().value(), 1);
auto recv_bwd_frontend_attributes = recv_bwd->frontend_attributes().map();
EXPECT_EQ(recv_bwd_frontend_attributes.size(), 3);
EXPECT_EQ(recv_bwd_frontend_attributes.at(kSendRecvValidationAttr),
"{{3,10}}");
EXPECT_EQ(recv_bwd_frontend_attributes.at(kSendRecvPipelineAttr), "0");
EXPECT_EQ(recv_bwd_frontend_attributes.at(kSendRecvSourceTargetPairsAttr),
"{{3,0}}");
HloInstruction* send_bwd = hlo_query::FindInstruction(while_body, "send");
auto send_bwd_frontend_attributes = send_bwd->frontend_attributes().map();
EXPECT_THAT(send_bwd_frontend_attributes.at(kSendRecvSourceTargetPairsAttr),
"{{3,0}}");
HloInstruction* recv_fwd = hlo_query::FindInstruction(while_body, "recv.1");
EXPECT_EQ(recv_fwd->channel_id().value(), 2);
auto recv_fwd_frontend_attributes = recv_fwd->frontend_attributes().map();
EXPECT_EQ(recv_fwd_frontend_attributes.size(), 3);
EXPECT_EQ(recv_fwd_frontend_attributes.at(kSendRecvPipelineAttr), "1");
EXPECT_EQ(recv_fwd_frontend_attributes.at(kSendRecvSourceTargetPairsAttr),
"{{0,1},{1,2},{2,3}}");
HloInstruction* send_fwd = hlo_query::FindInstruction(while_body, "send.1");
auto send_fwd_frontend_attributes = send_fwd->frontend_attributes().map();
EXPECT_EQ(send_fwd_frontend_attributes.size(), 3);
EXPECT_EQ(send_fwd_frontend_attributes.at(kSendRecvPipelineAttr), "1");
EXPECT_EQ(send_fwd_frontend_attributes.at(kSendRecvSourceTargetPairsAttr),
"{{0,1},{1,2},{2,3}}");
EXPECT_NE(while_body, nullptr);
HloInstruction* recv_done_fwd =
hlo_query::FindInstruction(while_body, "recv-done");
HloInstruction* recv_done_bwd =
hlo_query::FindInstruction(while_body, "recv-done.1");
EXPECT_EQ(recv_done_fwd->control_predecessors()[0], send_bwd);
EXPECT_EQ(recv_done_bwd->control_predecessors()[0], send_fwd);
}
TEST_F(CollectivePermuteDecomposerTest, BackwardPipeline2) {
const char* const kModuleStr = R"(
HloModule module
cond {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(param), index=0
ub = u32[] constant(2)
ROOT result = pred[] compare(count, ub), direction=LT
}
body {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(param), index=0
send-data = get-tuple-element(param), index=1
recv-data.0 = u32[2] collective-permute(send-data), channel_id=1,
source_target_pairs={{1,0},{2,1},{3,2}}
recv-data.1 = u32[2] collective-permute(send-data), channel_id=2,
source_target_pairs={{0,3}}
replica = u32[] replica-id()
constant0 = u32[] constant(0)
compare0 = pred[] compare(replica, constant0), direction=NE
compare = pred[2] broadcast(compare0), dimensions={}
recv-data = u32[2] select(compare, recv-data.0, recv-data.1)
c1 = u32[] constant(1)
new_count = u32[] add(count, c1)
r = u32[2] broadcast(c1), dimensions={}
s = u32[2] add(r, recv-data)
ROOT result = (u32[], u32[2]) tuple(new_count, s)
}
ENTRY test_computation {
c0 = u32[] constant(0)
c1 = u32[] constant(1)
r = u32[] replica-id()
a = u32[] add(c1, r)
init = u32[2] broadcast(a), dimensions={}
while_init = (u32[], u32[2]) tuple(c0, init)
while_result = (u32[], u32[2]) while(while_init), body=body, condition=cond
ROOT result = u32[2] get-tuple-element(while_result), index=1
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnUnverifiedModule((kModuleStr)));
CollectivePermuteDecomposer decomposer(0);
TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get()));
EXPECT_TRUE(changed);
HloInstruction* recv = FindInstruction(module.get(), "recv");
EXPECT_EQ(recv->channel_id().value(), 1);
EXPECT_THAT(
recv->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{1,0},{2,1},{3,2}}"));
EXPECT_THAT(recv->ToString(), HasSubstr("_xla_send_recv_pipeline=\"1\""));
HloInstruction* send = FindInstruction(module.get(), "send");
EXPECT_THAT(
send->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{1,0},{2,1},{3,2}}"));
EXPECT_THAT(send->ToString(), HasSubstr("_xla_send_recv_pipeline=\"1\""));
HloInstruction* recv1 = FindInstruction(module.get(), "recv.1");
EXPECT_EQ(recv1->channel_id().value(), 2);
EXPECT_THAT(recv1->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{0,3}}"));
EXPECT_THAT(recv1->ToString(), HasSubstr("_xla_send_recv_pipeline=\"0\""));
HloInstruction* send1 = FindInstruction(module.get(), "send.1");
EXPECT_THAT(send1->ToString(),
HasSubstr("_xla_send_recv_source_target_pairs={{0,3}}"));
EXPECT_THAT(send1->ToString(), HasSubstr("_xla_send_recv_pipeline=\"0\""));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/collective_permute_decomposer.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/collective_permute_decomposer_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
bf439647-1c08-4d9d-aff6-6426f3038b19 | cpp | google/quiche | quic_version_manager | quiche/quic/core/quic_version_manager.cc | quiche/quic/core/quic_version_manager_test.cc | #include "quiche/quic/core/quic_version_manager.h"
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/macros.h"
#include "quiche/quic/core/quic_versions.h"
#include "quiche/quic/platform/api/quic_flag_utils.h"
#include "quiche/quic/platform/api/quic_flags.h"
namespace quic {
QuicVersionManager::QuicVersionManager(
ParsedQuicVersionVector supported_versions)
: allowed_supported_versions_(std::move(supported_versions)) {}
QuicVersionManager::~QuicVersionManager() {}
const ParsedQuicVersionVector& QuicVersionManager::GetSupportedVersions() {
MaybeRefilterSupportedVersions();
return filtered_supported_versions_;
}
const ParsedQuicVersionVector&
QuicVersionManager::GetSupportedVersionsWithOnlyHttp3() {
MaybeRefilterSupportedVersions();
return filtered_supported_versions_with_http3_;
}
const std::vector<std::string>& QuicVersionManager::GetSupportedAlpns() {
MaybeRefilterSupportedVersions();
return filtered_supported_alpns_;
}
void QuicVersionManager::MaybeRefilterSupportedVersions() {
static_assert(SupportedVersions().size() == 4u,
"Supported versions out of sync");
if (enable_version_2_draft_08_ !=
GetQuicReloadableFlag(quic_enable_version_rfcv2) ||
disable_version_rfcv1_ !=
GetQuicReloadableFlag(quic_disable_version_rfcv1) ||
disable_version_draft_29_ !=
GetQuicReloadableFlag(quic_disable_version_draft_29) ||
disable_version_q046_ !=
GetQuicReloadableFlag(quic_disable_version_q046)) {
enable_version_2_draft_08_ =
GetQuicReloadableFlag(quic_enable_version_rfcv2);
disable_version_rfcv1_ = GetQuicReloadableFlag(quic_disable_version_rfcv1);
disable_version_draft_29_ =
GetQuicReloadableFlag(quic_disable_version_draft_29);
disable_version_q046_ = GetQuicReloadableFlag(quic_disable_version_q046);
RefilterSupportedVersions();
}
}
void QuicVersionManager::RefilterSupportedVersions() {
filtered_supported_versions_ =
FilterSupportedVersions(allowed_supported_versions_);
filtered_supported_versions_with_http3_.clear();
filtered_transport_versions_.clear();
filtered_supported_alpns_.clear();
for (const ParsedQuicVersion& version : filtered_supported_versions_) {
auto transport_version = version.transport_version;
if (std::find(filtered_transport_versions_.begin(),
filtered_transport_versions_.end(),
transport_version) == filtered_transport_versions_.end()) {
filtered_transport_versions_.push_back(transport_version);
}
if (version.UsesHttp3()) {
filtered_supported_versions_with_http3_.push_back(version);
}
if (std::find(filtered_supported_alpns_.begin(),
filtered_supported_alpns_.end(),
AlpnForVersion(version)) == filtered_supported_alpns_.end()) {
filtered_supported_alpns_.emplace_back(AlpnForVersion(version));
}
}
}
void QuicVersionManager::AddCustomAlpn(const std::string& alpn) {
filtered_supported_alpns_.push_back(alpn);
}
} | #include "quiche/quic/core/quic_version_manager.h"
#include "absl/base/macros.h"
#include "quiche/quic/core/quic_versions.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_test.h"
using ::testing::ElementsAre;
namespace quic {
namespace test {
namespace {
class QuicVersionManagerTest : public QuicTest {};
TEST_F(QuicVersionManagerTest, QuicVersionManager) {
static_assert(SupportedVersions().size() == 4u,
"Supported versions out of sync");
for (const ParsedQuicVersion& version : AllSupportedVersions()) {
QuicEnableVersion(version);
}
QuicDisableVersion(ParsedQuicVersion::RFCv2());
QuicDisableVersion(ParsedQuicVersion::RFCv1());
QuicDisableVersion(ParsedQuicVersion::Draft29());
QuicVersionManager manager(AllSupportedVersions());
ParsedQuicVersionVector expected_parsed_versions;
expected_parsed_versions.push_back(ParsedQuicVersion::Q046());
EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions());
EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()),
manager.GetSupportedVersions());
EXPECT_TRUE(manager.GetSupportedVersionsWithOnlyHttp3().empty());
EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3-Q046"));
QuicEnableVersion(ParsedQuicVersion::Draft29());
expected_parsed_versions.insert(expected_parsed_versions.begin(),
ParsedQuicVersion::Draft29());
EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions());
EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()),
manager.GetSupportedVersions());
EXPECT_EQ(1u, manager.GetSupportedVersionsWithOnlyHttp3().size());
EXPECT_EQ(CurrentSupportedHttp3Versions(),
manager.GetSupportedVersionsWithOnlyHttp3());
EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3-29", "h3-Q046"));
QuicEnableVersion(ParsedQuicVersion::RFCv1());
expected_parsed_versions.insert(expected_parsed_versions.begin(),
ParsedQuicVersion::RFCv1());
EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions());
EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()),
manager.GetSupportedVersions());
EXPECT_EQ(2u, manager.GetSupportedVersionsWithOnlyHttp3().size());
EXPECT_EQ(CurrentSupportedHttp3Versions(),
manager.GetSupportedVersionsWithOnlyHttp3());
EXPECT_THAT(manager.GetSupportedAlpns(),
ElementsAre("h3", "h3-29", "h3-Q046"));
QuicEnableVersion(ParsedQuicVersion::RFCv2());
expected_parsed_versions.insert(expected_parsed_versions.begin(),
ParsedQuicVersion::RFCv2());
EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions());
EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()),
manager.GetSupportedVersions());
EXPECT_EQ(3u, manager.GetSupportedVersionsWithOnlyHttp3().size());
EXPECT_EQ(CurrentSupportedHttp3Versions(),
manager.GetSupportedVersionsWithOnlyHttp3());
EXPECT_THAT(manager.GetSupportedAlpns(),
ElementsAre("h3", "h3-29", "h3-Q046"));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_version_manager.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_version_manager_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
752addfa-8501-4302-a483-b6663f69ea03 | cpp | tensorflow/tensorflow | recognize_commands | tensorflow/examples/speech_commands/recognize_commands.cc | tensorflow/examples/speech_commands/recognize_commands_test.cc | #include "tensorflow/examples/speech_commands/recognize_commands.h"
#include "absl/status/status.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
RecognizeCommands::RecognizeCommands(const std::vector<string>& labels,
int32_t average_window_duration_ms,
float detection_threshold,
int32_t suppression_ms,
int32_t minimum_count)
: labels_(labels),
average_window_duration_ms_(average_window_duration_ms),
detection_threshold_(detection_threshold),
suppression_ms_(suppression_ms),
minimum_count_(minimum_count) {
labels_count_ = labels.size();
previous_top_label_ = "_silence_";
previous_top_label_time_ = std::numeric_limits<int64_t>::min();
}
Status RecognizeCommands::ProcessLatestResults(const Tensor& latest_results,
const int64_t current_time_ms,
string* found_command,
float* score,
bool* is_new_command) {
if (latest_results.NumElements() != labels_count_) {
return errors::InvalidArgument(
"The results for recognition should contain ", labels_count_,
" elements, but there are ", latest_results.NumElements());
}
if ((!previous_results_.empty()) &&
(current_time_ms < previous_results_.front().first)) {
return errors::InvalidArgument(
"Results must be fed in increasing time order, but received a "
"timestamp of ",
current_time_ms, " that was earlier than the previous one of ",
previous_results_.front().first);
}
previous_results_.push_back({current_time_ms, latest_results});
const int64_t time_limit = current_time_ms - average_window_duration_ms_;
while (previous_results_.front().first < time_limit) {
previous_results_.pop_front();
}
const int64_t how_many_results = previous_results_.size();
const int64_t earliest_time = previous_results_.front().first;
const int64_t samples_duration = current_time_ms - earliest_time;
if ((how_many_results < minimum_count_) ||
(samples_duration < (average_window_duration_ms_ / 4))) {
*found_command = previous_top_label_;
*score = 0.0f;
*is_new_command = false;
return absl::OkStatus();
}
std::vector<float> average_scores(labels_count_);
for (const auto& previous_result : previous_results_) {
const Tensor& scores_tensor = previous_result.second;
auto scores_flat = scores_tensor.flat<float>();
for (int i = 0; i < scores_flat.size(); ++i) {
average_scores[i] += scores_flat(i) / how_many_results;
}
}
std::vector<std::pair<int, float>> sorted_average_scores;
sorted_average_scores.reserve(labels_count_);
for (int i = 0; i < labels_count_; ++i) {
sorted_average_scores.push_back(
std::pair<int, float>({i, average_scores[i]}));
}
std::sort(sorted_average_scores.begin(), sorted_average_scores.end(),
[](const std::pair<int, float>& left,
const std::pair<int, float>& right) {
return left.second > right.second;
});
const int current_top_index = sorted_average_scores[0].first;
const string current_top_label = labels_[current_top_index];
const float current_top_score = sorted_average_scores[0].second;
int64_t time_since_last_top;
if ((previous_top_label_ == "_silence_") ||
(previous_top_label_time_ == std::numeric_limits<int64_t>::min())) {
time_since_last_top = std::numeric_limits<int64_t>::max();
} else {
time_since_last_top = current_time_ms - previous_top_label_time_;
}
if ((current_top_score > detection_threshold_) &&
(current_top_label != previous_top_label_) &&
(time_since_last_top > suppression_ms_)) {
previous_top_label_ = current_top_label;
previous_top_label_time_ = current_time_ms;
*is_new_command = true;
} else {
*is_new_command = false;
}
*found_command = current_top_label;
*score = current_top_score;
return absl::OkStatus();
}
} | #include "tensorflow/examples/speech_commands/recognize_commands.h"
#include "xla/tsl/lib/core/status_test_util.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
TEST(RecognizeCommandsTest, Basic) {
RecognizeCommands recognize_commands({"_silence_", "a", "b"});
Tensor results(DT_FLOAT, {3});
test::FillValues<float>(&results, {1.0f, 0.0f, 0.0f});
string found_command;
float score;
bool is_new_command;
TF_EXPECT_OK(recognize_commands.ProcessLatestResults(
results, 0, &found_command, &score, &is_new_command));
}
TEST(RecognizeCommandsTest, FindCommands) {
RecognizeCommands recognize_commands({"_silence_", "a", "b"}, 1000, 0.2f);
Tensor results(DT_FLOAT, {3});
test::FillValues<float>(&results, {0.0f, 1.0f, 0.0f});
bool has_found_new_command = false;
string new_command;
for (int i = 0; i < 10; ++i) {
string found_command;
float score;
bool is_new_command;
int64_t current_time_ms = 0 + (i * 100);
TF_EXPECT_OK(recognize_commands.ProcessLatestResults(
results, current_time_ms, &found_command, &score, &is_new_command));
if (is_new_command) {
EXPECT_FALSE(has_found_new_command);
has_found_new_command = true;
new_command = found_command;
}
}
EXPECT_TRUE(has_found_new_command);
EXPECT_EQ("a", new_command);
test::FillValues<float>(&results, {0.0f, 0.0f, 1.0f});
has_found_new_command = false;
new_command = "";
for (int i = 0; i < 10; ++i) {
string found_command;
float score;
bool is_new_command;
int64_t current_time_ms = 1000 + (i * 100);
TF_EXPECT_OK(recognize_commands.ProcessLatestResults(
results, current_time_ms, &found_command, &score, &is_new_command));
if (is_new_command) {
EXPECT_FALSE(has_found_new_command);
has_found_new_command = true;
new_command = found_command;
}
}
EXPECT_TRUE(has_found_new_command);
EXPECT_EQ("b", new_command);
}
TEST(RecognizeCommandsTest, BadInputLength) {
RecognizeCommands recognize_commands({"_silence_", "a", "b"}, 1000, 0.2f);
Tensor bad_results(DT_FLOAT, {2});
test::FillValues<float>(&bad_results, {1.0f, 0.0f});
string found_command;
float score;
bool is_new_command;
EXPECT_FALSE(recognize_commands
.ProcessLatestResults(bad_results, 0, &found_command, &score,
&is_new_command)
.ok());
}
TEST(RecognizeCommandsTest, BadInputTimes) {
RecognizeCommands recognize_commands({"_silence_", "a", "b"}, 1000, 0.2f);
Tensor results(DT_FLOAT, {3});
test::FillValues<float>(&results, {1.0f, 0.0f, 0.0f});
string found_command;
float score;
bool is_new_command;
TF_EXPECT_OK(recognize_commands.ProcessLatestResults(
results, 100, &found_command, &score, &is_new_command));
EXPECT_FALSE(recognize_commands
.ProcessLatestResults(results, 0, &found_command, &score,
&is_new_command)
.ok());
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/examples/speech_commands/recognize_commands.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/examples/speech_commands/recognize_commands_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
3ec29614-5909-4ff3-94b0-a536b979a79e | cpp | google/libphonenumber | unicodetext | cpp/src/phonenumbers/utf/unicodetext.cc | cpp/test/phonenumbers/utf/unicodetext_test.cc | #include <algorithm>
#include <sstream>
#include <cassert>
#include <cstdio>
#include "phonenumbers/default_logger.h"
#include "phonenumbers/utf/unicodetext.h"
#include "phonenumbers/utf/stringpiece.h"
#include "phonenumbers/utf/utf.h"
#include "phonenumbers/utf/unilib.h"
namespace i18n {
namespace phonenumbers {
using std::string;
using std::stringstream;
using std::max;
using std::hex;
using std::dec;
static int CodepointDistance(const char* start, const char* end) {
int n = 0;
for (const char* p = start; p < end; ++p) {
n += (*reinterpret_cast<const signed char*>(p) >= -0x40);
}
return n;
}
static int CodepointCount(const char* utf8, int len) {
return CodepointDistance(utf8, utf8 + len);
}
UnicodeText::const_iterator::difference_type
distance(const UnicodeText::const_iterator& first,
const UnicodeText::const_iterator& last) {
return CodepointDistance(first.it_, last.it_);
}
static int ConvertToInterchangeValid(char* start, int len) {
char* const in = start;
char* out = start;
char* const end = start + len;
while (start < end) {
int good = UniLib::SpanInterchangeValid(start, static_cast<int>(end - start));
if (good > 0) {
if (out != start) {
memmove(out, start, good);
}
out += good;
start += good;
if (start == end) {
break;
}
}
Rune rune;
int n;
if (isvalidcharntorune(start, static_cast<int>(end - start), &rune, &n)) {
start += n;
} else {
start += 1;
}
*out++ = ' ';
}
return static_cast<int>(out - in);
}
void UnicodeText::Repr::reserve(int new_capacity) {
if (capacity_ >= new_capacity && ours_) return;
capacity_ = max(new_capacity, (3 * capacity_) / 2 + 20);
char* new_data = new char[capacity_];
if (data_) {
memcpy(new_data, data_, size_);
if (ours_) delete[] data_;
}
data_ = new_data;
ours_ = true;
}
void UnicodeText::Repr::resize(int new_size) {
if (new_size == 0) {
clear();
} else {
if (!ours_ || new_size > capacity_) reserve(new_size);
if (size_ < new_size) memset(data_ + size_, 0, new_size - size_);
size_ = new_size;
ours_ = true;
}
}
void UnicodeText::Repr::clear() {
if (ours_) delete[] data_;
data_ = NULL;
size_ = capacity_ = 0;
ours_ = true;
}
void UnicodeText::Repr::Copy(const char* data, int size) {
resize(size);
memcpy(data_, data, size);
}
void UnicodeText::Repr::TakeOwnershipOf(char* data, int size, int capacity) {
if (data == data_) return;
if (ours_ && data_) delete[] data_;
data_ = data;
size_ = size;
capacity_ = capacity;
ours_ = true;
}
void UnicodeText::Repr::PointTo(const char* data, int size) {
if (ours_ && data_) delete[] data_;
data_ = const_cast<char*>(data);
size_ = size;
capacity_ = size;
ours_ = false;
}
void UnicodeText::Repr::append(const char* bytes, int byte_length) {
reserve(size_ + byte_length);
memcpy(data_ + size_, bytes, byte_length);
size_ += byte_length;
}
string UnicodeText::Repr::DebugString() const {
stringstream ss;
ss << "{Repr " << hex << this << " data=" << data_ << " size=" << dec
<< size_ << " capacity=" << capacity_ << " "
<< (ours_ ? "Owned" : "Alias") << "}";
string result;
ss >> result;
return result;
}
UnicodeText::UnicodeText() {
}
UnicodeText::UnicodeText(const UnicodeText& src) {
Copy(src);
}
UnicodeText::UnicodeText(const UnicodeText::const_iterator& first,
const UnicodeText::const_iterator& last) {
assert(first <= last && "Incompatible iterators");
repr_.append(first.it_, static_cast<int>(last.it_ - first.it_));
}
string UnicodeText::UTF8Substring(const const_iterator& first,
const const_iterator& last) {
assert(first <= last && "Incompatible iterators");
return string(first.it_, last.it_ - first.it_);
}
UnicodeText& UnicodeText::operator=(const UnicodeText& src) {
if (this != &src) {
Copy(src);
}
return *this;
}
UnicodeText& UnicodeText::Copy(const UnicodeText& src) {
repr_.Copy(src.repr_.data_, src.repr_.size_);
return *this;
}
UnicodeText& UnicodeText::CopyUTF8(const char* buffer, int byte_length) {
repr_.Copy(buffer, byte_length);
repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length);
if (!repr_.utf8_was_valid_) {
LOG(WARNING) << "UTF-8 buffer is not interchange-valid.";
repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
}
return *this;
}
UnicodeText& UnicodeText::UnsafeCopyUTF8(const char* buffer,
int byte_length) {
repr_.Copy(buffer, byte_length);
return *this;
}
UnicodeText& UnicodeText::TakeOwnershipOfUTF8(char* buffer,
int byte_length,
int byte_capacity) {
repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity);
repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length);
if (!repr_.utf8_was_valid_) {
LOG(WARNING) << "UTF-8 buffer is not interchange-valid.";
repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
}
return *this;
}
UnicodeText& UnicodeText::UnsafeTakeOwnershipOfUTF8(char* buffer,
int byte_length,
int byte_capacity) {
repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity);
return *this;
}
UnicodeText& UnicodeText::PointToUTF8(const char* buffer, int byte_length) {
repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length);
if (repr_.utf8_was_valid_) {
repr_.PointTo(buffer, byte_length);
} else {
LOG(WARNING) << "UTF-8 buffer is not interchange-valid.";
repr_.Copy(buffer, byte_length);
repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
}
return *this;
}
UnicodeText& UnicodeText::UnsafePointToUTF8(const char* buffer,
int byte_length) {
repr_.PointTo(buffer, byte_length);
return *this;
}
UnicodeText& UnicodeText::PointTo(const UnicodeText& src) {
repr_.PointTo(src.repr_.data_, src.repr_.size_);
return *this;
}
UnicodeText& UnicodeText::PointTo(const const_iterator &first,
const const_iterator &last) {
assert(first <= last && " Incompatible iterators");
repr_.PointTo(first.utf8_data(), static_cast<int>(last.utf8_data() - first.utf8_data()));
return *this;
}
UnicodeText& UnicodeText::append(const UnicodeText& u) {
repr_.append(u.repr_.data_, u.repr_.size_);
return *this;
}
UnicodeText& UnicodeText::append(const const_iterator& first,
const const_iterator& last) {
assert(first <= last && "Incompatible iterators");
repr_.append(first.it_, static_cast<int>(last.it_ - first.it_));
return *this;
}
UnicodeText& UnicodeText::UnsafeAppendUTF8(const char* utf8, int len) {
repr_.append(utf8, len);
return *this;
}
UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look,
const_iterator start_pos) const {
assert(start_pos.utf8_data() >= utf8_data());
assert(start_pos.utf8_data() <= utf8_data() + utf8_length());
return UnsafeFind(look, start_pos);
}
UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look) const {
return UnsafeFind(look, begin());
}
UnicodeText::const_iterator UnicodeText::UnsafeFind(
const UnicodeText& look, const_iterator start_pos) const {
StringPiece searching(utf8_data(), utf8_length());
StringPiece look_piece(look.utf8_data(), look.utf8_length());
StringPiece::size_type found =
searching.find(look_piece, start_pos.utf8_data() - utf8_data());
if (found == StringPiece::npos) return end();
return const_iterator(utf8_data() + found);
}
bool UnicodeText::HasReplacementChar() const {
StringPiece searching(utf8_data(), utf8_length());
StringPiece looking_for("\xEF\xBF\xBD", 3);
return searching.find(looking_for) != StringPiece::npos;
}
void UnicodeText::clear() {
repr_.clear();
}
UnicodeText::~UnicodeText() {}
void UnicodeText::push_back(char32 c) {
if (UniLib::IsValidCodepoint(c)) {
char buf[UTFmax];
Rune rune = c;
int len = runetochar(buf, &rune);
if (UniLib::IsInterchangeValid(buf, len)) {
repr_.append(buf, len);
} else {
fprintf(stderr, "Unicode value 0x%x is not valid for interchange\n", c);
repr_.append(" ", 1);
}
} else {
fprintf(stderr, "Illegal Unicode value: 0x%x\n", c);
repr_.append(" ", 1);
}
}
int UnicodeText::size() const {
return CodepointCount(repr_.data_, repr_.size_);
}
bool operator==(const UnicodeText& lhs, const UnicodeText& rhs) {
if (&lhs == &rhs) return true;
if (lhs.repr_.size_ != rhs.repr_.size_) return false;
return memcmp(lhs.repr_.data_, rhs.repr_.data_, lhs.repr_.size_) == 0;
}
string UnicodeText::DebugString() const {
stringstream ss;
ss << "{UnicodeText " << hex << this << dec << " chars="
<< size() << " repr=" << repr_.DebugString() << "}";
#if 0
return StringPrintf("{UnicodeText %p chars=%d repr=%s}",
this,
size(),
repr_.DebugString().c_str());
#endif
string result;
ss >> result;
return result;
}
UnicodeText::const_iterator::const_iterator() : it_(0) {}
UnicodeText::const_iterator::const_iterator(const const_iterator& other)
: it_(other.it_) {
}
UnicodeText::const_iterator&
UnicodeText::const_iterator::operator=(const const_iterator& other) {
if (&other != this)
it_ = other.it_;
return *this;
}
UnicodeText::const_iterator UnicodeText::begin() const {
return const_iterator(repr_.data_);
}
UnicodeText::const_iterator UnicodeText::end() const {
return const_iterator(repr_.data_ + repr_.size_);
}
bool operator<(const UnicodeText::const_iterator& lhs,
const UnicodeText::const_iterator& rhs) {
return lhs.it_ < rhs.it_;
}
char32 UnicodeText::const_iterator::operator*() const {
uint8 byte1 = static_cast<uint8>(it_[0]);
if (byte1 < 0x80)
return byte1;
uint8 byte2 = static_cast<uint8>(it_[1]);
if (byte1 < 0xE0)
return ((byte1 & 0x1F) << 6)
| (byte2 & 0x3F);
uint8 byte3 = static_cast<uint8>(it_[2]);
if (byte1 < 0xF0)
return ((byte1 & 0x0F) << 12)
| ((byte2 & 0x3F) << 6)
| (byte3 & 0x3F);
uint8 byte4 = static_cast<uint8>(it_[3]);
return ((byte1 & 0x07) << 18)
| ((byte2 & 0x3F) << 12)
| ((byte3 & 0x3F) << 6)
| (byte4 & 0x3F);
}
UnicodeText::const_iterator& UnicodeText::const_iterator::operator++() {
it_ += UniLib::OneCharLen(it_);
return *this;
}
UnicodeText::const_iterator& UnicodeText::const_iterator::operator--() {
while (UniLib::IsTrailByte(*--it_)) { }
return *this;
}
int UnicodeText::const_iterator::get_utf8(char* utf8_output) const {
utf8_output[0] = it_[0];
if (static_cast<unsigned char>(it_[0]) < 0x80)
return 1;
utf8_output[1] = it_[1];
if (static_cast<unsigned char>(it_[0]) < 0xE0)
return 2;
utf8_output[2] = it_[2];
if (static_cast<unsigned char>(it_[0]) < 0xF0)
return 3;
utf8_output[3] = it_[3];
return 4;
}
UnicodeText::const_iterator UnicodeText::MakeIterator(const char* p) const {
#ifndef NDEBUG
assert(p != NULL);
const char* start = utf8_data();
int len = utf8_length();
const char* end = start + len;
assert(p >= start);
assert(p <= end);
assert(p == end || !UniLib::IsTrailByte(*p));
#endif
return const_iterator(p);
}
string UnicodeText::const_iterator::DebugString() const {
stringstream ss;
ss << "{iter " << hex << it_ << "}";
string result;
ss >> result;
return result;
}
}
} | #include <gtest/gtest.h>
#include "phonenumbers/utf/unicodetext.h"
namespace i18n {
namespace phonenumbers {
TEST(UnicodeTextTest, Iterator) {
struct value {
const char* utf8;
char32 code_point;
} values[] = {
{ "\x31", 0x31 },
{ "\xC2\xBD", 0x00BD },
{ "\xEF\xBC\x91", 0xFF11 },
{ "\xF0\x9F\x80\x80", 0x1F000 },
};
for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) {
string number(values[i].utf8);
UnicodeText number_as_unicode;
number_as_unicode.PointToUTF8(number.data(), number.size());
EXPECT_TRUE(number_as_unicode.UTF8WasValid());
UnicodeText::const_iterator it = number_as_unicode.begin();
EXPECT_EQ(values[i].code_point, *it);
}
}
}
} | https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/utf/unicodetext.cc | https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/utf/unicodetext_test.cc | 9aa9aaa39ad8098aef56071d2df4f6f8d251c98b |
58f7e05d-6f1d-41ca-932f-498558a8bde2 | cpp | tensorflow/tensorflow | nvptx_compiler | third_party/xla/xla/service/gpu/nvptx_compiler.cc | third_party/xla/xla/service/gpu/nvptx_compiler_test.cc | #include "xla/service/gpu/nvptx_compiler.h"
#include <algorithm>
#include <array>
#include <cstdint>
#include <fstream>
#include <iterator>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/call_once.h"
#include "absl/cleanup/cleanup.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/hlo/pass/hlo_pass_fix.h"
#include "xla/hlo/pass/hlo_pass_pipeline.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/service/algebraic_simplifier.h"
#include "xla/service/call_inliner.h"
#include "xla/service/convert_mover.h"
#include "xla/service/dot_dimension_merger.h"
#include "xla/service/dump.h"
#include "xla/service/float_normalization.h"
#include "xla/service/float_support.h"
#include "xla/service/gpu/autotuning/autotuner_util.h"
#include "xla/service/gpu/autotuning/conv_algorithm_picker.h"
#include "xla/service/gpu/autotuning/gemm_algorithm_picker.h"
#include "xla/service/gpu/autotuning/gemm_fusion_autotuner.h"
#include "xla/service/gpu/buffer_sharing.h"
#include "xla/service/gpu/cublas_padding_requirements.h"
#include "xla/service/gpu/gpu_asm_opts_util.h"
#include "xla/service/gpu/gpu_compiler.h"
#include "xla/service/gpu/ir_emission_utils.h"
#include "xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h"
#include "xla/service/gpu/metrics.h"
#include "xla/service/gpu/target_constants.h"
#include "xla/service/gpu/transforms/algebraic_simplifier.h"
#include "xla/service/gpu/transforms/conv_padding_legalization.h"
#include "xla/service/gpu/transforms/conv_rewriter.h"
#include "xla/service/gpu/transforms/cublas_pad_for_gemms.h"
#include "xla/service/gpu/transforms/cudnn_custom_call_compiler.h"
#include "xla/service/gpu/transforms/cudnn_fused_conv_rewriter.h"
#include "xla/service/gpu/transforms/cudnn_fused_mha_rewriter.h"
#include "xla/service/gpu/transforms/cudnn_fused_mha_transpose_fusion.h"
#include "xla/service/gpu/transforms/cudnn_fusion_compiler.h"
#include "xla/service/gpu/transforms/cudnn_norm_rewriter.h"
#include "xla/service/gpu/transforms/cudnn_pad_for_convolutions.h"
#include "xla/service/gpu/transforms/cudnn_simplify_padding.h"
#include "xla/service/gpu/transforms/cudnn_vectorize_convolutions.h"
#include "xla/service/gpu/transforms/dot_sparsity_rewriter.h"
#include "xla/service/gpu/transforms/gpusolver_rewriter.h"
#include "xla/service/gpu/transforms/sort_rewriter.h"
#include "xla/service/gpu/transforms/triangular_solve_rewriter.h"
#include "xla/service/hlo_constant_folding.h"
#include "xla/service/hlo_cse.h"
#include "xla/service/hlo_dataflow_analysis.h"
#include "xla/service/hlo_dce.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/hlo_verifier.h"
#include "xla/service/llvm_ir/llvm_util.h"
#include "xla/service/reshape_mover.h"
#include "xla/service/tuple_simplifier.h"
#include "xla/stream_executor/cuda/cuda_asm_compiler.h"
#include "xla/stream_executor/cuda/cuda_diagnostics.h"
#include "xla/stream_executor/cuda/cuda_driver.h"
#include "xla/stream_executor/cuda/cuda_platform_id.h"
#include "xla/stream_executor/cuda/nvjitlink.h"
#include "xla/stream_executor/cuda/nvjitlink_support.h"
#include "xla/stream_executor/cuda/ptx_compilation_method.h"
#include "xla/stream_executor/cuda/ptx_compiler.h"
#include "xla/stream_executor/cuda/ptx_compiler_support.h"
#include "xla/stream_executor/cuda/ptx_linking_method.h"
#include "xla/stream_executor/device_description.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/stream_executor/dnn.h"
#include "xla/stream_executor/gpu/gpu_asm_opts.h"
#include "xla/stream_executor/gpu/gpu_driver.h"
#include "xla/stream_executor/gpu/gpu_executor.h"
#include "xla/stream_executor/semantic_version.h"
#include "xla/stream_executor/stream_executor.h"
#include "xla/tsl/util/env_var.h"
#include "xla/util.h"
#include "xla/xla.pb.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/path.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/threadpool.h"
#include "tsl/profiler/lib/scoped_annotation.h"
#include "tsl/profiler/lib/traceme.h"
namespace xla {
namespace gpu {
namespace {
class ConvBfloat16Support : public FloatSupport {
public:
explicit ConvBfloat16Support(
se::dnn::VersionInfo cudnn_version,
se::CudaComputeCapability cuda_compute_capability)
: FloatSupport(BF16),
is_conv_bf16_supported_((cudnn_version.major_version() > 8 ||
(cudnn_version.major_version() == 8 &&
cudnn_version.minor_version() >= 2)) &&
cuda_compute_capability.IsAtLeast(
se::CudaComputeCapability::AMPERE)) {}
bool SupportsLowPrecisionOperand(const HloInstruction& hlo,
int64_t operand_index) const override {
return (hlo.opcode() != HloOpcode::kConvolution) || is_conv_bf16_supported_;
}
bool SupportsLowPrecisionOutput(const HloInstruction& hlo) const override {
return (hlo.opcode() != HloOpcode::kConvolution) || is_conv_bf16_supported_;
}
bool SupportsMixedPrecisions(const HloInstruction& hlo) const override {
return (hlo.opcode() != HloOpcode::kConvolution);
}
private:
bool is_conv_bf16_supported_;
};
class MatmulBfloat16Support : public FloatSupport {
public:
explicit MatmulBfloat16Support(
se::CudaComputeCapability cuda_compute_capability)
: FloatSupport(BF16),
is_matmul_bf16_supported_(cuda_compute_capability.IsAtLeast(
se::CudaComputeCapability::AMPERE)) {}
bool SupportsLowPrecisionOperand(const HloInstruction& hlo,
int64_t operand_index) const override {
return (hlo.opcode() != HloOpcode::kDot) || is_matmul_bf16_supported_;
}
bool SupportsLowPrecisionOutput(const HloInstruction& hlo) const override {
return (hlo.opcode() != HloOpcode::kDot) || is_matmul_bf16_supported_;
}
bool SupportsMixedPrecisions(const HloInstruction& hlo) const override {
return true;
}
private:
bool is_matmul_bf16_supported_;
};
}
absl::Status NVPTXCompiler::OptimizeHloConvolutionCanonicalization(
HloModule* hlo_module, se::GpuComputeCapability gpu_version,
se::dnn::VersionInfo dnn_version,
se::DeviceMemoryAllocator* device_allocator,
const se::SemanticVersion& toolkit_version) {
auto cuda_compute_capability =
std::get<se::CudaComputeCapability>(gpu_version);
HloPassPipeline pipeline("conv_canonicalization");
pipeline.AddInvariantCheckerDebug<HloVerifier>(
false,
false);
ConvBfloat16Support conv_bf16_support(dnn_version, cuda_compute_capability);
pipeline.AddPass<FloatNormalization>(&conv_bf16_support);
MatmulBfloat16Support matmul_bf16_support(cuda_compute_capability);
pipeline.AddPass<FloatNormalization>(&matmul_bf16_support);
pipeline.AddPass<GpusolverRewriter>();
if (!hlo_module->config()
.debug_options()
.xla_gpu_experimental_disable_binary_libraries()) {
pipeline.AddPass<ConvRewriter>(cuda_compute_capability);
pipeline.AddPass<CudnnFusedConvRewriter>(cuda_compute_capability,
dnn_version, toolkit_version);
pipeline.AddPass<ConvPaddingLegalization>();
pipeline.AddPass<CudnnPadForConvolutions>(cuda_compute_capability);
pipeline.AddPass<CudnnVectorizeConvolutions>(cuda_compute_capability,
dnn_version);
}
pipeline.AddPass<CallInliner>();
pipeline.AddPass<TupleSimplifier>();
AlgebraicSimplifierOptions algsimp_options =
GetAlgebraicSimplifierOptions(hlo_module->config());
algsimp_options.set_supports_non_canonical_dots(false);
algsimp_options.set_enable_conv_operand_swap(false);
algsimp_options.set_enable_unconditional_reduce_of_concat_replacement(false);
pipeline.AddPass<HloPassFix<GpuAlgebraicSimplifier>>(algsimp_options,
gpu_version);
if (!hlo_module->config()
.debug_options()
.xla_gpu_experimental_disable_binary_libraries()) {
pipeline.AddPass<CudnnSimplifyPadding>();
}
[&, &pipeline = pipeline.AddPass<HloPassFix<HloPassPipeline>>(
"reshape_mover_after_conv_canonicalization")] {
ReshapeMoverOptions reshape_mover_options;
reshape_mover_options.reshape_of_1d_broadcast_is_cheap = true;
pipeline.AddPass<ReshapeMover>(reshape_mover_options);
pipeline.AddPass<GpuAlgebraicSimplifier>(algsimp_options, gpu_version);
}();
[&, &pipeline = pipeline.AddPass<HloPassFix<HloPassPipeline>>(
"simplify_after_conv_canonicalization")] {
pipeline.AddPass<ConvertMover>();
pipeline.AddPass<GpuAlgebraicSimplifier>(algsimp_options, gpu_version);
}();
pipeline.AddPass<HloConstantFolding>();
TF_RETURN_IF_ERROR(pipeline.Run(hlo_module).status());
return absl::OkStatus();
}
absl::Status NVPTXCompiler::OptimizeHloPostLayoutAssignment(
HloModule* hlo_module, se::StreamExecutor* stream_exec,
const CompileOptions& options, const TargetConfig& gpu_target_config,
tsl::thread::ThreadPool* thread_pool) {
auto cuda_compute_capability = std::get<se::CudaComputeCapability>(
gpu_target_config.device_description.gpu_compute_capability());
if (hlo_module->config().debug_options().xla_gpu_enable_cudnn_fmha() &&
!hlo_module->config()
.debug_options()
.xla_gpu_experimental_disable_binary_libraries()) {
HloPassPipeline mha_fusion_pipeline(
"nvptx cudnn multi-headed attention fusion");
AlgebraicSimplifierOptions alg_sim_options =
GetAlgebraicSimplifierOptions(hlo_module->config());
alg_sim_options.set_supports_non_canonical_dots(false);
alg_sim_options.set_is_layout_sensitive(true);
alg_sim_options.set_enable_conv_operand_swap(false);
alg_sim_options.set_minmax_propagate_nan(
!hlo_module->config().debug_options().xla_gpu_enable_fast_min_max());
alg_sim_options.set_enable_unconditional_reduce_of_concat_replacement(
false);
mha_fusion_pipeline.AddPass<HloCSE>(true);
se::GpuComputeCapability gpu_version =
gpu_target_config.device_description.gpu_compute_capability();
mha_fusion_pipeline.AddPass<HloPassFix<GpuAlgebraicSimplifier>>(
alg_sim_options, gpu_version);
mha_fusion_pipeline.AddPass<HloCSE>(true);
if (stream_exec) {
mha_fusion_pipeline.AddPass<CudnnFusedMHARewriter>(
cuda_compute_capability, stream_exec);
} else {
mha_fusion_pipeline.AddPass<CudnnFusedMHARewriter>(
cuda_compute_capability, gpu_target_config.dnn_version_info);
}
mha_fusion_pipeline.AddPass<GpuAlgebraicSimplifier>(alg_sim_options,
gpu_version);
mha_fusion_pipeline.AddPass<CudnnFusedMHATransposeFusion>();
mha_fusion_pipeline.AddPass<HloDCE>();
mha_fusion_pipeline.AddPass<HloCSE>(true);
TF_RETURN_IF_ERROR(mha_fusion_pipeline.Run(hlo_module).status());
}
HloPassPipeline pre_pipeline("nvptx post-layout_assignment part 1");
if (hlo_module->config().debug_options().xla_gpu_enable_cudnn_layer_norm() &&
!hlo_module->config()
.debug_options()
.xla_gpu_experimental_disable_binary_libraries()) {
pre_pipeline.AddPass<CudnnNormRewriter>(cuda_compute_capability);
}
pre_pipeline.AddPass<DotDimensionMerger>();
pre_pipeline.AddPass<DotSparsityRewriter>();
if (!hlo_module->config()
.debug_options()
.xla_gpu_experimental_disable_binary_libraries()) {
for (const CublasPaddingRequirement& requirement :
CublasPaddingRequirements) {
if (cuda_compute_capability.IsAtLeast(
requirement.min_compute_capability)) {
pre_pipeline.AddPass<CublasPadForGemms>(cuda_compute_capability,
requirement.data_type,
requirement.multiple_of);
}
}
}
pre_pipeline.AddPass<HloConstantFolding>();
TF_RETURN_IF_ERROR(pre_pipeline.Run(hlo_module).status());
TF_RETURN_IF_ERROR(GpuCompiler::OptimizeHloPostLayoutAssignment(
hlo_module, stream_exec, options, gpu_target_config, thread_pool));
HloPassPipeline post_pipeline("nvptx post-layout_assignment part 2");
post_pipeline.AddPass<TriangularSolveRewriter>();
TF_RETURN_IF_ERROR(post_pipeline.Run(hlo_module).status());
return absl::OkStatus();
}
bool NVPTXCompiler::RequiresCollectiveScheduleLinearizer(
const HloModule* module, se::StreamExecutor* stream_exec) {
if (stream_exec == nullptr || !GpuConvAlgorithmPicker::IsEnabled(module)) {
return false;
}
for (const HloComputation* comp : module->MakeNonfusionComputations()) {
for (const HloInstruction* inst : comp->instructions()) {
if (GpuConvAlgorithmPicker::IsCandidate(inst)) {
return true;
}
}
}
return false;
}
absl::Status NVPTXCompiler::AddConvAndGemmAutotuningPasses(
HloPassPipeline* pipeline, const se::GpuComputeCapability& gpu_version,
const CompileOptions& options, HloModule* hlo_module,
AutotuneConfig& autotune_config, tsl::thread::ThreadPool* thread_pool) {
if (hlo_module->config()
.debug_options()
.xla_gpu_experimental_disable_binary_libraries()) {
return absl::OkStatus();
}
if (GpuConvAlgorithmPicker::IsEnabled(hlo_module)) {
pipeline->AddPass<GpuConvAlgorithmPicker>(autotune_config);
}
if (!std::get<se::CudaComputeCapability>(gpu_version).IsAtLeastAmpere() ||
options.is_autotuning_compilation) {
pipeline->AddPass<GemmAlgorithmPicker>(autotune_config);
}
return absl::OkStatus();
}
absl::Status NVPTXCompiler::AddGemmFusionAutotuningPasses(
HloPassPipeline* pipeline, HloModule* hlo_module,
AutotuneConfig& autotune_config, tsl::thread::ThreadPool* thread_pool,
const MultiProcessKeyValueStore& key_value_store,
const se::SemanticVersion& toolkit_version) {
pipeline->AddPass<GemmFusionAutotuner>(autotune_config, toolkit_version,
thread_pool, key_value_store);
return absl::OkStatus();
}
absl::Status NVPTXCompiler::AddCustomKernelReplacementPasses(
HloPassPipeline* pipeline, const DebugOptions& debug_options) {
if (debug_options.xla_gpu_enable_cub_radix_sort()) {
pipeline->AddPass<SortRewriter>();
}
return absl::OkStatus();
}
absl::Status NVPTXCompiler::RunCudnnCompilerPasses(
HloModule* module, se::StreamExecutor* stream_exec,
BinaryMap* dnn_compiled_graphs) {
if (module->config()
.debug_options()
.xla_gpu_experimental_disable_binary_libraries()) {
return absl::OkStatus();
}
tsl::profiler::ScopedAnnotation annotation([&] {
return absl::StrFormat("XlaCompileCudnnFusion:#module=%s,program_id=%d#",
module->name(), module->unique_id());
});
CuDnnFusionCompiler fusion_compiler(*stream_exec, *dnn_compiled_graphs);
TF_RETURN_IF_ERROR(fusion_compiler.Run(module).status());
CuDnnCustomCallCompiler call_compiler(*stream_exec, *dnn_compiled_graphs);
return call_compiler.Run(module).status();
}
namespace {
bool MaybeLoadPtxFromFile(const HloModuleConfig module_config,
const HloModule* module, std::string* ptx) {
std::string prefix = xla::FilenameFor(*module, "", *ptx);
std::string matched_filename;
for (const std::string& full_filename :
module_config.debug_options().xla_gpu_ptx_file()) {
auto filename = tsl::io::Basename(full_filename);
if (absl::StartsWith(filename, prefix)) {
matched_filename = full_filename;
VLOG(1) << "RunBackend() - Will load PTX from file: " << full_filename;
break;
}
}
if (!module_config.debug_options().xla_gpu_ptx_file().empty() &&
matched_filename.empty()) {
VLOG(1) << "RunBackend() - For module with prefix '" << prefix
<< "', we did not found a PTX file to load.";
}
if (!matched_filename.empty()) {
std::ifstream ifs(matched_filename, std::ifstream::in);
*ptx = std::string(std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>());
CHECK(!ptx->empty()) << "Empty or non existing PTX file: "
<< matched_filename;
return true;
}
return false;
}
std::unique_ptr<llvm::Module> MaybeLoadLLVMFromFile(const HloModule* module,
llvm::Module* llvm_module) {
if (module == nullptr) {
return nullptr;
}
std::string prefix = xla::FilenameFor(*module, "", "");
auto xla_gpu_llvm_ir_file =
module->config().debug_options().xla_gpu_llvm_ir_file();
auto matched_filename = absl::c_find_if(
xla_gpu_llvm_ir_file, [prefix](const std::string& full_filename) {
return absl::StartsWith(tsl::io::Basename(full_filename), prefix);
});
if (!xla_gpu_llvm_ir_file.empty() &&
matched_filename == std::end(xla_gpu_llvm_ir_file)) {
VLOG(1) << "RunBackend() - For module with prefix '" << prefix
<< "', we did not found a LLVM file to load.";
}
if (matched_filename != std::end(xla_gpu_llvm_ir_file)) {
VLOG(1) << "RunBackend() - Will load LLVM from file: " << *matched_filename;
llvm::LLVMContext& context = llvm_module->getContext();
llvm::SMDiagnostic err;
std::unique_ptr<llvm::Module> loaded_module =
llvm::parseIRFile(*matched_filename, err, context);
if (!loaded_module) {
err.print("ERR", llvm::errs());
LOG(FATAL) << "Failed to load an LLVM file. It is probably invalid LLVM.";
}
llvm_ir::DumpIrIfEnabled(*module, *loaded_module, false);
return loaded_module;
}
return nullptr;
}
}
void WarnIfBadDriverJITVersion() {
static absl::once_flag run_once;
absl::call_once(run_once, [] {
auto version_or_status = se::cuda::Diagnostician::FindKernelDriverVersion();
if (!version_or_status.ok()) {
LOG(WARNING) << "Couldn't read CUDA driver version.";
return;
}
se::cuda::DriverVersion version = version_or_status.value();
if (version < std::make_tuple(396, 20, 0)) {
LOG(WARNING)
<< "*** WARNING *** Invoking the PTX->SASS JIT from driver version "
<< se::cuda::DriverVersionToString(version)
<< ", which is older than 396.20.0. These versions are known to "
"miscompile XLA code, leading to incorrect results or "
"invalid-address errors.\nXLA only uses the driver JIT if it "
"cannot find ptxas; you don't need to update your driver if "
"you can point XLA to ptxas 9.2.88 or newer.";
}
});
}
NVPTXCompiler::NVPTXCompiler()
: GpuCompiler(stream_executor::cuda::kCudaPlatformId, nvptx::TargetTriple(),
nvptx::DataLayout()) {}
HloDataflowAnalysis::CanShareBuffer NVPTXCompiler::GetCanShareBuffer() const {
return &CanShareBufferHint;
}
constexpr const uint8_t kPtxPrefix[] = {'P', 'T', 'X', ':', ' '};
absl::StatusOr<GpuCompiler::BackendCompileResult>
NVPTXCompiler::CompileTargetBinary(const HloModuleConfig& module_config,
llvm::Module* llvm_module,
se::GpuComputeCapability gpu_version,
bool relocatable,
const HloModule* debug_module,
const CompileOptions& options) {
std::unique_ptr<llvm::Module> loaded_module =
MaybeLoadLLVMFromFile(debug_module, llvm_module);
llvm::Module* selected_module = nullptr;
if (loaded_module) {
selected_module = loaded_module.get();
} else {
selected_module = llvm_module;
}
std::string ptx;
if (!(debug_module &&
MaybeLoadPtxFromFile(module_config, debug_module, &ptx))) {
XLA_SCOPED_LOGGING_TIMER_IF(
absl::StrCat(
"NVPTXCompiler::CompileTargetBinary - CompileToPtx for ",
(debug_module != nullptr ? debug_module->name() : "(unknown")),
!options.is_autotuning_compilation);
uint64_t start_usecs = tsl::Env::Default()->NowMicros();
TF_ASSIGN_OR_RETURN(ptx,
nvptx::CompileToPtx(selected_module, gpu_version,
module_config.debug_options()));
uint64_t end_usecs = tsl::Env::Default()->NowMicros();
RecordLlvmPassesAndLlvmToPtxDuration(end_usecs - start_usecs);
}
TF_ASSIGN_OR_RETURN(se::PtxLinkingMethod linking_method,
ChooseLinkingMethod(module_config.debug_options()));
if (linking_method == se::PtxLinkingMethod::kNvJitLink && relocatable) {
VLOG(2) << "Deferring the PTX to CUBIN compilation of the relocatable "
"module to the linking step.";
std::vector<uint8_t> binary;
if (!ptx.empty()) {
binary.reserve(sizeof(kPtxPrefix) + ptx.size() + 1);
binary.insert(binary.end(), kPtxPrefix, kPtxPrefix + sizeof(kPtxPrefix));
binary.insert(binary.end(), ptx.begin(), ptx.end());
binary.emplace_back('\0');
}
return BackendCompileResult{std::move(ptx), std::move(binary)};
}
absl::StatusOr<std::vector<uint8_t>> maybe_cubin =
CompileGpuAsmOrGetCachedResult(
ptx, std::get<se::CudaComputeCapability>(gpu_version), module_config,
(debug_module != nullptr ? debug_module->name() : "(unknown)"),
relocatable, options);
if (!maybe_cubin.ok()) {
return maybe_cubin.status();
}
return BackendCompileResult{std::move(ptx), std::move(maybe_cubin.value())};
}
using stream_executor::PtxCompilationMethod;
std::vector<PtxCompilationMethod> GetSupportedCompilationMethods() {
std::vector<PtxCompilationMethod> methods;
if (se::IsLibNvPtxCompilerSupported()) {
methods.emplace_back(PtxCompilationMethod::kNvPtxCompiler);
}
if (se::IsLibNvJitLinkSupported()) {
methods.emplace_back(PtxCompilationMethod::kNvJitLink);
}
methods.emplace_back(PtxCompilationMethod::kPtxas);
return methods;
}
absl::StatusOr<PtxCompilationMethod> ChooseCompilationMethod(
absl::Span<const PtxCompilationMethod> available_compilation_methods,
const DebugOptions& debug_options, bool relocatable) {
std::vector<PtxCompilationMethod> compilation_methods(
available_compilation_methods.begin(),
available_compilation_methods.end());
VLOG(2) << "Available compilation methods: "
<< absl::StrJoin(compilation_methods, ", ");
auto remove_compilation_method = [&](PtxCompilationMethod method) {
auto it = absl::c_find(compilation_methods, method);
if (it != compilation_methods.end()) {
compilation_methods.erase(it);
}
};
if (!debug_options.xla_gpu_enable_libnvjitlink()) {
VLOG(3) << "Discarding NvJitLink since it is disabled.";
remove_compilation_method(PtxCompilationMethod::kNvJitLink);
}
if (!debug_options.xla_gpu_enable_libnvptxcompiler()) {
VLOG(3) << "Discarding NvPtxCompiler since it is disabled.";
remove_compilation_method(PtxCompilationMethod::kNvPtxCompiler);
}
VLOG(2) << "Supported and enabled compilation methods: "
<< absl::StrJoin(compilation_methods, ", ");
if (relocatable && absl::c_linear_search(compilation_methods,
PtxCompilationMethod::kNvJitLink)) {
VLOG(3) << "Discarding NvJitLink since it can't produce the requested "
"relocatable CUBIN.";
remove_compilation_method(PtxCompilationMethod::kNvJitLink);
}
VLOG(2) << "Considered compilation methods: "
<< absl::StrJoin(compilation_methods, ", ");
if (compilation_methods.empty()) {
return absl::UnavailableError(
"No supported compilation method is available.");
}
return compilation_methods.front();
}
static absl::StatusOr<std::vector<uint8_t>> AssembleOptionsAndCompile(
const std::string& ptx, se::CudaComputeCapability cc,
const HloModuleConfig& hlo_module_config,
GpuCompiler::CompileOptions options, bool relocatable) {
if (ptx.empty()) {
return std::vector<uint8_t>();
}
se::GpuAsmOpts ptxas_config =
PtxOptsFromDebugOptions(hlo_module_config.debug_options());
if (relocatable) {
ptxas_config.extra_flags.push_back("-c");
}
uint64_t start_usecs = tsl::Env::Default()->NowMicros();
bool cancel_if_reg_spill =
hlo_module_config.debug_options()
.xla_gpu_filter_kernels_spilling_registers_on_autotuning() &&
options.is_autotuning_compilation;
std::vector<PtxCompilationMethod> supported_compilation_methods =
GetSupportedCompilationMethods();
TF_ASSIGN_OR_RETURN(
PtxCompilationMethod compilation_method,
ChooseCompilationMethod(supported_compilation_methods,
hlo_module_config.debug_options(), relocatable));
VLOG(2) << "Using compilation method: " << compilation_method;
absl::StatusOr<std::vector<uint8_t>> maybe_cubin = [&] {
switch (compilation_method) {
case PtxCompilationMethod::kNvJitLink:
return se::CompileAndLinkUsingLibNvJitLink(
cc.major, cc.minor,
{se::NvJitLinkInput{
se::NvJitLinkInput::Type::kPtx,
absl::Span<const uint8_t>{
reinterpret_cast<const uint8_t*>(ptx.c_str()),
ptx.size() + 1 }}},
ptxas_config, cancel_if_reg_spill);
case PtxCompilationMethod::kNvPtxCompiler:
return se::CompileGpuAsmUsingLibNvPtxCompiler(
cc.major, cc.minor, ptx.c_str(), ptxas_config, cancel_if_reg_spill);
case PtxCompilationMethod::kPtxas:
return se::CompileGpuAsmUsingPtxAs(cc.major, cc.minor, ptx.c_str(),
ptxas_config, cancel_if_reg_spill);
}
}();
if (maybe_cubin.ok()) {
uint64_t end_usecs = tsl::Env::Default()->NowMicros();
RecordPtxToCubinDuration(end_usecs - start_usecs);
VLOG(1) << "Compiled PTX size: " << ptx.size()
<< "bytes. CUBIN size: " << maybe_cubin.value().size() << "bytes.";
return maybe_cubin;
}
if (maybe_cubin.status().code() == absl::StatusCode::kNotFound) {
if (!hlo_module_config.debug_options()
.xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found()) {
LOG(WARNING) << nvptx::CantFindCudaMessage(
"Can't find ptxas binary in ${CUDA_DIR}/bin. Custom ptxas "
"location can be specified using $PATH.",
hlo_module_config.debug_options().xla_gpu_cuda_data_dir());
LOG(FATAL) << "Can't find ptxas binary. You can pass the flag "
"--xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found "
"to use the GPU driver for compiling ptx instead. However "
"this option is discouraged and can lead to increased "
"memory consumptions and other subtle runtime issues.";
}
LOG_FIRST_N(WARNING, 1) << nvptx::CantFindCudaMessage(
"Can't find ptxas binary in ${CUDA_DIR}/bin. Will back to "
"the GPU driver for PTX -> sass compilation. This is OK so "
"long as you don't see a warning below about an out-of-date "
"driver version. Custom ptxas location can be specified "
"using $PATH.",
hlo_module_config.debug_options().xla_gpu_cuda_data_dir());
WarnIfBadDriverJITVersion();
return maybe_cubin;
}
if (maybe_cubin.status().code() == absl::StatusCode::kCancelled) {
return maybe_cubin;
}
if (maybe_cubin.status().code() == absl::StatusCode::kResourceExhausted) {
return maybe_cubin;
}
if (maybe_cubin.status().code() != absl::StatusCode::kUnimplemented) {
return AppendStatus(
maybe_cubin.status(),
"If the error message indicates that a file could not be written, "
"please verify that sufficient filesystem space is provided.");
}
return maybe_cubin;
}
absl::StatusOr<std::vector<uint8_t>>
NVPTXCompiler::CompileGpuAsmOrGetCachedResult(
const std::string& ptx, se::CudaComputeCapability cc,
const HloModuleConfig& hlo_module_config, absl::string_view module_name,
bool relocatable, const CompileOptions& options) {
XLA_SCOPED_LOGGING_TIMER_IF(
absl::StrCat("NVPTXCompiler::CompileGpuAsmOrGetCachedResult for ",
module_name),
!options.is_autotuning_compilation);
tsl::profiler::ScopedAnnotation annotation([&] {
return absl::StrFormat("XlaCompileGpuAsm:#module=%s#", module_name);
});
tsl::profiler::TraceMe activity("PTX->CUBIN",
tsl::profiler::TraceMeLevel::kInfo);
CompilationCacheValue* cache_value = nullptr;
bool inserted = [&] {
auto flags = CompilationCacheFlags{
hlo_module_config.debug_options()
.xla_gpu_filter_kernels_spilling_registers_on_autotuning()};
absl::MutexLock lock(&mutex_);
auto [iter, inserted] = compilation_cache_.emplace(
std::piecewise_construct,
std::forward_as_tuple(ptx, cc.major, cc.minor, relocatable, flags),
std::forward_as_tuple());
cache_value = &iter->second;
return inserted;
}();
absl::MutexLock lock(&cache_value->mutex);
if (inserted) {
CHECK(!cache_value->compilation_done);
absl::Cleanup mark_compilation_as_done = [cache_value] {
cache_value->compilation_done = true;
cache_value->compilation_done_cv.SignalAll();
};
cache_value->maybe_cubin = AssembleOptionsAndCompile(
ptx, cc, hlo_module_config, options, relocatable);
return cache_value->maybe_cubin;
}
while (!cache_value->compilation_done) {
cache_value->compilation_done_cv.Wait(&cache_value->mutex);
}
return cache_value->maybe_cubin;
}
static bool IsNvlinkEnabled() {
const bool use_nvlink_by_default =
#ifdef TF_DISABLE_NVLINK_BY_DEFAULT
false;
#else
true;
#endif
bool use_nvlink;
TF_CHECK_OK(tsl::ReadBoolFromEnvVar("TF_USE_NVLINK_FOR_PARALLEL_COMPILATION",
use_nvlink_by_default, &use_nvlink));
return use_nvlink;
}
static absl::StatusOr<stream_executor::SemanticVersion> GetAsmCompilerVersion(
const DebugOptions& debug_options, const std::string& preferred_cuda_dir) {
if (debug_options.xla_gpu_enable_libnvptxcompiler() &&
se::IsLibNvPtxCompilerSupported()) {
return stream_executor::GetLibNvPtxCompilerVersion();
}
return se::GetAsmCompilerVersion(preferred_cuda_dir);
}
absl::StatusOr<se::PtxLinkingMethod> NVPTXCompiler::ChooseLinkingMethod(
const DebugOptions& debug_options) {
se::GpuAsmOpts ptxas_config = PtxOptsFromDebugOptions(debug_options);
std::string& preferred_cuda_dir = ptxas_config.preferred_cuda_dir;
using LinkingMethod = se::PtxLinkingMethod;
if (stream_executor::IsLibNvJitLinkSupported() &&
debug_options.xla_gpu_enable_libnvjitlink()) {
return se::PtxLinkingMethod::kNvJitLink;
}
TF_ASSIGN_OR_RETURN(auto asm_compiler_version,
GetAsmCompilerVersion(debug_options, preferred_cuda_dir));
auto nvlink_version = stream_executor::GetNvLinkVersion(preferred_cuda_dir);
if (IsNvlinkEnabled() && nvlink_version.ok() &&
nvlink_version.value() >= asm_compiler_version) {
return LinkingMethod::kNvLink;
}
int ptxas_version =
asm_compiler_version.major() * 1000 + asm_compiler_version.minor() * 10;
TF_ASSIGN_OR_RETURN(int driver_version,
se::gpu::GpuDriver::GetDriverVersion());
if (driver_version >= ptxas_version) {
return LinkingMethod::kDriver;
}
LOG_FIRST_N(WARNING, 1)
<< "The NVIDIA driver's CUDA version is "
<< absl::StrFormat("%d.%d", driver_version / 1000,
(driver_version % 1000) / 10)
<< " which is older than the PTX compiler version "
<< asm_compiler_version
<< ". Because the driver is older than the PTX compiler version, XLA is "
"disabling parallel compilation, which may slow down compilation. "
"You should update your NVIDIA driver or use the NVIDIA-provided "
"CUDA forward compatibility packages.";
return se::PtxLinkingMethod::kNone;
}
absl::StatusOr<bool> NVPTXCompiler::CanUseLinkModules(
const HloModuleConfig& hlo_module_config) {
TF_ASSIGN_OR_RETURN(se::PtxLinkingMethod linking_method,
ChooseLinkingMethod(hlo_module_config.debug_options()));
return linking_method != se::PtxLinkingMethod::kNone;
}
absl::StatusOr<std::vector<uint8_t>> NVPTXCompiler::LinkModules(
se::GpuComputeCapability compute_capability,
se::StreamExecutor* stream_exec, std::vector<std::vector<uint8_t>> modules,
const DebugOptions& debug_options) {
if (modules.empty()) return std::vector<uint8_t>{};
auto cc =
std::get<stream_executor::CudaComputeCapability>(compute_capability);
TF_ASSIGN_OR_RETURN(se::PtxLinkingMethod linking_method,
ChooseLinkingMethod(debug_options));
VLOG(1) << "Linking " << modules.size()
<< " modules with linking method: " << linking_method;
if (linking_method == se::PtxLinkingMethod::kNvJitLink) {
const auto module_contains_ptx =
[](const std::vector<uint8_t>& module) -> bool {
return module.size() >= sizeof(kPtxPrefix) &&
std::equal(std::begin(kPtxPrefix), std::end(kPtxPrefix),
std::begin(module));
};
std::vector<stream_executor::NvJitLinkInput> nvjitlink_inputs;
nvjitlink_inputs.reserve(modules.size());
for (std::vector<uint8_t>& module : modules) {
if (module_contains_ptx(module)) {
nvjitlink_inputs.push_back(
{se::NvJitLinkInput::Type::kPtx,
absl::Span<const uint8_t>(module).subspan(sizeof(kPtxPrefix))});
} else {
nvjitlink_inputs.push_back({se::NvJitLinkInput::Type::kCubin, module});
}
}
se::GpuAsmOpts ptxas_config = PtxOptsFromDebugOptions(debug_options);
return stream_executor::CompileAndLinkUsingLibNvJitLink(
cc.major, cc.minor, nvjitlink_inputs, ptxas_config,
false);
}
std::vector<stream_executor::CubinOrPTXImage> cubin_images;
cubin_images.reserve(modules.size());
for (std::vector<uint8_t>& module : modules) {
{
std::string profile = absl::StrCat("sm_", cc.major, cc.minor);
cubin_images.push_back({std::move(profile), std::move(module)});
}
}
if (linking_method == se::PtxLinkingMethod::kNvLink) {
return LinkUsingNvlink(cc, debug_options.xla_gpu_cuda_data_dir(),
cubin_images);
}
return LinkGpuAsm(cc, se::gpu::ExtractGpuExecutor(stream_exec)->gpu_context(),
cubin_images);
}
}
} | #include "xla/service/gpu/nvptx_compiler.h"
#include <cstdint>
#include <memory>
#include <gtest/gtest.h>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/hlo/utils/hlo_query.h"
#include "xla/service/backend.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/buffer_value.h"
#include "xla/service/gpu/gpu_constants.h"
#include "xla/service/gpu/gpu_hlo_schedule.h"
#include "xla/service/gpu/gpu_latency_hiding_scheduler.h"
#include "xla/service/hlo_ordering.h"
#include "xla/service/logical_buffer.h"
#include "xla/stream_executor/device_description.h"
#include "xla/tests/hlo_test_base.h"
#include "xla/tsl/lib/core/status_test_util.h"
#include "xla/util.h"
#include "xla/xla.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
namespace {
int64_t CountCopies(const HloComputation& computation) {
int64_t count = 0;
for (const auto& instruction : computation.instructions()) {
if (instruction->opcode() == HloOpcode::kCopy) {
count++;
}
}
return count;
}
int64_t CountCopies(const HloModule& module) {
int64_t count = 0;
for (const auto& computation : module.computations()) {
count += CountCopies(*computation);
}
return count;
}
class NVPTXCompilerTest : public HloTestBase {
public:
absl::StatusOr<std::unique_ptr<BufferAssignment>> AssignBuffers(
HloModule* module) {
constexpr uint64_t pointer_size = 4;
const se::DeviceDescription& gpu_device_info =
backend().default_stream_executor()->GetDeviceDescription();
TF_RETURN_IF_ERROR(
ScheduleGpuModule(module, pointer_size, gpu_device_info).status());
auto buffer_size_bytes_function =
[](const BufferValue& buffer_value) -> int64_t {
return GetSizeOfShape(buffer_value.shape(), pointer_size);
};
return BufferAssigner::Run(
module, std::make_unique<SequentialHloOrdering>(module->schedule()),
buffer_size_bytes_function,
[](LogicalBuffer::Color) { return kXlaAllocatedBufferAlignBytes; });
}
};
class NVPTXCompilerTestTriton : public NVPTXCompilerTest {
public:
DebugOptions GetDebugOptionsForTest() override {
DebugOptions debug_options = HloTestBase::GetDebugOptionsForTest();
debug_options.set_xla_gpu_cublas_fallback(false);
return debug_options;
}
};
TEST_F(NVPTXCompilerTest, AllReducePerformedInplace) {
const absl::string_view hlo_string = R"(
HloModule Module, input_output_alias={ {}: (0, {}, may-alias) }
summit {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY entry {
param0 = f32[128] parameter(0)
ROOT allreduce = f32[128] all-reduce(param0),
replica_groups={}, to_apply=summit
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(auto buffer_assignment, AssignBuffers(module.get()));
HloInstruction* all_reduce = module->entry_computation()->root_instruction();
EXPECT_TRUE(buffer_assignment->SharesTopLevelSlice(all_reduce,
all_reduce->operand(0)));
}
TEST_F(NVPTXCompilerTest, AllReducePerformedInplaceTwoOperands) {
const absl::string_view hlo_string = R"(
HloModule Module,
input_output_alias={ {0}: (0, {}, may-alias), {1}: (1, {}, may-alias) }
summit {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY entry {
param0 = f32[128] parameter(0)
param1 = f32[128] parameter(1)
ROOT allreduce = (f32[128], f32[128]) all-reduce(param0, param1),
replica_groups={}, to_apply=summit
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(auto buffer_assignment, AssignBuffers(module.get()));
HloInstruction* all_reduce = module->entry_computation()->root_instruction();
EXPECT_TRUE(buffer_assignment->SharesSliceAtIndex(
all_reduce, {0}, all_reduce->operand(0), {}));
EXPECT_TRUE(buffer_assignment->SharesSliceAtIndex(
all_reduce, {1}, all_reduce->operand(1), {}));
}
TEST_F(NVPTXCompilerTestTriton,
DotDimensionAreSortedBeforePaddingForCublasEnablingTritonFusion) {
const absl::string_view hlo_string = R"(
ENTRY e {
p0 = f16[11,22,33,44] parameter(0)
p1 = s8[11,22,33,44] parameter(1)
p1c = f16[11,22,33,44] convert(p1)
ROOT d = f16[11,22,44,44] dot(p0, p1c),
lhs_batch_dims={0,1}, lhs_contracting_dims={2},
rhs_batch_dims={0,1}, rhs_contracting_dims={2}
})";
se::CudaComputeCapability cc = backend()
.default_stream_executor()
->GetDeviceDescription()
.cuda_compute_capability();
if (cc.IsAtLeastAmpere()) {
MatchOptimizedHlo(hlo_string, R"(
; CHECK: ENTRY
; CHECK-NEXT: parameter
; CHECK-NEXT: parameter
; CHECK-NEXT: __triton_gemm
)");
} else {
MatchOptimizedHlo(hlo_string, R"(
; CHECK-NOT: triton
)");
}
}
TEST_F(NVPTXCompilerTest, RemovesUnnecessaryCopyInPostSchedulingPipelines) {
const absl::string_view hlo_text = R"(
HloModule all_gather_overlapping, is_scheduled=true
condition {
input_tuple = (f32[1,128], f32[2,128], pred[]) parameter(0)
ROOT cond = pred[] get-tuple-element(input_tuple), index=2
}
body {
c0 = f32[] constant(0)
splat_c0 = f32[1,128] broadcast(c0), dimensions={}
input_tuple = (f32[1,128], f32[2,128], pred[]) parameter(0)
param_0 = f32[1,128] get-tuple-element(input_tuple), index=0
add = f32[1,128] add(splat_c0, param_0)
param_1 = f32[2,128] get-tuple-element(input_tuple), index=1
c1_s32 = s32[] constant(1)
c0_s32 = s32[] constant(0)
dynamic-slice = f32[1,128] dynamic-slice(param_1, c1_s32, c0_s32), dynamic_slice_sizes={1,128}
all-gather-start = (f32[1,128], f32[2,128]) all-gather-start(add), channel_id=1337, replica_groups={{0,1}}, dimensions={0}, use_global_device_ids=true
all-gather-done = f32[2,128] all-gather-done(all-gather-start)
copy = f32[2,128] copy(all-gather-done)
cond = pred[] get-tuple-element(input_tuple), index=2
ROOT output_tuple = (f32[1,128], f32[2,128], pred[]) tuple(dynamic-slice, copy, cond)
}
ENTRY main {
param_0 = f32[1,128] parameter(0)
param_1 = f32[2,128] parameter(1)
param_2 = pred[] parameter(2)
copy_param_0 = f32[1,128] copy(param_0)
copy_param_1 = f32[2,128] copy(param_1)
tuple = (f32[1,128], f32[2,128], pred[]) tuple(copy_param_0, copy_param_1, param_2)
while = (f32[1,128], f32[2,128], pred[]) while(tuple), condition=condition, body=body
get-tuple-element = f32[1,128]{1,0} get-tuple-element((f32[1,128]{1,0}, f32[2,128]{1,0}, pred[]) while), index=0
get-tuple-element.1 = f32[2,128]{1,0} get-tuple-element((f32[1,128]{1,0}, f32[2,128]{1,0}, pred[]) while), index=1
get-tuple-element.2 = pred[] get-tuple-element((f32[1,128]{1,0}, f32[2,128]{1,0}, pred[]) while), index=2
copy.3 = pred[] copy(pred[] get-tuple-element.2)
ROOT tuple.2 = (f32[1,128]{1,0}, f32[2,128]{1,0}, pred[]) tuple(f32[1,128]{1,0} get-tuple-element, f32[2,128]{1,0} get-tuple-element.1, pred[] copy.3)
}
)";
auto module = ParseAndReturnVerifiedModule(hlo_text).value();
EXPECT_EQ(CountCopies(*module), 4);
const HloInstruction* while_op = hlo_query::GetFirstInstructionWithOpcode(
*module->entry_computation(), HloOpcode::kWhile);
EXPECT_EQ(while_op->while_body()->root_instruction()->operand(1)->opcode(),
HloOpcode::kCopy);
NVPTXCompiler compiler;
TF_EXPECT_OK(compiler.RunPostSchedulingPipelines(
module.get(), 100000,
backend().default_stream_executor()->GetDeviceDescription()));
EXPECT_EQ(CountCopies(*module), 3);
while_op = hlo_query::GetFirstInstructionWithOpcode(
*module->entry_computation(), HloOpcode::kWhile);
EXPECT_EQ(while_op->while_body()->root_instruction()->operand(1)->opcode(),
HloOpcode::kAllGatherDone);
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/nvptx_compiler.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/nvptx_compiler_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
511d6642-4f1a-4dc8-bc5f-e3d3f7835350 | cpp | google/glog | mock-log | src/mock-log.h | src/mock-log_unittest.cc | #ifndef GLOG_SRC_MOCK_LOG_H_
#define GLOG_SRC_MOCK_LOG_H_
#include <gmock/gmock.h>
#include <string>
#include "glog/logging.h"
#include "utilities.h"
namespace google {
namespace glog_testing {
class ScopedMockLog : public google::LogSink {
public:
ScopedMockLog() { AddLogSink(this); }
~ScopedMockLog() override { RemoveLogSink(this); }
MOCK_METHOD3(Log,
void(google::LogSeverity severity, const std::string& file_path,
const std::string& message));
private:
void send(google::LogSeverity severity, const char* full_filename,
const char* , int ,
const LogMessageTime& , const char* message,
size_t message_len) override {
message_info_.severity = severity;
message_info_.file_path = full_filename;
message_info_.message = std::string(message, message_len);
}
void WaitTillSent() override {
MessageInfo message_info = message_info_;
Log(message_info.severity, message_info.file_path, message_info.message);
}
struct MessageInfo {
google::LogSeverity severity;
std::string file_path;
std::string message;
};
MessageInfo message_info_;
};
}
}
#endif | #include "mock-log.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
namespace {
using google::GLOG_ERROR;
using google::GLOG_INFO;
using google::GLOG_WARNING;
using google::glog_testing::ScopedMockLog;
using std::string;
using testing::_;
using testing::EndsWith;
using testing::InSequence;
using testing::InvokeWithoutArgs;
TEST(ScopedMockLogTest, InterceptsLog) {
ScopedMockLog log;
InSequence s;
EXPECT_CALL(log,
Log(GLOG_WARNING, EndsWith("mock-log_unittest.cc"), "Fishy."));
EXPECT_CALL(log, Log(GLOG_INFO, _, "Working...")).Times(2);
EXPECT_CALL(log, Log(GLOG_ERROR, _, "Bad!!"));
LOG(WARNING) << "Fishy.";
LOG(INFO) << "Working...";
LOG(INFO) << "Working...";
LOG(ERROR) << "Bad!!";
}
void LogBranch() { LOG(INFO) << "Logging a branch..."; }
void LogTree() { LOG(INFO) << "Logging the whole tree..."; }
void LogForest() {
LOG(INFO) << "Logging the entire forest.";
LOG(INFO) << "Logging the entire forest..";
LOG(INFO) << "Logging the entire forest...";
}
TEST(ScopedMockLogTest, LogDuringIntercept) {
ScopedMockLog log;
InSequence s;
EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging a branch..."))
.WillOnce(InvokeWithoutArgs(LogTree));
EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the whole tree..."))
.WillOnce(InvokeWithoutArgs(LogForest));
EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the entire forest."));
EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the entire forest.."));
EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "Logging the entire forest..."));
LogBranch();
}
}
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
testing::InitGoogleTest(&argc, argv);
testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
} | https://github.com/google/glog/blob/de309c08c05382fee0792380de7df1bd65332da2/src/mock-log.h | https://github.com/google/glog/blob/de309c08c05382fee0792380de7df1bd65332da2/src/mock-log_unittest.cc | de309c08c05382fee0792380de7df1bd65332da2 |
c30fe9e6-8cac-4bf9-8a3a-a1ee162dddce | cpp | tensorflow/tensorflow | functionalize_control_flow | tensorflow/compiler/tf2xla/functionalize_control_flow.cc | tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc | #include "tensorflow/compiler/tf2xla/functionalize_control_flow.h"
#include <algorithm>
#include <deque>
#include <stack>
#include <unordered_set>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/types/optional.h"
#include "tensorflow/compiler/tf2xla/functionalize_cond.h"
#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h"
#include "tensorflow/compiler/tf2xla/functionalize_while.h"
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "xla/status_macros.h"
#include "xla/union_find.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/common_runtime/graph_optimizer.h"
#include "tensorflow/core/common_runtime/process_function_library_runtime.h"
#include "tensorflow/core/framework/graph_to_functiondef.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/control_flow.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/dump_graph.h"
namespace tensorflow {
using FuncMap = std::map<string, std::optional<string>>;
using FuncMapIter = std::map<string, std::optional<string>>::const_iterator;
bool FunctionHasBeenProcessed(FuncMapIter func_iter, const FuncMap* func_map) {
return func_iter != func_map->end();
}
bool FunctionHasBeenModified(FuncMapIter func_iter) {
return func_iter->second.has_value();
}
string GetNewFunctionName(
const string& func_name, Node* n,
AssociatedFunctionInfo::AssociatedFunctionType func_type,
FunctionLibraryDefinition* fld) {
return (
func_type ==
AssociatedFunctionInfo::AssociatedFunctionType::kSymbolicGradient
? fld->UniqueFunctionName(absl::StrCat(n->name(), "_f15n_"))
: fld->UniqueFunctionName(absl::StrCat(func_name, "_f15n_")));
}
const string& GetMappedFunctionName(FuncMapIter func_iter) {
DCHECK(func_iter->second.has_value());
return func_iter->second.value();
}
void UpdateFunctionMap(FuncMap* func_map, const string& canonicalized_name,
const string& new_func_name, bool function_modified) {
(*func_map)[canonicalized_name] =
function_modified ? absl::make_optional(new_func_name) : std::nullopt;
}
Status AddFunctionDefToGraphLibrary(
const string& func_name, const AssociatedFunctionInfo& associated_function,
Graph* graph, FunctionLibraryDefinition* fld) {
const OpRegistrationData* op_reg_data;
if (graph->flib_def().LookUp(func_name, &op_reg_data).ok())
return absl::OkStatus();
const FunctionDef* new_fdef = fld->Find(func_name);
DCHECK(new_fdef != nullptr);
FunctionDefLibrary fdef_lib;
*(fdef_lib.add_function()) = *new_fdef;
return graph->AddFunctionLibrary(fdef_lib);
}
Status FunctionalizeControlFlowForFunction(
const string& func_name, const string& new_func_name,
const protobuf::Map<string, tensorflow::AttrValue>& attrs,
FunctionLibraryDefinition* fld, FunctionLibraryRuntime* flr,
FuncMap* func_map, bool* function_modified,
const NodeFilter& node_filter = {});
Status FunctionalizeControlFlowForNodeAssociatedFunctions(
FuncMap* func_map, Graph* graph, FunctionLibraryDefinition* fld,
FunctionLibraryRuntime* flr, bool* any_function_modified,
const NodeFilter& node_filter) {
std::vector<std::pair<Node*, std::vector<AssociatedFunctionInfo>>>
nodes_to_associated_functions;
for (auto* n : graph->nodes()) {
auto associated_functions = GetAssociatedFunctions(*n, fld);
if (!associated_functions.empty()) {
nodes_to_associated_functions.push_back({n, associated_functions});
}
}
for (const auto& pair : nodes_to_associated_functions) {
Node* n = pair.first;
auto associated_functions = pair.second;
for (auto& associated_function : associated_functions) {
DCHECK(associated_function.type() !=
AssociatedFunctionInfo::kFunctionCallNode ||
associated_functions.size() == 1);
string func_name = associated_function.func_name();
string canonicalized_name =
Canonicalize(func_name, AttrSlice(&associated_function.attrs()));
auto func_iter = func_map->find(canonicalized_name);
string new_func_name;
if (FunctionHasBeenProcessed(func_iter, func_map)) {
if (FunctionHasBeenModified(func_iter)) {
*any_function_modified = true;
new_func_name = GetMappedFunctionName(func_iter);
TF_RETURN_IF_ERROR(RewriteAssociatedFunction(
graph, n, fld, associated_function, new_func_name));
}
continue;
}
bool function_modified = false;
new_func_name =
GetNewFunctionName(func_name, n, associated_function.type(), fld);
TF_RETURN_IF_ERROR(FunctionalizeControlFlowForFunction(
func_name, new_func_name, associated_function.attrs(), fld, flr,
func_map, &function_modified, node_filter));
UpdateFunctionMap(func_map, canonicalized_name, new_func_name,
function_modified);
if (function_modified) {
*any_function_modified = true;
TF_RETURN_IF_ERROR(AddFunctionDefToGraphLibrary(
new_func_name, associated_function, graph, fld));
TF_RETURN_IF_ERROR(RewriteAssociatedFunction(
graph, n, fld, associated_function, new_func_name));
}
}
}
return absl::OkStatus();
}
Status FunctionalizeControlFlowForFunction(
const string& func_name, const string& new_func_name,
const protobuf::Map<string, tensorflow::AttrValue>& attrs,
FunctionLibraryDefinition* fld, FunctionLibraryRuntime* flr,
FuncMap* func_map, bool* function_modified, const NodeFilter& node_filter) {
*function_modified = false;
FunctionLibraryRuntime::Handle handle;
TF_RETURN_IF_ERROR(flr->Instantiate(func_name, AttrSlice(&attrs), &handle));
Status ret_status = absl::OkStatus();
auto cleanup_handle = gtl::MakeCleanup([&]() {
auto s = flr->ReleaseHandle(handle);
if (!s.ok()) {
ret_status.Update(s);
}
});
const FunctionBody* body = flr->GetFunctionBody(handle);
Graph* g = body->graph;
bool has_switch_or_merge = false;
for (Node* n : body->graph->nodes()) {
if (node_filter && !node_filter(n)) continue;
if (n->type_string() == "Switch" || n->type_string() == "Merge") {
has_switch_or_merge = true;
break;
}
}
TF_RETURN_IF_ERROR(FunctionalizeControlFlowForNodeAssociatedFunctions(
func_map, g, fld, flr, function_modified, node_filter));
if (has_switch_or_merge) {
*function_modified = true;
if (VLOG_IS_ON(4)) {
DumpGraphToFile(
absl::StrCat("functionalize_control_flow_before_fdef_", func_name),
*g, fld);
}
TF_RETURN_IF_ERROR(FunctionalizeControlFlow(g, fld, node_filter));
if (VLOG_IS_ON(4)) {
DumpGraphToFile(
absl::StrCat("functionalize_control_flow_after_fdef_", func_name), *g,
fld);
}
}
if (*function_modified) {
FunctionDef functionalized_fdef;
TF_RETURN_IF_ERROR(
GraphToFunctionDef(*g, new_func_name, &functionalized_fdef));
if (func_name == new_func_name) {
VLOG(2) << "Replacing function " << func_name;
TF_RETURN_IF_ERROR(
fld->ReplaceFunction(new_func_name, functionalized_fdef));
} else {
VLOG(2) << "Adding function " << new_func_name;
TF_RETURN_IF_ERROR(fld->AddFunctionDef(functionalized_fdef));
}
}
return ret_status;
}
Status FunctionalizeControlFlow(Graph* graph,
FunctionLibraryDefinition* library,
const NodeFilter& node_filter,
bool include_functions) {
VLOG(2) << "FunctionalizeControlFlow (initial): "
<< DumpGraphToFile("functionalize_initial", *graph, library);
if (include_functions) {
auto pflr = std::make_unique<ProcessFunctionLibraryRuntime>(
nullptr, tensorflow::Env::Default(),
nullptr, TF_GRAPH_DEF_VERSION, library,
tensorflow::OptimizerOptions());
FunctionLibraryRuntime* flr =
pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice);
FuncMap func_map;
bool modified = false;
TF_RETURN_IF_ERROR(FunctionalizeControlFlowForNodeAssociatedFunctions(
&func_map, graph, library, flr, &modified, node_filter));
}
TF_RETURN_IF_ERROR(FunctionalizeWhileLoop(graph, library, node_filter));
TF_RETURN_IF_ERROR(FunctionalizeCond(graph, library, node_filter));
VLOG(2) << "FunctionalizeControlFlow (final): "
<< DumpGraphToFile("functionalize_final", *graph, library);
return absl::OkStatus();
}
Status FunctionalizeControlFlowForGraphDef(GraphDef* graph_def,
FunctionLibraryDefinition* library,
const NodeFilter& node_filter,
bool include_functions) {
FunctionDefLibrary function_lib = graph_def->library();
Graph graph(OpRegistry::Global());
TF_RETURN_IF_ERROR(ConvertGraphDefToGraph({}, *graph_def, &graph));
TF_RETURN_IF_ERROR(FunctionalizeControlFlow(&graph, library, node_filter,
include_functions));
graph.ToGraphDef(graph_def);
std::swap(*graph_def->mutable_library(), function_lib);
return absl::OkStatus();
}
Status FunctionalizeControlFlowForXlaPass::Run(
const GraphOptimizationPassOptions& options) {
Graph* graph = options.graph->get();
if (VLOG_IS_ON(4)) {
DumpGraphToFile("functionalize_control_flow_before", *graph,
options.flib_def);
}
const auto* config = &options.session_options->config;
std::unique_ptr<ProcessFunctionLibraryRuntime> pflr(
new ProcessFunctionLibraryRuntime(
nullptr, options.session_options->env, config,
TF_GRAPH_DEF_VERSION, options.flib_def,
config->graph_options().optimizer_options()));
FunctionLibraryRuntime* flr =
pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice);
static std::map<string, string>* kNodeTypeToFunctionAttrMapping =
new std::map<string, string>{
{"_TPUReplicate", "computation"},
{"XlaLaunch", "function"},
};
FuncMap func_map;
bool fld_modified = false;
for (Node* n : graph->nodes()) {
auto it = kNodeTypeToFunctionAttrMapping->find(n->type_string());
if (it == kNodeTypeToFunctionAttrMapping->end()) {
continue;
}
const string func_attr = it->second;
NameAttrList func;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), func_attr, &func));
VLOG(2) << "Graph has node " << n->type_string()
<< ". Corresponding function: " << func.name();
string new_func_name = options.flib_def->UniqueFunctionName(
absl::StrCat(func.name(), "_f15n_"));
bool modified;
TF_RETURN_IF_ERROR(FunctionalizeControlFlowForFunction(
func.name(), new_func_name, func.attr(), options.flib_def, flr,
&func_map, &modified));
if (modified) {
n->ClearAttr(func_attr);
func.set_name(new_func_name);
n->AddAttr(func_attr, func);
fld_modified = true;
}
}
if (false) {
if (VLOG_IS_ON(4)) {
DumpGraphToFile("functionalize_control_flow_before_prune", *graph,
options.flib_def);
}
TF_RETURN_IF_ERROR(
PruneUnreachableFunctionsFromGraph(*graph, options.flib_def));
}
if (VLOG_IS_ON(4)) {
DumpGraphToFile("functionalize_control_flow_after", *graph,
options.flib_def);
}
return absl::OkStatus();
}
} | #include "tensorflow/compiler/tf2xla/functionalize_control_flow.h"
#include <string>
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/control_flow_ops_internal.h"
#include "tensorflow/cc/ops/function_ops.h"
#include "tensorflow/cc/ops/functional_ops.h"
#include "tensorflow/cc/ops/resource_variable_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/compiler/tf2xla/cc/ops/xla_ops.h"
#include "tensorflow/compiler/tf2xla/test_util.h"
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "xla/status_macros.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/graph_to_functiondef.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/graph/validate.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/dump_graph.h"
#include "tensorflow/core/util/equal_graph_def.h"
namespace tensorflow {
namespace {
Status FindIfThenAndElse(const GraphDef& graph, string* op_name,
NameAttrList* then_fn, NameAttrList* else_fn) {
for (const NodeDef& node : graph.node()) {
if (node.op() == "If") {
*op_name = node.name();
const NameAttrList* result;
TF_RETURN_IF_ERROR(GetNodeAttr(node, "then_branch", &result));
*then_fn = *result;
TF_RETURN_IF_ERROR(GetNodeAttr(node, "else_branch", &result));
*else_fn = *result;
return absl::OkStatus();
}
}
return errors::NotFound("No If node found in graph");
}
class ConditionalTestFixture
: public ::testing::TestWithParam<std::tuple<bool, bool>> {
protected:
void SetUp() override {
restrict_to_tpu_nodes_ = std::get<0>(GetParam());
wrap_condition_in_function_ = std::get<1>(GetParam());
}
void RunTest();
private:
void BuildCondGraph(Graph* cond_graph);
void CheckGraphDef(const GraphDef& graph_def,
const FunctionLibraryDefinition& library);
bool restrict_to_tpu_nodes_ = false;
bool wrap_condition_in_function_ = false;
};
TEST_P(ConditionalTestFixture, ConditionalTests) { RunTest(); }
INSTANTIATE_TEST_SUITE_P(
FunctionalizeControlFlow, ConditionalTestFixture,
::testing::Combine(::testing::Bool(), ::testing::Bool()),
[](const ::testing::TestParamInfo<ConditionalTestFixture::ParamType>&
info) {
bool restrict_to_tpu_nodes = std::get<0>(info.param);
bool wrap_cond_in_function = std::get<1>(info.param);
string name =
absl::StrCat(restrict_to_tpu_nodes ? "with_filter" : "without_filter",
wrap_cond_in_function ? "_in_function" : "_in_graph");
return name;
});
void ConditionalTestFixture::BuildCondGraph(Graph* cond_graph) {
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32);
auto y = ops::Placeholder(scope.WithOpName("y"), DT_INT32);
auto less = ops::Less(scope.WithOpName("cond/Less"), y, x);
auto switch_1 = ops::Switch(scope.WithOpName("cond/Switch"), less, less);
auto identity_t =
ops::Identity(scope.WithOpName("cond/Identity"), switch_1.output_true);
auto seventeen = ops::Const<int32>(
scope.WithOpName("cond").WithControlDependencies(identity_t), 17);
auto switch_2 = ops::Switch(scope.WithOpName("cond/Switch"), y, less);
auto mul = ops::Multiply(scope.WithOpName("cond/Mul"), switch_2.output_true,
seventeen);
auto identity_f =
ops::Identity(scope.WithOpName("cond/Identity"), switch_1.output_false);
auto twenty_three = ops::Const<int32>(
scope.WithOpName("cond").WithControlDependencies(identity_f), 23);
auto switch_3 = ops::Switch(scope.WithOpName("cond/Switch"), x, less);
auto add = ops::Add(scope.WithOpName("cond/false/add"),
switch_3.output_false, twenty_three);
auto merge = ops::Merge(scope.WithOpName("cond/Merge"),
std::initializer_list<Input>{add, mul});
TF_EXPECT_OK(scope.ToGraph(cond_graph));
for (Node* n : cond_graph->nodes()) {
std::string dummy_value = "value";
for (absl::string_view attr_name : kAttrsToPropagate) {
n->AddAttr(std::string(attr_name), dummy_value);
}
}
}
}
void ConditionalTestFixture::CheckGraphDef(
const GraphDef& graph_def, const FunctionLibraryDefinition& library) {
string op_name;
NameAttrList then_fn;
NameAttrList else_fn;
TF_EXPECT_OK(FindIfThenAndElse(graph_def, &op_name, &then_fn, &else_fn));
InstantiationResultForTest else_result;
TF_EXPECT_OK(
InstantiateFunctionForTest(else_fn.name(), library, &else_result));
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto y = ops::Placeholder(scope.WithOpName("y"), DT_INT32);
auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32);
auto less = ops::Less(scope.WithOpName("cond/Less"), y, x);
auto if_op =
ops::If(scope.WithOpName(op_name), less,
std::initializer_list<Input>{less, y, x}, {DT_INT32}, then_fn,
else_fn, ops::If::OutputShapes({PartialTensorShape()}));
auto id = ops::Identity(scope.WithOpName("cond/Merge"), if_op.output[0]);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
TF_EXPECT_GRAPH_EQ(expected, graph_def);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg_0 = ops::_Arg(scope.WithOpName("arg0"), DT_BOOL, 0);
auto arg_1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto arg_2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2);
auto identity = ops::Identity(scope.WithOpName("cond/Identity"), arg_0);
auto cond = ops::Const(
scope.WithOpName("cond").WithControlDependencies(identity), 17);
auto mul = ops::Mul(scope.WithOpName("cond/Mul"), arg_1, cond);
auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), mul, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(InstantiateFunctionForTest(then_fn.name(), library, &result));
EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types);
EXPECT_EQ((DataTypeVector{DT_BOOL, DT_INT32, DT_INT32}), result.arg_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg_0 = ops::_Arg(scope.WithOpName("arg0"), DT_BOOL, 0);
auto arg_1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto arg_2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2);
auto identity = ops::Identity(scope.WithOpName("cond/Identity_1"), arg_0);
auto cond_1 = ops::Const(
scope.WithOpName("cond_1").WithControlDependencies(identity), 23);
auto add = ops::Add(scope.WithOpName("cond/false/add"), arg_2, cond_1);
auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(InstantiateFunctionForTest(else_fn.name(), library, &result));
EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types);
EXPECT_EQ((DataTypeVector{DT_BOOL, DT_INT32, DT_INT32}), result.arg_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
for (const NodeDef& node : graph_def.node()) {
if (node.op() == "If") {
for (absl::string_view attr_name : kAttrsToPropagate) {
std::string attr_val;
TF_EXPECT_OK(GetNodeAttr(node, attr_name, &attr_val));
EXPECT_EQ(attr_val, "value");
}
}
}
}
}
void ConditionalTestFixture::RunTest() {
Graph graph(OpRegistry::Global());
if (wrap_condition_in_function_) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
Graph cond_graph(OpRegistry::Global());
BuildCondGraph(&cond_graph);
FunctionDef cond_fdef;
TF_ASSERT_OK(GraphToFunctionDef(cond_graph, "cond_fn", &cond_fdef));
FunctionDefLibrary fdef_lib;
*(fdef_lib.add_function()) = cond_fdef;
TF_ASSERT_OK(scope.graph()->AddFunctionLibrary(fdef_lib));
NodeDef cond_fn;
cond_fn.set_name("cond_node");
cond_fn.set_op("cond_fn");
*(cond_fn.add_input()) = "source";
Status status;
scope.graph()->AddNode(cond_fn, &status);
TF_ASSERT_OK(status);
TF_ASSERT_OK(scope.ToGraph(&graph));
} else {
BuildCondGraph(&graph);
}
FunctionLibraryDefinition library(graph.flib_def());
NodeFilter node_filter =
restrict_to_tpu_nodes_
? [](const Node* n) { return n->attrs().Find("_tpu_replicate"); }
: NodeFilter{};
GraphDef optimized_graph_def;
graph.ToGraphDef(&optimized_graph_def);
TF_ASSERT_OK(FunctionalizeControlFlowForGraphDef(
&optimized_graph_def, &library, node_filter,
wrap_condition_in_function_));
TF_ASSERT_OK(FunctionalizeControlFlow(
&graph, &library, node_filter,
wrap_condition_in_function_));
if (wrap_condition_in_function_) {
auto pflr = std::make_unique<ProcessFunctionLibraryRuntime>(
nullptr, tensorflow::Env::Default(),
nullptr, TF_GRAPH_DEF_VERSION, &library,
tensorflow::OptimizerOptions());
FunctionLibraryRuntime* flr =
pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice);
FunctionLibraryRuntime::Handle handle;
string func_name;
for (Node* n : graph.nodes()) {
if (n->name() == "cond_node") {
func_name = n->type_string();
break;
}
}
TF_ASSERT_OK(flr->Instantiate(func_name, AttrSlice(), &handle));
const FunctionBody* body = flr->GetFunctionBody(handle);
GraphDef graph_def;
body->graph->ToGraphDef(&graph_def);
CheckGraphDef(graph_def, library);
} else {
CheckGraphDef(optimized_graph_def, library);
GraphDef converted_graph_def;
graph.ToGraphDef(&converted_graph_def);
CheckGraphDef(converted_graph_def, library);
}
}
Status FindWhileCondAndBody(const GraphDef& graph, NameAttrList* cond,
NameAttrList* body) {
for (const NodeDef& node : graph.node()) {
if (node.op() == "While") {
const NameAttrList* result;
TF_RETURN_IF_ERROR(GetNodeAttr(node, "cond", &result));
*cond = *result;
TF_RETURN_IF_ERROR(GetNodeAttr(node, "body", &result));
*body = *result;
return absl::OkStatus();
}
}
return errors::NotFound("No While node found in graph");
}
TEST(FunctionalizeControlFlow, OneLoopVar) {
Graph graph(OpRegistry::Global());
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32);
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
auto enter =
ops::internal::Enter(scope.WithOpName("while/Enter"), source, "aloop");
auto enter2 =
ops::internal::Enter(scope.WithOpName("while/Enter2"), source, "aloop");
auto merge = ops::Merge(scope.WithOpName("while/Merge"),
std::initializer_list<Input>{enter, dummy});
auto ten = ops::Const<int32>(
scope.WithOpName("while/Less/y").WithControlDependencies(merge.output),
10);
auto less = ops::Less(scope.WithOpName("while/Less"), merge.output, ten);
auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less);
auto switch_ =
ops::Switch(scope.WithOpName("while/Switch"), merge.output, loop_cond);
auto exit = ops::internal::Exit(scope.WithOpName("while/Exit"),
switch_.output_false);
auto identity =
ops::Identity(scope.WithOpName("while/Identity"), switch_.output_true);
auto one = ops::Const<int32>(
scope.WithOpName("while/add/y").WithControlDependencies(identity), 1);
auto add = ops::Add(scope.WithOpName("while/add"), identity, one);
auto next_iteration =
ops::NextIteration(scope.WithOpName("while/NextIteration"), add);
auto sink = ops::Identity(scope.WithOpName("sink"), exit);
scope.graph()->RemoveNode(dummy.node());
scope.graph()->AddEdge(next_iteration.node(), 0, merge.output.node(), 1);
TF_EXPECT_OK(scope.ToGraph(&graph));
}
for (Node* n : graph.nodes()) {
if (n->name() == "while/Enter") {
graph.AddControlEdge(n, graph.sink_node());
}
}
FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary());
GraphDef optimized_graph_def;
graph.ToGraphDef(&optimized_graph_def);
TF_ASSERT_OK(
FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library));
TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library));
GraphDef converted_graph_def;
graph.ToGraphDef(&converted_graph_def);
for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) {
NameAttrList cond_fn, body_fn;
TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn));
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
auto while_op =
ops::While(scope.WithOpName("while/LoopCond"),
std::initializer_list<Input>{source}, cond_fn, body_fn);
auto sink = ops::Identity(scope.WithOpName("sink"), while_op[0]);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
TF_EXPECT_GRAPH_EQ(expected, graph_def);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto ten = ops::Const<int32>(
scope.WithOpName("while/Less/y").WithControlDependencies(arg), 10);
auto less = ops::Less(scope.WithOpName("while/Less"), arg, ten);
auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(cond_fn.name(), library, &result));
EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types);
EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto identity = ops::Identity(scope.WithOpName("while/Identity"), arg);
auto one = ops::Const<int32>(
scope.WithOpName("while/add/y").WithControlDependencies(identity), 1);
auto add = ops::Add(scope.WithOpName("while/add"), identity, one);
auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(body_fn.name(), library, &result));
EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types);
EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
}
}
FunctionDef GetNoinlineFunctionDef() {
FunctionDef fdef = FunctionDefHelper::Create(
"increment_fn", {"x:int32"}, {"add:int32"}, {},
{
{{"add/y"}, "Const", {}, {{"dtype", DT_INT32}}},
{{"add_0"}, "Add", {"x", "add/y:output:0"}, {{"T", DT_INT32}}},
},
{{"add", "add_0:z:0"}});
(*fdef.mutable_attr())["_noinline"].set_b(true);
return fdef;
}
Status AddNoinlineFunctionToGraph(const string& node_name, Graph* graph) {
FunctionDefLibrary fdef_lib;
*(fdef_lib.add_function()) = GetNoinlineFunctionDef();
TF_RETURN_IF_ERROR(graph->AddFunctionLibrary(fdef_lib));
NodeDef increment_fn;
increment_fn.set_name(node_name);
increment_fn.set_op("increment_fn");
*increment_fn.add_input() = "while/Identity";
*increment_fn.add_input() = "^while/Identity";
Status status;
graph->AddNode(increment_fn, &status);
return status;
}
TEST(FunctionalizeControlFlow, NoinlineLoopBody) {
const string& noinline_node_name = "while/increment_fn";
Graph graph(OpRegistry::Global());
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32);
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
auto enter = ops::internal::Enter(scope.WithOpName("while/Enter"), source,
"while/while_context");
auto merge = ops::Merge(scope.WithOpName("while/Merge"),
std::initializer_list<Input>{enter, dummy});
auto ten = ops::Const<int32>(
scope.WithOpName("while/Less/y").WithControlDependencies(merge.output),
10);
auto less = ops::Less(scope.WithOpName("while/Less"), merge.output, ten);
auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less);
auto switch_ =
ops::Switch(scope.WithOpName("while/Switch"), merge.output, loop_cond);
auto exit = ops::internal::Exit(scope.WithOpName("while/Exit"),
switch_.output_false);
auto identity =
ops::Identity(scope.WithOpName("while/Identity"), switch_.output_true);
TF_ASSERT_OK(AddNoinlineFunctionToGraph(noinline_node_name, scope.graph()));
NodeDef next_iter;
next_iter.set_name("while/NextIteration");
next_iter.set_op("NextIteration");
*next_iter.add_input() = noinline_node_name;
(*next_iter.mutable_attr())["T"].set_type(DT_INT32);
Status status;
Node* n = scope.graph()->AddNode(next_iter, &status);
TF_ASSERT_OK(status);
scope.graph()->RemoveNode(dummy.node());
scope.graph()->AddEdge(n, 0, merge.output.node(), 1);
TF_ASSERT_OK(scope.ToGraph(&graph));
}
FunctionLibraryDefinition library(graph.flib_def());
GraphDef optimized_graph_def;
graph.ToGraphDef(&optimized_graph_def);
*(optimized_graph_def.mutable_library()->add_function()) =
GetNoinlineFunctionDef();
TF_ASSERT_OK(
FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library));
TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library));
GraphDef converted_graph_def;
graph.ToGraphDef(&converted_graph_def);
for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) {
NameAttrList cond_fn, body_fn;
TF_ASSERT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn));
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
auto while_op =
ops::While(scope.WithOpName("while/LoopCond"),
std::initializer_list<Input>{source}, cond_fn, body_fn);
GraphDef expected;
TF_ASSERT_OK(scope.ToGraphDef(&expected));
TF_EXPECT_GRAPH_EQ(expected, graph_def);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
TF_ASSERT_OK(
AddNoinlineFunctionToGraph(noinline_node_name, scope.graph()));
auto identity = ops::Identity(scope.WithOpName("while/Identity"), arg);
NodeDef retval;
retval.set_name("retval0_RetVal");
retval.set_op(FunctionLibraryDefinition::kRetOp);
*retval.add_input() = noinline_node_name;
(*retval.mutable_attr())["T"].set_type(DT_INT32);
(*retval.mutable_attr())["index"].set_i(0);
Status status;
scope.graph()->AddNode(retval, &status);
TF_ASSERT_OK(status);
GraphDef expected;
TF_ASSERT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(body_fn.name(), library, &result));
EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types);
EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types);
expected.clear_library();
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
}
}
TEST(FunctionalizeControlFlow, MissingFunctionDefInLibrary) {
const string& noinline_node_name = "while/increment_fn";
Graph graph(OpRegistry::Global());
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
auto identity = ops::Identity(scope.WithOpName("while/Identity"), source);
TF_ASSERT_OK(AddNoinlineFunctionToGraph(noinline_node_name, scope.graph()));
TF_ASSERT_OK(scope.ToGraph(&graph));
}
FunctionLibraryDefinition library(graph.flib_def());
GraphDef graph_def;
graph.ToGraphDef(&graph_def);
graph_def.clear_library();
Status status = FunctionalizeControlFlowForGraphDef(&graph_def, &library);
EXPECT_EQ(tensorflow::error::NOT_FOUND, status.code());
}
TEST(FunctionalizeControlFlow, OneLoopVarWithoutExit) {
Graph graph(OpRegistry::Global());
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32);
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
auto enter =
ops::internal::Enter(scope.WithOpName("while/Enter"), source, "aloop");
auto merge = ops::Merge(scope.WithOpName("while/Merge"),
std::initializer_list<Input>{enter, dummy});
auto ten = ops::Const<int32>(
scope.WithOpName("while/Less/y").WithControlDependencies(merge.output),
10);
auto less = ops::Less(scope.WithOpName("while/Less"), merge.output, ten);
auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less);
auto switch_ =
ops::Switch(scope.WithOpName("while/Switch"), merge.output, loop_cond);
auto identity =
ops::Identity(scope.WithOpName("while/Identity"), switch_.output_true);
auto one = ops::Const<int32>(
scope.WithOpName("while/add/y").WithControlDependencies(identity), 1);
auto add = ops::Add(scope.WithOpName("while/add"), identity, one);
auto next_iteration =
ops::NextIteration(scope.WithOpName("while/NextIteration"), add);
scope.graph()->RemoveNode(dummy.node());
scope.graph()->AddEdge(next_iteration.node(), 0, merge.output.node(), 1);
TF_EXPECT_OK(scope.ToGraph(&graph));
}
FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary());
GraphDef optimized_graph_def;
graph.ToGraphDef(&optimized_graph_def);
TF_ASSERT_OK(
FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library));
TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library));
GraphDef converted_graph_def;
graph.ToGraphDef(&converted_graph_def);
for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) {
NameAttrList cond_fn, body_fn;
TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn));
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32);
auto while_op =
ops::While(scope.WithOpName("while/LoopCond"),
std::initializer_list<Input>{source}, cond_fn, body_fn);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
TF_EXPECT_GRAPH_EQ(expected, graph_def);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto ten = ops::Const<int32>(
scope.WithOpName("while/Less/y").WithControlDependencies(arg), 10);
auto less = ops::Less(scope.WithOpName("while/Less"), arg, ten);
auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(cond_fn.name(), library, &result));
EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types);
EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto identity = ops::Identity(scope.WithOpName("while/Identity"), arg);
auto one = ops::Const<int32>(
scope.WithOpName("while/add/y").WithControlDependencies(identity), 1);
auto add = ops::Add(scope.WithOpName("while/add"), identity, one);
auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(body_fn.name(), library, &result));
EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types);
EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
}
}
TEST(FunctionalizeControlFlow, TwoLoopVars) {
Graph graph(OpRegistry::Global());
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32);
auto x = ops::Placeholder(scope.WithOpName("Placeholder/x"), DT_INT32);
auto y = ops::Placeholder(scope.WithOpName("Placeholder/y"), DT_INT32);
auto enter_x =
ops::internal::Enter(scope.WithOpName("while/Enter/x"), x, "aloop");
auto enter_y =
ops::internal::Enter(scope.WithOpName("while/Enter/y"), y, "aloop");
auto merge_x = ops::Merge(scope.WithOpName("while/Merge/x"),
std::initializer_list<Input>{enter_x, dummy});
auto merge_y = ops::Merge(scope.WithOpName("while/Merge/y"),
std::initializer_list<Input>{enter_y, dummy});
auto three = ops::Const<int32>(scope.WithOpName("while/cond/three")
.WithControlDependencies(merge_x.output),
3);
auto cond_add =
ops::Add(scope.WithOpName("while/cond/Add"), merge_x.output, three);
auto ten = ops::Const<int32>(scope.WithOpName("while/cond/ten")
.WithControlDependencies(merge_x.output),
10);
auto less = ops::Less(scope.WithOpName("while/cond/Less"), cond_add, ten);
auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less);
auto switch_x = ops::Switch(scope.WithOpName("while/Switch/x"),
merge_x.output, loop_cond);
auto switch_y = ops::Switch(scope.WithOpName("while/Switch/y"),
merge_y.output, loop_cond);
auto exit_x = ops::internal::Exit(scope.WithOpName("while/Exit/x"),
switch_x.output_false);
auto exit_y = ops::internal::Exit(scope.WithOpName("while/Exit/y"),
switch_y.output_false);
auto identity_x = ops::Identity(scope.WithOpName("while/Identity/x"),
switch_x.output_true);
auto identity_y = ops::Identity(scope.WithOpName("while/Identity/y"),
switch_y.output_true);
auto one = ops::Const<int32>(
scope.WithOpName("while/add/one").WithControlDependencies(identity_x),
1);
auto two = ops::Const<int32>(
scope.WithOpName("while/mul/two").WithControlDependencies(identity_x),
2);
auto add = ops::Add(scope.WithOpName("while/add"), identity_x, one);
auto mul = ops::Add(scope.WithOpName("while/mul"), identity_y, two);
auto next_iteration_x =
ops::NextIteration(scope.WithOpName("while/NextIteration/x"), add);
auto next_iteration_y =
ops::NextIteration(scope.WithOpName("while/NextIteration/y"), mul);
auto sink_x = ops::Identity(scope.WithOpName("sink_x"), exit_x);
auto sink_y = ops::Identity(scope.WithOpName("sink_y"), exit_y);
scope.graph()->RemoveNode(dummy.node());
scope.graph()->AddEdge(next_iteration_x.node(), 0, merge_x.output.node(),
1);
scope.graph()->AddEdge(next_iteration_y.node(), 0, merge_y.output.node(),
1);
TF_EXPECT_OK(scope.ToGraph(&graph));
}
FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary());
GraphDef optimized_graph_def;
graph.ToGraphDef(&optimized_graph_def);
TF_ASSERT_OK(
FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library));
TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library));
GraphDef converted_graph_def;
graph.ToGraphDef(&converted_graph_def);
for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) {
NameAttrList cond_fn, body_fn;
TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn));
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto x = ops::Placeholder(scope.WithOpName("Placeholder/x"), DT_INT32);
auto y = ops::Placeholder(scope.WithOpName("Placeholder/y"), DT_INT32);
auto while_op =
ops::While(scope.WithOpName("while/LoopCond"),
std::initializer_list<Input>{x, y}, cond_fn, body_fn);
auto sink_x = ops::Identity(scope.WithOpName("sink_x"), while_op[0]);
auto sink_y = ops::Identity(scope.WithOpName("sink_y"), while_op[1]);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
TF_EXPECT_GRAPH_EQ(expected, graph_def);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto three = ops::Const<int32>(scope.WithOpName("while/cond/three")
.WithControlDependencies(arg0.output),
3);
auto cond_add =
ops::Add(scope.WithOpName("while/cond/Add"), arg0.output, three);
auto ten = ops::Const<int32>(scope.WithOpName("while/cond/ten")
.WithControlDependencies(arg0.output),
10);
auto less = ops::Less(scope.WithOpName("while/cond/Less"), cond_add, ten);
auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(cond_fn.name(), library, &result));
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32}), result.arg_types);
EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto identity_x =
ops::Identity(scope.WithOpName("while/Identity/x"), arg0);
auto identity_y =
ops::Identity(scope.WithOpName("while/Identity/y"), arg1);
auto one = ops::Const<int32>(
scope.WithOpName("while/add/one").WithControlDependencies(identity_x),
1);
auto two = ops::Const<int32>(
scope.WithOpName("while/mul/two").WithControlDependencies(identity_x),
2);
auto add = ops::Add(scope.WithOpName("while/add"), identity_x, one);
auto mul = ops::Add(scope.WithOpName("while/mul"), identity_y, two);
auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0);
auto retval1 = ops::_Retval(scope.WithOpName("retval1_RetVal"), mul, 1);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(body_fn.name(), library, &result));
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32}), result.arg_types);
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32}), result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
}
}
class ComplexTestFixture
: public ::testing::TestWithParam<std::tuple<bool, bool, bool>> {
protected:
void SetUp() override {
restrict_to_tpu_nodes_ = std::get<0>(GetParam());
mark_inner_loop_tpu_ = std::get<1>(GetParam());
mark_outer_loop_tpu_ = std::get<2>(GetParam());
}
void RunTest();
private:
void CheckOuterNodesFunctionalized(const GraphDef& graph_def,
const FunctionLibraryDefinition& library,
NameAttrList& inner_cond_fn,
NameAttrList& inner_body_fn);
void CheckInnerNodesFunctionalized(const GraphDef& graph_def,
const FunctionLibraryDefinition& library,
const NameAttrList& inner_cond_fn,
const NameAttrList& inner_body_fn);
bool restrict_to_tpu_nodes_ = false;
bool mark_inner_loop_tpu_ = false;
bool mark_outer_loop_tpu_ = false;
};
TEST_P(ComplexTestFixture, ComplexTests) { RunTest(); }
INSTANTIATE_TEST_SUITE_P(
FunctionalizeControlFlow, ComplexTestFixture,
::testing::Combine(::testing::Bool(), ::testing::Bool(), ::testing::Bool()),
[](const ::testing::TestParamInfo<ComplexTestFixture::ParamType>& info) {
bool restrict_to_tpu_nodes = std::get<0>(info.param);
bool mark_inner_loop_tpu = std::get<1>(info.param);
bool mark_outer_loop_tpu = std::get<2>(info.param);
string node_string;
if (mark_inner_loop_tpu && mark_outer_loop_tpu)
node_string = "both_loops_tpu";
else if (!mark_inner_loop_tpu && !mark_outer_loop_tpu)
node_string = "no_loop_tpu";
else
node_string = mark_inner_loop_tpu ? "inner_loop_tpu" : "outer_loop_tpu";
string name = absl::StrCat(
restrict_to_tpu_nodes ? "restricted_" : "unrestricted_", node_string);
return name;
});
void ComplexTestFixture::RunTest() {
Graph graph(OpRegistry::Global());
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32);
auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32);
auto three = ops::Const<int32>(scope.WithOpName("three"), 3);
auto y = ops::Add(scope.WithOpName("y"), x, three);
auto var = ops::VarHandleOp(scope.WithOpName("Variable"), DT_INT32,
TensorShape({}));
auto zero = ops::Const<int32>(scope.WithOpName("outer/Const"), 0);
auto enter_i =
ops::internal::Enter(scope.WithOpName("outer/Enter_i"), zero, "outer");
auto merge_i = ops::Merge(scope.WithOpName("outer/Merge_i"),
std::initializer_list<Input>{enter_i, dummy});
auto ten = ops::Const<int32>(scope.WithOpName("outer/Less/y")
.WithControlDependencies(merge_i.output),
10);
auto less_i =
ops::Less(scope.WithOpName("outer/Less_i"), merge_i.output, ten);
auto outer_loop_cond =
ops::LoopCond(scope.WithOpName("outer/LoopCond"), less_i);
auto switch_i = ops::Switch(scope.WithOpName("outer/Switch"),
merge_i.output, outer_loop_cond);
auto exit_i = ops::internal::Exit(scope.WithOpName("outer/Exit"),
switch_i.output_false);
auto identity_i =
ops::Identity(scope.WithOpName("outer/Identity"), switch_i.output_true);
auto enter_x_outer =
ops::internal::Enter(scope.WithOpName("outer/Enter_x"), x, "outer",
ops::internal::Enter::Attrs().IsConstant(true));
auto enter_k_outer =
ops::internal::Enter(scope.WithOpName("outer/Enter_k"), y, "outer",
ops::internal::Enter::Attrs().IsConstant(true));
auto enter_var_outer =
ops::internal::Enter(scope.WithOpName("outer/Enter_var"), var, "outer",
ops::internal::Enter::Attrs().IsConstant(true));
auto one_j = ops::Const<int32>(
scope.WithOpName("outer/j").WithControlDependencies(identity_i), 1);
auto enter_j = ops::internal::Enter(scope.WithOpName("outer/inner/Enter_j"),
one_j, "inner");
auto enter_k =
ops::internal::Enter(scope.WithOpName("outer/inner/Enter_k")
.WithControlDependencies(identity_i),
enter_k_outer, "inner");
auto enter_x = ops::internal::Enter(
scope.WithOpName("outer/inner/Enter_x"), enter_x_outer, "inner",
ops::internal::Enter::Attrs().IsConstant(true));
auto enter_var = ops::internal::Enter(
scope.WithOpName("outer/inner/Enter_var"), enter_var_outer, "inner",
ops::internal::Enter::Attrs().IsConstant(true));
auto merge_j = ops::Merge(scope.WithOpName("outer/inner/Merge_j"),
std::initializer_list<Input>{enter_j, dummy});
auto merge_k = ops::Merge(scope.WithOpName("outer/inner/Merge_k"),
std::initializer_list<Input>{enter_k, dummy});
auto five = ops::Const<int32>(scope.WithOpName("outer/inner/Five")
.WithControlDependencies(merge_j.output),
5);
auto less_j =
ops::Less(scope.WithOpName("outer/inner/Less_j"), merge_j.output, five);
auto loop_cond =
ops::LoopCond(scope.WithOpName("outer/inner/LoopCond"), less_j);
auto switch_j = ops::Switch(scope.WithOpName("outer/inner/Switch_j"),
merge_j.output, loop_cond);
auto switch_k = ops::Switch(scope.WithOpName("outer/inner/Switch_k"),
merge_k.output, loop_cond);
auto exit_j = ops::internal::Exit(scope.WithOpName("outer/inner/Exit_j"),
switch_j.output_false);
auto exit_k = ops::internal::Exit(scope.WithOpName("outer/inner/Exit_k"),
switch_k.output_false);
auto identity_j = ops::Identity(scope.WithOpName("outer/inner/Identity_j"),
switch_j.output_true);
auto identity_k = ops::Identity(scope.WithOpName("outer/inner/Identity_k"),
switch_k.output_true);
auto mul_jk =
ops::Mul(scope.WithOpName("outer/inner/mul"), identity_j, identity_k);
auto add_jkx =
ops::Add(scope.WithOpName("outer/inner/add"), mul_jk, enter_x);
auto assign = ops::AssignAddVariableOp(
scope.WithOpName("outer/inner/assign_add"), enter_var, add_jkx);
auto one = ops::Const<int32>(
scope.WithOpName("outer/inner/One")
.WithControlDependencies(
absl::Span<const Operation>{assign.operation}),
1);
auto add_j =
ops::Add(scope.WithOpName("outer/inner/add_j"), identity_j, one);
auto next_iteration_j = ops::NextIteration(
scope.WithOpName("outer/inner/NextIteration_j"), add_j);
auto next_iteration_k = ops::NextIteration(
scope.WithOpName("outer/inner/NextIteration_k"), identity_k);
auto one_outer = ops::Const<int32>(
scope.WithOpName("outer/add/y").WithControlDependencies(identity_i), 1);
auto add_i =
ops::Add(scope.WithOpName("outer/add")
.WithControlDependencies(absl::Span<const Operation>{
exit_j.output.op(), exit_k.output.op()}),
identity_i, one_outer);
auto next_iteration_i =
ops::NextIteration(scope.WithOpName("outer/NextIteration"), add_i);
auto sink = ops::Identity(scope.WithOpName("sink"), exit_i);
scope.graph()->RemoveNode(dummy.node());
scope.graph()->AddEdge(next_iteration_i.node(), 0, merge_i.output.node(),
1);
scope.graph()->AddEdge(next_iteration_j.node(), 0, merge_j.output.node(),
1);
scope.graph()->AddEdge(next_iteration_k.node(), 0, merge_k.output.node(),
1);
TF_EXPECT_OK(scope.ToGraph(&graph));
}
for (Node* n : graph.nodes()) {
string name = n->name();
bool is_inner_node = name.find("outer/inner/") != string::npos;
bool is_outer_node = !is_inner_node && name.find("outer/") != string::npos;
if ((is_inner_node && mark_inner_loop_tpu_) ||
(is_outer_node && mark_outer_loop_tpu_)) {
n->AddAttr("_tpu_replicate", "cluster");
}
}
FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary());
GraphDef orig_graph_def, optimized_graph_def;
graph.ToGraphDef(&orig_graph_def);
optimized_graph_def = orig_graph_def;
NodeFilter node_filter =
restrict_to_tpu_nodes_
? [](const Node* n) { return n->attrs().Find("_tpu_replicate"); }
: NodeFilter{};
Status status1 = FunctionalizeControlFlowForGraphDef(&optimized_graph_def,
&library, node_filter);
Status status2 = FunctionalizeControlFlow(&graph, &library, node_filter);
ASSERT_EQ(status1, status2);
if (restrict_to_tpu_nodes_ && mark_outer_loop_tpu_ && !mark_inner_loop_tpu_) {
ASSERT_EQ(errors::IsInternal(status1), true);
return;
} else {
TF_ASSERT_OK(status1);
}
GraphDef optimized_converted_graph_def;
graph.ToGraphDef(&optimized_converted_graph_def);
for (const GraphDef& graph_def :
{optimized_graph_def, optimized_converted_graph_def}) {
NameAttrList inner_cond_fn, inner_body_fn;
if (!restrict_to_tpu_nodes_ ||
(restrict_to_tpu_nodes_ && mark_outer_loop_tpu_ &&
mark_inner_loop_tpu_)) {
CheckOuterNodesFunctionalized(graph_def, library, inner_cond_fn,
inner_body_fn);
CheckInnerNodesFunctionalized(graph_def, library, inner_cond_fn,
inner_body_fn);
} else {
if (!mark_outer_loop_tpu_ && !mark_inner_loop_tpu_) {
TF_EXPECT_GRAPH_EQ(orig_graph_def, graph_def);
} else if (!mark_outer_loop_tpu_ && mark_inner_loop_tpu_) {
TF_EXPECT_OK(
FindWhileCondAndBody(graph_def, &inner_cond_fn, &inner_body_fn));
CheckInnerNodesFunctionalized(graph_def, library, inner_cond_fn,
inner_body_fn);
}
}
}
}
void ComplexTestFixture::CheckOuterNodesFunctionalized(
const GraphDef& graph_def, const FunctionLibraryDefinition& library,
NameAttrList& inner_cond_fn, NameAttrList& inner_body_fn) {
NameAttrList outer_cond_fn, outer_body_fn;
TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &outer_cond_fn, &outer_body_fn));
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32);
auto three = ops::Const<int32>(scope.WithOpName("three"), 3);
auto y = ops::Add(scope.WithOpName("y"), x, three);
auto var = ops::VarHandleOp(scope.WithOpName("Variable"), DT_INT32,
TensorShape({}));
auto zero = ops::Const<int32>(scope.WithOpName("outer/Const"), 0);
auto while_op = ops::While(scope.WithOpName("outer/LoopCond"),
std::initializer_list<Input>{zero, y, x, var},
outer_cond_fn, outer_body_fn);
auto sink = ops::Identity(scope.WithOpName("sink"), while_op[0]);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
TF_EXPECT_GRAPH_EQ(expected, graph_def);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2);
auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3);
auto ten = ops::Const<int32>(
scope.WithOpName("outer/Less/y").WithControlDependencies(arg0.output),
10);
auto less = ops::Less(scope.WithOpName("outer/Less_i"), arg0, ten);
auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(outer_cond_fn.name(), library, &result));
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}),
result.arg_types);
EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
{
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(outer_body_fn.name(), library, &result));
TF_EXPECT_OK(
FindWhileCondAndBody(result.gdef, &inner_cond_fn, &inner_body_fn));
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2);
auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3);
auto identity_i = ops::Identity(scope.WithOpName("outer/Identity"), arg0);
auto one_j = ops::Const<int32>(
scope.WithOpName("outer/j").WithControlDependencies(identity_i), 1);
auto while_op =
ops::While(scope.WithOpName("outer/inner/LoopCond"),
std::initializer_list<Input>{one_j, arg1, arg2, arg3},
inner_cond_fn, inner_body_fn);
auto one_outer = ops::Const<int32>(
scope.WithOpName("outer/add/y").WithControlDependencies(identity_i), 1);
auto add_i =
ops::Add(scope.WithOpName("outer/add")
.WithControlDependencies(absl::Span<const Operation>{
while_op[0].op(), while_op[1].op()}),
identity_i, one_outer);
auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add_i, 0);
auto retval1 = ops::_Retval(scope.WithOpName("retval1_RetVal"), arg1, 1);
auto retval2 = ops::_Retval(scope.WithOpName("retval2_RetVal"), arg2, 2);
auto retval3 = ops::_Retval(scope.WithOpName("retval3_RetVal"), arg3, 3);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}),
result.arg_types);
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}),
result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
}
void ComplexTestFixture::CheckInnerNodesFunctionalized(
const GraphDef& graph_def, const FunctionLibraryDefinition& library,
const NameAttrList& inner_cond_fn, const NameAttrList& inner_body_fn) {
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2);
auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3);
auto five = ops::Const<int32>(
scope.WithOpName("outer/inner/Five").WithControlDependencies(arg0), 5);
auto less_j = ops::Less(scope.WithOpName("outer/inner/Less_j"), arg0, five);
auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less_j, 0);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(inner_cond_fn.name(), library, &result));
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}),
result.arg_types);
EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1);
auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2);
auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3);
auto identity_j =
ops::Identity(scope.WithOpName("outer/inner/Identity_j"), arg0);
auto identity_k =
ops::Identity(scope.WithOpName("outer/inner/Identity_k"), arg1);
auto mul_jk =
ops::Mul(scope.WithOpName("outer/inner/mul"), identity_j, identity_k);
auto add_jkx = ops::Add(scope.WithOpName("outer/inner/add"), mul_jk, arg2);
auto assign = ops::AssignAddVariableOp(
scope.WithOpName("outer/inner/assign_add"), arg3, add_jkx);
auto one = ops::Const<int32>(
scope.WithOpName("outer/inner/One")
.WithControlDependencies(
absl::Span<const Operation>{assign.operation}),
1);
auto add_j =
ops::Add(scope.WithOpName("outer/inner/add_j"), identity_j, one);
auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add_j, 0);
auto retval1 =
ops::_Retval(scope.WithOpName("retval1_RetVal"), identity_k, 1);
auto retval2 = ops::_Retval(scope.WithOpName("retval2_RetVal"), arg2, 2);
auto retval3 = ops::_Retval(scope.WithOpName("retval3_RetVal"), arg3, 3);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
InstantiationResultForTest result;
TF_EXPECT_OK(
InstantiateFunctionForTest(inner_body_fn.name(), library, &result));
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}),
result.arg_types);
EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}),
result.ret_types);
TF_EXPECT_GRAPH_EQ(expected, result.gdef);
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/functionalize_control_flow.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
1ebc940d-e527-4074-8f1f-bd379b98050d | cpp | tensorflow/tensorflow | hlo_matchers | tensorflow/compiler/mlir/lite/stablehlo/transforms/hlo_matchers.cc | third_party/xla/xla/hlo/utils/hlo_matchers_test.cc | #include "tensorflow/compiler/mlir/lite/stablehlo/transforms/hlo_matchers.h"
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <optional>
#include <utility>
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributeInterfaces.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypeInterfaces.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Value.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Transforms/DialectConversion.h"
#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h"
namespace mlir {
namespace odml {
namespace {
class StridedArrayViewBase {
protected:
StridedArrayViewBase(ArrayRef<int64_t> shape, ArrayRef<int64_t> index,
int64_t axis) {
assert(shape.size() == index.size());
assert(axis < shape.size());
assert(axis >= 0);
assert(index[axis] == 0);
offset_ = IndexToOffset(shape, index);
stride_ = StrideForAxis(shape, axis);
size_ = shape[axis];
}
int64_t size() const { return size_; }
static std::optional<SmallVector<int64_t>> NextTensorIndex(
SmallVector<int64_t> index, ArrayRef<int64_t> shape, int64_t fixed_axis) {
#ifndef NDEBUG
assert(shape.size() == index.size());
assert(fixed_axis < shape.size());
assert(fixed_axis >= 0);
assert(index[fixed_axis] == 0);
for (size_t i = 0; i < shape.size(); ++i) {
assert(index[i] < shape[i]);
assert(index[i] >= 0);
}
#endif
for (int64_t dim = shape.size() - 1; dim >= 0; --dim) {
if (dim == fixed_axis) continue;
++index[dim];
if (index[dim] < shape[dim]) return std::move(index);
index[dim] = 0;
}
return std::nullopt;
}
protected:
int64_t OffsetForIndex(int64_t i) const { return offset_ + i * stride_; }
private:
static int64_t StrideForAxis(ArrayRef<int64_t> shape, int64_t axis) {
int64_t stride = 1;
for (int64_t dim = shape.size() - 1; dim > axis; --dim) {
stride *= shape[dim];
}
return stride;
}
static int64_t IndexToOffset(ArrayRef<int64_t> shape,
ArrayRef<int64_t> index) {
#ifndef NDEBUG
assert(shape.size() == index.size());
for (size_t i = 0; i < shape.size(); ++i) {
assert(index[i] < shape[i]);
assert(index[i] >= 0);
}
#endif
int64_t offset = 0;
int64_t stride = 1;
for (int64_t dim = shape.size() - 1; dim >= 0; --dim) {
offset += index[dim] * stride;
stride *= shape[dim];
}
return offset;
}
int64_t offset_;
int64_t stride_;
int64_t size_;
};
template <typename T>
class StridedArrayView;
template <>
class StridedArrayView<DenseIntElementsAttr> : StridedArrayViewBase {
public:
StridedArrayView(const DenseIntElementsAttr& data, ArrayRef<int64_t> shape,
ArrayRef<int64_t> index, int64_t axis)
: StridedArrayViewBase(shape, index, axis), data_(data) {
int64_t element_count = 1;
for (int64_t i = 0, e = shape.size(); i < e; ++i) {
element_count *= shape[i];
}
assert(data.getNumElements() == element_count);
}
using StridedArrayViewBase::NextTensorIndex;
using StridedArrayViewBase::size;
int64_t operator[](int64_t i) const {
return data_.getValues<APInt>()[OffsetForIndex(i)].getSExtValue();
}
private:
const DenseIntElementsAttr& data_;
};
bool MatchIotaBroadCastInDim(DenseIntElementsAttr dimensions, Value iota) {
auto iota_broadcast =
dyn_cast_or_null<mhlo::BroadcastInDimOp>(iota.getDefiningOp());
if (!iota_broadcast || iota_broadcast.getBroadcastDimensions() != dimensions)
return false;
if (!isa_and_nonnull<mhlo::IotaOp>(
iota_broadcast.getOperand().getDefiningOp()))
return false;
return true;
}
bool MatchIotaConst(DenseIntElementsAttr dimensions, Value iota) {
DenseIntElementsAttr iota_const_attr;
if (!matchPattern(iota, m_Constant(&iota_const_attr))) return false;
auto iota_type = iota_const_attr.getType();
auto iota_shape = iota_type.getShape();
auto reduce_dim = (*dimensions.value_begin<APInt>()).getSExtValue();
if (reduce_dim < 0) reduce_dim += iota_type.getRank();
auto index =
std::optional<SmallVector<int64_t>>(std::in_place, iota_type.getRank());
while (index.has_value()) {
StridedArrayView<DenseIntElementsAttr> array_view(
iota_const_attr, iota_shape, *index, reduce_dim);
for (int64_t i = 0; i < array_view.size(); ++i) {
if (array_view[i] != i) return false;
}
index = StridedArrayView<DenseIntElementsAttr>::NextTensorIndex(
std::move(*index), iota_shape, reduce_dim);
}
return true;
}
bool MatchReshapedIota(DenseIntElementsAttr dimensions, Value iota) {
if (dimensions.getNumElements() != 1) return false;
auto reshape_op = dyn_cast_or_null<mhlo::ReshapeOp>(iota.getDefiningOp());
if (!reshape_op) return false;
auto operand_type =
mlir::dyn_cast<RankedTensorType>(reshape_op.getOperand().getType());
if (!operand_type || !operand_type.hasStaticShape()) return false;
auto reshape_type = mlir::cast<RankedTensorType>(reshape_op.getType());
if (operand_type.getRank() != 1) return false;
if (!dyn_cast_or_null<mhlo::IotaOp>(reshape_op.getOperand().getDefiningOp()))
return false;
int64_t iota_dim = (*dimensions.value_begin<APInt>()).getSExtValue();
for (int64_t i = 0, e = reshape_type.getRank(); i < e; ++i) {
if (i == iota_dim) {
if (reshape_type.getDimSize(i) != operand_type.getDimSize(0))
return false;
} else if (reshape_type.getDimSize(i) != 1) {
return false;
}
}
return true;
}
bool MatchSingleIota(DenseIntElementsAttr dimensions, Value iota) {
auto iota_op = dyn_cast_or_null<mhlo::IotaOp>(iota.getDefiningOp());
if (!iota_op || dimensions.getNumElements() != 1) return false;
auto dim = *dimensions.value_begin<APInt>();
return dim == iota_op.getIotaDimension();
}
bool MatchConstIotaBroadCastInDim(DenseIntElementsAttr dimensions, Value iota) {
if (dimensions.getNumElements() != 1) return false;
auto iota_broadcast =
dyn_cast_or_null<mhlo::BroadcastInDimOp>(iota.getDefiningOp());
if (!iota_broadcast || iota_broadcast.getBroadcastDimensions() != dimensions)
return false;
DenseElementsAttr range_const;
if (!matchPattern(iota_broadcast.getOperand(), m_Constant(&range_const)))
return false;
int index = 0;
for (auto value : range_const.getValues<APInt>()) {
if (value != index++) return false;
}
return true;
}
}
bool MatchIota(DenseIntElementsAttr dimensions, Value iota) {
return MatchSingleIota(dimensions, iota) ||
MatchIotaBroadCastInDim(dimensions, iota) ||
MatchReshapedIota(dimensions, iota) ||
MatchConstIotaBroadCastInDim(dimensions, iota) ||
MatchIotaConst(dimensions, iota);
}
}
} | #include "xla/hlo/utils/hlo_matchers.h"
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include "xla/literal_util.h"
#include "xla/shape_util.h"
#include "xla/tests/hlo_test_base.h"
#include "xla/xla_data.pb.h"
namespace op = xla::testing::opcode_matchers;
using ::testing::_;
using ::testing::Eq;
using ::testing::HasSubstr;
namespace xla {
namespace {
using HloMatchersTest = HloTestBase;
std::string DescribeHloMatcher(
const ::testing::Matcher<const HloInstruction*>& m) {
std::stringstream ss;
m.DescribeTo(&ss);
return ss.str();
}
template <typename M, typename T>
std::string Explain(const T& t, const M& m) {
::testing::StringMatchResultListener listener;
EXPECT_THAT(t, ::testing::Not(m));
EXPECT_FALSE(m.MatchAndExplain(t, &listener));
return listener.str();
}
TEST_F(HloMatchersTest, Test) {
auto shape = ShapeUtil::MakeShape(F32, {1});
auto param = HloInstruction::CreateParameter(0, shape, "param");
auto mul = HloInstruction::CreateBinary(shape, HloOpcode::kMultiply,
param.get(), param.get());
auto add = HloInstruction::CreateBinary(shape, HloOpcode::kAdd, param.get(),
mul.get());
EXPECT_THAT(add.get(), op::Add());
EXPECT_THAT(add.get(), op::Add(op::Parameter(), op::Multiply()));
EXPECT_THAT(add.get(),
op::Add(op::Parameter(), op::Multiply(_, op::Parameter())));
EXPECT_THAT(
Explain(add.get(), op::Parameter()),
Eq("(%add = f32[1]{0} add(f32[1]{0} %param, f32[1]{0} %multiply))"));
EXPECT_THAT(
Explain(add.get(), op::Add(op::Parameter())),
Eq("(%add = f32[1]{0} add(f32[1]{0} %param, f32[1]{0} %multiply)) "
"has too many operands (got 2, want 1)"));
EXPECT_THAT(
Explain(add.get(), op::Add(op::Parameter(), op::Parameter())),
Eq("(%add = f32[1]{0} add(f32[1]{0} %param, f32[1]{0} %multiply))"
"\noperand 1:\n\t"
"%multiply = f32[1]{0} multiply(f32[1]{0} %param, f32[1]{0} %param)\n"
"doesn't match expected:\n\t"
"parameter"
", (%multiply = f32[1]{0} multiply(f32[1]{0} %param, f32[1]{0} "
"%param))"));
EXPECT_THAT(
Explain(add.get(),
op::Add(op::Parameter(), op::Multiply(op::Add(), op::Add()))),
Eq("(%add = f32[1]{0} add(f32[1]{0} %param, f32[1]{0} %multiply))"
"\noperand 1:\n\t"
"%multiply = f32[1]{0} multiply(f32[1]{0} %param, f32[1]{0} %param)\n"
"doesn't match expected:\n\t"
"multiply(add, add)"
", (%multiply = f32[1]{0} multiply(f32[1]{0} %param, f32[1]{0} "
"%param))\n"
"operand 0:\n\t"
"%param = f32[1]{0} parameter(0)\n"
"doesn't match expected:\n\t"
"add, (%param = f32[1]{0} parameter(0))"));
}
TEST_F(HloMatchersTest, CustomCallMatcher) {
auto c1 =
HloInstruction::CreateConstant(LiteralUtil::CreateR1<float>({1, 2, 3}));
auto c2 =
HloInstruction::CreateConstant(LiteralUtil::CreateR1<int32_t>({1, 2, 3}));
auto call = HloInstruction::CreateCustomCall(
ShapeUtil::MakeShape(F32, {1}), {c1.get(), c2.get()}, "foo_target");
EXPECT_THAT(call.get(), op::CustomCall());
EXPECT_THAT(call.get(), op::CustomCall(c1.get(), c2.get()));
EXPECT_THAT(call.get(), op::CustomCall("foo_target"));
EXPECT_THAT(call.get(), op::CustomCall("foo_target", c1.get(), c2.get()));
EXPECT_THAT(call.get(), op::CustomCall(::testing::StartsWith("foo")));
EXPECT_THAT(call.get(),
op::CustomCall(::testing::Not(::testing::StartsWith("bar"))));
EXPECT_THAT(call.get(), ::testing::Not(op::CustomCall(c1.get())));
EXPECT_THAT(call.get(),
::testing::Not(op::CustomCall(::testing::StartsWith("bar"))));
EXPECT_THAT(Explain(call.get(), op::CustomCall("bar")),
"(%custom-call = f32[1]{0} custom-call(f32[3]{0} %constant, "
"s32[3]{0} %constant), custom_call_target=\"foo_target\") "
"custom-call with call target that isn't equal to \"bar\"");
EXPECT_THAT(DescribeHloMatcher(op::CustomCall("foo_target")),
R"(custom-call with call target that is equal to "foo_target")");
}
TEST_F(HloMatchersTest, ShapeMatcher) {
auto p0 = HloInstruction::CreateParameter(
0, ShapeUtil::MakeShapeWithDenseLayout(F32, {5, 7}, {0, 1}), "param");
EXPECT_THAT(p0.get(), op::Shape(ShapeUtil::MakeShape(F32, {5, 7})));
EXPECT_THAT(p0.get(), op::Shape("f32[5,7]"));
EXPECT_THAT(
p0.get(),
::testing::Not(op::ShapeWithLayout(ShapeUtil::MakeShape(F32, {5, 7}))));
EXPECT_THAT(p0.get(), ::testing::Not(op::ShapeWithLayout("f32[5,7]")));
EXPECT_THAT(p0.get(),
::testing::Not(op::Shape(ShapeUtil::MakeShape(F32, {7, 5}))));
EXPECT_THAT(p0.get(), ::testing::Not(op::Shape("f32[7,5]")));
EXPECT_THAT(
p0.get(),
::testing::Not(op::ShapeWithLayout(ShapeUtil::MakeShape(F32, {7, 5}))));
EXPECT_THAT(p0.get(), ::testing::Not(op::ShapeWithLayout("f32[7,5]")));
EXPECT_THAT(p0.get(), op::Shape(ShapeUtil::MakeShapeWithDenseLayout(
F32, {5, 7}, {0, 1})));
EXPECT_THAT(p0.get(), op::Shape("f32[5,7]{0,1}"));
EXPECT_THAT(p0.get(), op::ShapeWithLayout(ShapeUtil::MakeShapeWithDenseLayout(
F32, {5, 7}, {0, 1})));
EXPECT_THAT(p0.get(), op::ShapeWithLayout("f32[5,7]{0,1}"));
EXPECT_THAT(p0.get(),
::testing::Not(op::ShapeWithLayout(
ShapeUtil::MakeShapeWithDenseLayout(F32, {5, 7}, {1, 0}))));
EXPECT_THAT(p0.get(), ::testing::Not(op::ShapeWithLayout("f32[5,7]{1,0}")));
EXPECT_THAT(Explain(p0.get(), op::Shape(ShapeUtil::MakeShape(F32, {7, 5}))),
"%param = f32[5,7]{0,1} parameter(0) has incorrect shape "
"(expected: f32[7,5])");
EXPECT_THAT(
Explain(p0.get(), op::ShapeWithLayout(ShapeUtil::MakeShapeWithDenseLayout(
F32, {7, 5}, {1, 0}))),
"%param = f32[5,7]{0,1} parameter(0) has incorrect shape "
"(expected: f32[7,5]{1,0})");
}
TEST_F(HloMatchersTest, ShardingMatcher) {
auto p0 = HloInstruction::CreateParameter(0, ShapeUtil::MakeShape(F32, {5}),
"param.0");
p0->clear_sharding();
auto p1 = HloInstruction::CreateParameter(1, ShapeUtil::MakeShape(F32, {7}),
"param.1");
p1->set_sharding(HloSharding::AssignDevice(1));
auto tuple_shape = ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {7}), ShapeUtil::MakeShape(S32, {9}),
ShapeUtil::MakeShape(F32, {11})});
auto p2 = HloInstruction::CreateParameter(1, tuple_shape, "param.2");
Array<int64_t> assignment({2});
assignment.SetValues({0, 1});
auto sharding = HloSharding::Tuple(
tuple_shape, {HloSharding::Tile(assignment), HloSharding::AssignDevice(1),
HloSharding::Replicate()});
p2->set_sharding(sharding);
EXPECT_THAT(p0.get(), op::NoSharding());
EXPECT_THAT(p0.get(),
::testing::Not(op::Sharding(HloSharding::AssignDevice(1))));
EXPECT_THAT(p1.get(), ::testing::Not(op::NoSharding()));
EXPECT_THAT(p1.get(),
::testing::Not(op::Sharding(HloSharding::AssignDevice(0))));
EXPECT_THAT(p1.get(), op::Sharding(HloSharding::AssignDevice(1)));
EXPECT_THAT(
p2.get(),
op::Sharding("{{devices=[2]0,1}, {maximal device=1}, {replicated}}"));
EXPECT_THAT(Explain(p0.get(), op::Sharding(HloSharding::AssignDevice(1))),
"%param.0 = f32[5]{0} parameter(0) has no sharding (expected: "
"{maximal device=1})");
EXPECT_THAT(Explain(p1.get(), op::NoSharding()),
"%param.1 = f32[7]{0} parameter(1), sharding={maximal device=1} "
"expected to have no sharding.");
EXPECT_THAT(Explain(p1.get(), op::Sharding(HloSharding::AssignDevice(0))),
"%param.1 = f32[7]{0} parameter(1), sharding={maximal device=1} "
"has incorrect sharding (expected: {maximal device=0})");
}
TEST_F(HloMatchersTest, DotMatcher) {
std::string hlo_string = R"(
HloModule DotOperationFusion_TransposeFusion
ENTRY DotOperationFusion_TransposeFusion {
arg0 = f32[1,256] parameter(0)
arg1 = f32[256,1024] parameter(1)
ROOT dot = f32[1,1024] dot(arg0, arg1), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::Dot(op::Parameter(0), op::Parameter(1),
1,
0));
EXPECT_THAT(
Explain(root, op::Dot(op::Parameter(0), op::Parameter(1),
0,
0)),
"(%dot = f32[1,1024]{1,0} dot(f32[1,256]{1,0} %arg0, f32[256,1024]{1,0} "
"%arg1), lhs_contracting_dims={1}, rhs_contracting_dims={0}) has wrong "
"lhs_contracting_dimensions (got {1} want {0})");
EXPECT_THAT(
Explain(root, op::Dot(op::Parameter(0), op::Parameter(1),
1,
1)),
"(%dot = f32[1,1024]{1,0} dot(f32[1,256]{1,0} %arg0, f32[256,1024]{1,0} "
"%arg1), lhs_contracting_dims={1}, rhs_contracting_dims={0}) has wrong "
"rhs_contracting_dimensions (got {0} want {1})");
}
TEST_F(HloMatchersTest, ComparisonMatcher) {
auto shape = ShapeUtil::MakeShape(F32, {1});
auto p0 = HloInstruction::CreateParameter(0, shape, "param.0");
auto p1 = HloInstruction::CreateParameter(1, shape, "param.1");
auto eq = HloInstruction::CreateCompare(shape, p0.get(), p1.get(),
ComparisonDirection::kEq);
auto ne = HloInstruction::CreateCompare(shape, p0.get(), p1.get(),
ComparisonDirection::kNe);
auto add =
HloInstruction::CreateBinary(shape, HloOpcode::kAdd, p0.get(), p1.get());
auto le = HloInstruction::CreateCompare(shape, p0.get(), add.get(),
ComparisonDirection::kLe);
EXPECT_THAT(eq.get(), op::Compare());
EXPECT_THAT(eq.get(), op::Eq());
EXPECT_THAT(ne.get(), op::Compare());
EXPECT_THAT(ne.get(), op::Ne());
EXPECT_THAT(le.get(),
op::Compare(op::Parameter(0),
op::Add(op::Parameter(0), op::Parameter(1))));
EXPECT_THAT(le.get(), op::Le(op::Parameter(0),
op::Add(op::Parameter(0), op::Parameter(1))));
EXPECT_THAT(Explain(eq.get(), op::Add()),
Eq("(%compare = f32[1]{0} compare(f32[1]{0} %param.0, "
"f32[1]{0} %param.1), direction=EQ)"));
EXPECT_THAT(Explain(eq.get(), op::Ne()),
Eq("(%compare = f32[1]{0} compare(f32[1]{0} %param.0, "
"f32[1]{0} %param.1), direction=EQ) "
"has wrong comparison direction (got EQ, want NE)"));
}
TEST_F(HloMatchersTest, AsyncCopyMatcher) {
Shape shape_memspace1 = ShapeUtil::MakeShapeWithDenseLayout(
F32, {16}, {0}, {},
1,
0,
1);
Shape shape_memspace2 = ShapeUtil::MakeShapeWithDenseLayout(
F32, {16}, {0}, {},
1,
0,
2);
auto p0 = HloInstruction::CreateParameter(0, shape_memspace1, "p0");
auto copy_start = HloInstruction::CreateCopyStart(
ShapeUtil::MakeTupleShape(
{shape_memspace2, shape_memspace1, ShapeUtil::MakeShape(U32, {})}),
p0.get());
auto copy_done = HloInstruction::CreateUnary(
shape_memspace2, HloOpcode::kCopyDone, copy_start.get());
EXPECT_THAT(copy_done.get(), op::AsyncCopy(2, 1, op::Parameter(0)));
EXPECT_THAT(Explain(copy_start.get(), op::AsyncCopy(2, 1, op::Parameter(0))),
Eq("(%copy-start = (f32[16]{0:S(2)}, f32[16]{0:S(1)}, u32[]) "
"copy-start(f32[16]{0:S(1)} %p0))"));
EXPECT_THAT(Explain(copy_done.get(), op::AsyncCopy(3, 1, op::Parameter(0))),
"(%copy-done = f32[16]{0:S(2)} copy-done((f32[16]{0:S(2)}, "
"f32[16]{0:S(1)}, u32[]) "
"%copy-start)) "
"copies to memory space 2, expected 3");
EXPECT_THAT(Explain(copy_done.get(), op::AsyncCopy(2, 3, op::Parameter(0))),
"(%copy-done = f32[16]{0:S(2)} copy-done((f32[16]{0:S(2)}, "
"f32[16]{0:S(1)}, u32[]) "
"%copy-start)) "
"is in the memory space 1, expected 3");
}
TEST_F(HloMatchersTest, ConstantMatcher) {
std::string hlo_string = R"(
HloModule Constant
ENTRY main {
ROOT x = u32[2] constant({1, 2})
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::Constant());
EXPECT_THAT(root, op::Constant(LiteralUtil::CreateR1<uint32_t>({1, 2})));
EXPECT_THAT(root, ::testing::Not(
op::Constant(LiteralUtil::CreateR1<uint32_t>({1, 1}))));
EXPECT_THAT(Explain(root, op::Constant(LiteralUtil::CreateR0<uint32_t>(1))),
"(%x = u32[2]{0} constant({1, 2})) has wrong value (got u32[2] "
"{1, 2}, want u32[] 1)");
}
TEST_F(HloMatchersTest, ReplicaGroupsMatcher) {
Shape shape = ShapeUtil::MakeShape(F32, {5, 7});
std::unique_ptr<HloInstruction> p0 =
HloInstruction::CreateParameter(0, shape, "param");
std::vector<ReplicaGroup> replica_groups(2);
replica_groups[0].add_replica_ids(0);
replica_groups[0].add_replica_ids(2);
replica_groups[1].add_replica_ids(1);
replica_groups[1].add_replica_ids(3);
std::unique_ptr<HloInstruction> all_to_all = HloInstruction::CreateAllToAll(
shape, {p0.get()}, CollectiveDeviceList(replica_groups),
false,
std::nullopt);
EXPECT_THAT(Explain(p0.get(), op::ReplicaGroups({})),
"%param = f32[5,7]{1,0} parameter(0) not a collective op");
EXPECT_THAT(Explain(all_to_all.get(), op::ReplicaGroups({{0, 1}, {2, 3}})),
"%all-to-all = f32[5,7]{1,0} all-to-all(f32[5,7]{1,0} %param), "
"replica_groups={{0,2},{1,3}} has incorrect replica_groups "
"(expected: {{0,1},{2,3}})");
EXPECT_THAT(all_to_all.get(), op::ReplicaGroups({{0, 2}, {1, 3}}));
}
TEST_F(HloMatchersTest, SourceTargetPairsMatcher) {
Shape shape = ShapeUtil::MakeShape(F32, {5, 7});
std::unique_ptr<HloInstruction> p0 =
HloInstruction::CreateParameter(0, shape, "param");
std::vector<std::pair<int64_t, int64_t>> source_target_pairs = {
{0, 1}, {2, 3}, {1, 2}};
std::unique_ptr<HloInstruction> cp = HloInstruction::CreateCollectivePermute(
shape, p0.get(), source_target_pairs, std::nullopt);
EXPECT_THAT(Explain(p0.get(), op::SourceTargetPairs({{0, 1}})),
HasSubstr("not a collective permute"));
EXPECT_THAT(Explain(cp.get(), op::SourceTargetPairs({{0, 1}, {2, 3}})),
HasSubstr("source_target_pairs (expected: {{0,1},{2,3}}"));
EXPECT_THAT(cp.get(), op::SourceTargetPairs({{0, 1}, {2, 3}, {1, 2}}));
}
TEST_F(HloMatchersTest, MetadataMatcher) {
Shape shape = ShapeUtil::MakeShape(F32, {5, 7});
std::unique_ptr<HloInstruction> p0 =
HloInstruction::CreateParameter(0, shape, "param");
OpMetadata metadata;
metadata.set_op_type("op_type1");
metadata.set_op_name("op_name1");
p0->set_metadata(metadata);
OpMetadata actual_opname;
actual_opname.set_op_type("op_type1");
actual_opname.set_op_name("op_name2");
OpMetadata actual_source_file;
actual_source_file.set_op_type("op_type1");
actual_source_file.set_op_name("op_name1");
actual_source_file.set_source_file("source_file");
OpMetadata actual_optype;
actual_optype.set_op_type("op_type2");
actual_optype.set_op_name("op_name1");
OpMetadata actual_source_line;
actual_source_line.set_op_type("op_type1");
actual_source_line.set_op_name("op_name1");
actual_source_line.set_source_line(1);
EXPECT_THAT(Explain(p0.get(), op::Metadata(actual_opname)),
HasSubstr("has wrong metadata (got op_name1, want op_name2)"));
EXPECT_THAT(Explain(p0.get(), op::Metadata(actual_source_file)),
HasSubstr("has wrong metadata (got "
", want source_file)"));
EXPECT_THAT(Explain(p0.get(), op::Metadata(actual_optype)),
HasSubstr("has wrong metadata (got"
" op_type1, want op_type2)"));
EXPECT_THAT(Explain(p0.get(), op::Metadata(actual_source_line)),
HasSubstr("has wrong metadata (got 0"
", want 1)"));
EXPECT_THAT(DescribeHloMatcher(op::Metadata(p0->metadata())),
R"( (metadata: op_type1 op_name1 0))");
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/mlir/lite/stablehlo/transforms/hlo_matchers.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/hlo/utils/hlo_matchers_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
2daed6fc-9200-44fa-9d04-a8857c2e409c | cpp | tensorflow/tensorflow | cpu_utils | third_party/xla/third_party/tsl/tsl/platform/profile_utils/cpu_utils.cc | third_party/xla/third_party/tsl/tsl/platform/profile_utils/cpu_utils_test.cc | #include "tsl/platform/profile_utils/cpu_utils.h"
#include <fstream>
#include <limits>
#include <mutex>
#if defined(_WIN32)
#include <windows.h>
#endif
#if defined(__APPLE__)
#include <sys/sysctl.h>
#endif
#include "absl/base/call_once.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/profile_utils/android_armv7a_cpu_utils_helper.h"
namespace tsl {
namespace profile_utils {
constexpr int64_t CpuUtils::INVALID_FREQUENCY;
static ICpuUtilsHelper* cpu_utils_helper_instance_ = nullptr;
#if (defined(__powerpc__) || \
defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \
(defined(__s390x__))
uint64 CpuUtils::GetCycleCounterFrequency() {
static const uint64 cpu_frequency = GetCycleCounterFrequencyImpl();
return cpu_frequency;
}
#else
int64_t CpuUtils::GetCycleCounterFrequency() {
static const int64_t cpu_frequency = GetCycleCounterFrequencyImpl();
return cpu_frequency;
}
#endif
double CpuUtils::GetMicroSecPerClock() {
static const double micro_sec_per_clock =
(1000.0 * 1000.0) / static_cast<double>(GetCycleCounterFrequency());
return micro_sec_per_clock;
}
void CpuUtils::ResetClockCycle() {
GetCpuUtilsHelperSingletonInstance().ResetClockCycle();
}
void CpuUtils::EnableClockCycleProfiling() {
GetCpuUtilsHelperSingletonInstance().EnableClockCycleProfiling();
}
void CpuUtils::DisableClockCycleProfiling() {
GetCpuUtilsHelperSingletonInstance().DisableClockCycleProfiling();
}
std::chrono::duration<double> CpuUtils::ConvertClockCycleToTime(
const int64_t clock_cycle) {
return std::chrono::duration<double>(static_cast<double>(clock_cycle) /
GetCycleCounterFrequency());
}
int64_t CpuUtils::GetCycleCounterFrequencyImpl() {
#if defined(__ANDROID__)
return GetCpuUtilsHelperSingletonInstance().CalculateCpuFrequency();
#elif defined(__linux__)
std::ifstream cpuinfo("/proc/cpuinfo");
if (!cpuinfo) {
LOG(WARNING) << "Failed to open /proc/cpuinfo";
return INVALID_FREQUENCY;
}
string line;
while (std::getline(cpuinfo, line)) {
double cpu_freq = 0.0;
int retval = 0;
double freq_factor = 2.0;
#if (defined(__powerpc__) || \
defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
retval = sscanf(line.c_str(), "clock : %lfMHz", &cpu_freq);
freq_factor = 1.0;
#elif defined(__s390x__)
retval = sscanf(line.c_str(), "bogomips per cpu: %lf", &cpu_freq);
#elif defined(__aarch64__)
retval = sscanf(line.c_str(), "BogoMIPS : %lf", &cpu_freq);
#else
retval = sscanf(line.c_str(), "bogomips : %lf", &cpu_freq);
#endif
if (retval > 0) {
const double freq_ghz = cpu_freq / 1000.0 / freq_factor;
if (retval != 1 || freq_ghz < 0.01) {
LOG(WARNING) << "Failed to get CPU frequency: " << freq_ghz << " GHz";
return INVALID_FREQUENCY;
}
const int64_t freq_n =
static_cast<int64_t>(freq_ghz * 1000.0 * 1000.0 * 1000.0);
VLOG(1) << "CPU Frequency: " << freq_n << " Hz";
return freq_n;
}
}
LOG(WARNING)
<< "Failed to find bogomips or clock in /proc/cpuinfo; cannot determine "
"CPU frequency";
return INVALID_FREQUENCY;
#elif defined(__APPLE__)
int64_t freq_hz = 0;
size_t freq_hz_size = sizeof(freq_hz);
int retval =
sysctlbyname("hw.cpufrequency_max", &freq_hz, &freq_hz_size, NULL, 0);
if (retval != 0 || freq_hz < 1e6) {
int64_t tbfrequency = 0;
size_t tbfrequency_size = sizeof(tbfrequency);
retval = sysctlbyname("hw.tbfrequency", &tbfrequency, &tbfrequency_size,
NULL, 0);
if (retval == 0) {
clockinfo clock_info;
size_t clock_info_size = sizeof(clock_info);
retval = sysctlbyname("kern.clockrate", &clock_info, &clock_info_size,
NULL, 0);
if (retval == 0) {
freq_hz = clock_info.hz * tbfrequency;
}
}
if (retval != 0 || freq_hz < 1e6) {
LOG(WARNING) << "Failed to get CPU frequency: " << freq_hz << " Hz";
return INVALID_FREQUENCY;
}
}
return freq_hz;
#elif defined(_WIN32)
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
return freq.QuadPart;
#else
return INVALID_FREQUENCY;
#endif
}
ICpuUtilsHelper& CpuUtils::GetCpuUtilsHelperSingletonInstance() {
static absl::once_flag flag;
absl::call_once(flag, []() {
if (cpu_utils_helper_instance_ != nullptr) {
LOG(FATAL) << "cpu_utils_helper_instance_ is already instantiated.";
}
#if defined(__ANDROID__) && (__ANDROID_API__ >= 21) && \
(defined(__ARM_ARCH_7A__) || defined(__aarch64__))
cpu_utils_helper_instance_ = new AndroidArmV7ACpuUtilsHelper();
#else
cpu_utils_helper_instance_ = new DefaultCpuUtilsHelper();
#endif
});
return *cpu_utils_helper_instance_;
}
}
} | #include "tsl/platform/profile_utils/cpu_utils.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/profile_utils/clock_cycle_profiler.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace profile_utils {
static constexpr bool DBG = false;
class CpuUtilsTest : public ::testing::Test {
protected:
void SetUp() override { CpuUtils::EnableClockCycleProfiling(); }
};
TEST_F(CpuUtilsTest, SetUpTestCase) {}
TEST_F(CpuUtilsTest, TearDownTestCase) {}
TEST_F(CpuUtilsTest, CheckGetCurrentClockCycle) {
static constexpr int LOOP_COUNT = 10;
const uint64 start_clock_count = CpuUtils::GetCurrentClockCycle();
CHECK_GT(start_clock_count, 0);
uint64 prev_clock_count = start_clock_count;
for (int i = 0; i < LOOP_COUNT; ++i) {
const uint64 clock_count = CpuUtils::GetCurrentClockCycle();
CHECK_GE(clock_count, prev_clock_count);
prev_clock_count = clock_count;
}
const uint64 end_clock_count = CpuUtils::GetCurrentClockCycle();
if (DBG) {
LOG(INFO) << "start clock = " << start_clock_count;
LOG(INFO) << "end clock = " << end_clock_count;
LOG(INFO) << "average clock = "
<< ((end_clock_count - start_clock_count) / LOOP_COUNT);
}
}
TEST_F(CpuUtilsTest, CheckCycleCounterFrequency) {
#if (defined(__powerpc__) || \
defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \
(defined(__s390x__))
const uint64 cpu_frequency = CpuUtils::GetCycleCounterFrequency();
CHECK_GT(cpu_frequency, 0);
CHECK_NE(cpu_frequency, unsigned(CpuUtils::INVALID_FREQUENCY));
#else
const int64_t cpu_frequency = CpuUtils::GetCycleCounterFrequency();
CHECK_GT(cpu_frequency, 0);
CHECK_NE(cpu_frequency, CpuUtils::INVALID_FREQUENCY);
#endif
if (DBG) {
LOG(INFO) << "Cpu frequency = " << cpu_frequency;
}
}
TEST_F(CpuUtilsTest, CheckMicroSecPerClock) {
const double micro_sec_per_clock = CpuUtils::GetMicroSecPerClock();
CHECK_GT(micro_sec_per_clock, 0.0);
if (DBG) {
LOG(INFO) << "Micro sec per clock = " << micro_sec_per_clock;
}
}
TEST_F(CpuUtilsTest, SimpleUsageOfClockCycleProfiler) {
static constexpr int LOOP_COUNT = 10;
ClockCycleProfiler prof;
for (int i = 0; i < LOOP_COUNT; ++i) {
prof.Start();
prof.Stop();
}
EXPECT_EQ(LOOP_COUNT, static_cast<int>(prof.GetCount() + 0.5));
if (DBG) {
prof.DumpStatistics("CpuUtilsTest");
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/third_party/tsl/tsl/platform/profile_utils/cpu_utils.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/third_party/tsl/tsl/platform/profile_utils/cpu_utils_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
10851145-94d4-4428-b846-ace1c1731762 | cpp | google/tensorstore | alignment | tensorstore/index_space/alignment.cc | tensorstore/index_space/alignment_test.cc | #include "tensorstore/index_space/alignment.h"
#include <algorithm>
#include <numeric>
#include "absl/status/status.h"
#include "tensorstore/index_space/internal/transform_rep.h"
#include "tensorstore/util/str_cat.h"
namespace tensorstore {
absl::Status AlignDimensionsTo(IndexDomainView<> source,
IndexDomainView<> target,
span<DimensionIndex> source_matches,
DomainAlignmentOptions options) {
assert(source.valid());
assert(target.valid());
const DimensionIndex source_rank = source.rank();
const DimensionIndex target_rank = target.rank();
if (!(options & DomainAlignmentOptions::broadcast) &&
source_rank != target_rank) {
return absl::InvalidArgumentError(tensorstore::StrCat(
"Aligning source domain of rank ", source_rank,
" to target domain of rank ", target_rank, " requires broadcasting"));
}
assert(source_matches.size() == source_rank);
const auto source_labels = source.labels();
const auto target_labels = target.labels();
if (!(options & DomainAlignmentOptions::permute) ||
internal_index_space::IsUnlabeled(source_labels) ||
internal_index_space::IsUnlabeled(target_labels)) {
const DimensionIndex match_rank = std::min(source_rank, target_rank);
const DimensionIndex source_match_start = source_rank - match_rank;
const DimensionIndex target_match_start = target_rank - match_rank;
std::fill_n(source_matches.begin(), source_match_start, DimensionIndex(-1));
std::iota(source_matches.begin() + source_match_start, source_matches.end(),
target_match_start);
} else {
DimensionIndex next_potentially_unlabeled_target = target_rank - 1;
for (DimensionIndex i = source_rank - 1; i >= 0; --i) {
std::string_view source_label = source_labels[i];
DimensionIndex j;
if (source_label.empty()) {
while (true) {
if (next_potentially_unlabeled_target < 0) {
j = -1;
break;
}
if (target_labels[next_potentially_unlabeled_target].empty()) {
j = next_potentially_unlabeled_target--;
break;
}
--next_potentially_unlabeled_target;
}
} else {
for (j = target_rank - 1; j >= 0; --j) {
if (target_labels[j] == source_label) break;
}
}
source_matches[i] = j;
}
}
std::string mismatch_error;
const auto source_shape = source.shape();
const auto target_shape = target.shape();
for (DimensionIndex i = 0; i < source_rank; ++i) {
DimensionIndex& j = source_matches[i];
const DimensionIndex source_size = source_shape[i];
if (j != -1) {
if (!(options & DomainAlignmentOptions::translate)
? source[i] != target[j]
: source_size != target_shape[j]) {
if (!(options & DomainAlignmentOptions::broadcast) ||
source_size != 1) {
tensorstore::StrAppend(&mismatch_error, "source dimension ", i, " ",
source[i], " mismatch with target dimension ",
j, " ", target[j], ", ");
}
j = -1;
}
} else {
if (!(options & DomainAlignmentOptions::broadcast)) {
tensorstore::StrAppend(&mismatch_error, "unmatched source dimension ",
i, " ", source[i], ", ");
}
if (source_size != 1) {
tensorstore::StrAppend(&mismatch_error, "unmatched source dimension ",
i, " ", source[i],
" does not have a size of 1, ");
}
}
}
if (!mismatch_error.empty()) {
mismatch_error.resize(mismatch_error.size() - 2);
return absl::InvalidArgumentError(
tensorstore::StrCat("Error aligning dimensions: ", mismatch_error));
}
return absl::OkStatus();
}
Result<IndexTransform<>> AlignDomainTo(IndexDomainView<> source,
IndexDomainView<> target,
DomainAlignmentOptions options) {
using internal_index_space::TransformAccess;
assert(source.valid());
assert(target.valid());
const DimensionIndex source_rank = source.rank();
DimensionIndex source_matches[kMaxRank];
TENSORSTORE_RETURN_IF_ERROR(AlignDimensionsTo(
source, target, span(source_matches).first(source_rank), options));
const DimensionIndex target_rank = target.rank();
auto alignment =
internal_index_space::TransformRep::Allocate(target_rank, source_rank);
CopyTransformRepDomain(TransformAccess::rep(target), alignment.get());
alignment->output_rank = source_rank;
const auto maps = alignment->output_index_maps();
span<const Index> source_origin = source.origin();
span<const Index> target_origin = target.origin();
for (DimensionIndex i = 0; i < source_rank; ++i) {
auto& map = maps[i];
const DimensionIndex j = source_matches[i];
const Index source_origin_value = source_origin[i];
if (j == -1) {
map.SetConstant();
map.offset() = source_origin_value;
map.stride() = 0;
} else {
map.SetSingleInputDimension(j);
map.offset() = source_origin_value - target_origin[j];
map.stride() = 1;
}
}
internal_index_space::DebugCheckInvariants(alignment.get());
return TransformAccess::Make<IndexTransform<>>(std::move(alignment));
}
Result<IndexTransform<>> AlignTransformTo(IndexTransform<> source_transform,
IndexDomainView<> target,
DomainAlignmentOptions options) {
TENSORSTORE_ASSIGN_OR_RETURN(
auto alignment,
AlignDomainTo(source_transform.domain(), target, options));
return ComposeTransforms(source_transform, alignment);
}
} | #include "tensorstore/index_space/alignment.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorstore/index_space/index_domain_builder.h"
#include "tensorstore/index_space/index_transform.h"
#include "tensorstore/index_space/index_transform_builder.h"
#include "tensorstore/util/status.h"
#include "tensorstore/util/status_testutil.h"
namespace {
using ::tensorstore::DimensionIndex;
using ::tensorstore::Index;
using ::tensorstore::IndexDomain;
using ::tensorstore::IndexDomainBuilder;
using ::tensorstore::IndexTransform;
using ::tensorstore::IndexTransformBuilder;
using ::tensorstore::MatchesStatus;
using Dao = tensorstore::DomainAlignmentOptions;
TEST(AlignDimensionsToTest, AllUnlabeled) {
auto source = IndexDomainBuilder(3)
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.origin({2, 0, 6})
.exclusive_max({6, 4, 12})
.Finalize()
.value();
for (auto options : {Dao::all, Dao::translate | Dao::broadcast}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches, options));
EXPECT_THAT(source_matches, ::testing::ElementsAre(0, -1, 2));
}
{
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, source, source_matches, Dao::none));
EXPECT_THAT(source_matches, ::testing::ElementsAre(0, 1, 2));
}
{
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(
AlignDimensionsTo(source, target, source_matches, Dao::translate),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: "
"source dimension 1 \\[5, 6\\) mismatch with target "
"dimension 1 \\[0, 4\\)"));
}
{
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(
AlignDimensionsTo(source, target, source_matches, Dao::broadcast),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: "
"source dimension 0 \\[3, 7\\) mismatch with target "
"dimension 0 \\[2, 6\\), "
"source dimension 2 \\[4, 10\\) mismatch with target "
"dimension 2 \\[6, 12\\)"));
}
}
TEST(AlignDimensionsToTest, MismatchedLabelsNoPermute) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", "z"})
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"a", "b", "c"})
.origin({2, 0, 6})
.exclusive_max({6, 4, 12})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches,
Dao::translate | Dao::broadcast));
EXPECT_THAT(source_matches, ::testing::ElementsAre(0, -1, 2));
EXPECT_THAT(AlignDimensionsTo(source, target, source_matches, Dao::all),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: "
"unmatched source dimension 0 \"x\": \\[3, 7\\) "
"does not have a size of 1, "
"unmatched source dimension 2 \"z\": \\[4, 10\\) "
"does not have a size of 1"));
}
TEST(AlignDimensionsToTest, SourceUnlabeled) {
auto source = IndexDomainBuilder(3)
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.origin({4, 0, 6})
.labels({"x", "y", "z"})
.exclusive_max({8, 4, 12})
.Finalize()
.value();
for (auto options : {Dao::all, Dao::translate | Dao::broadcast}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches, options));
EXPECT_THAT(source_matches, ::testing::ElementsAre(0, -1, 2));
}
}
TEST(AlignDimensionsToTest, TargetUnlabeled) {
auto source = IndexDomainBuilder(3)
.origin({3, 5, 4})
.labels({"x", "y", "z"})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.origin({4, 0, 6})
.exclusive_max({8, 4, 12})
.Finalize()
.value();
for (auto options : {Dao::all, Dao::translate | Dao::broadcast}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches, options));
EXPECT_THAT(source_matches, ::testing::ElementsAre(0, -1, 2));
}
}
TEST(AlignDimensionsToTest, AllLabeled) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", "z"})
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"z", "x", "y"})
.origin({6, 4, 0})
.exclusive_max({12, 8, 4})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches));
EXPECT_THAT(source_matches, ::testing::ElementsAre(1, -1, 0));
}
TEST(AlignDimensionsToTest, AllLabeledPermuteOnly) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", "z"})
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"z", "x", "y"})
.origin({4, 3, 5})
.exclusive_max({10, 7, 6})
.Finalize()
.value();
for (auto options : {Dao::permute, Dao::permute | Dao::translate,
Dao::permute | Dao::broadcast, Dao::all}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches, options));
EXPECT_THAT(source_matches, ::testing::ElementsAre(1, 2, 0));
}
for (auto options : {Dao::none, Dao::translate, Dao::broadcast,
Dao::translate | Dao::broadcast}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(AlignDimensionsTo(source, target, source_matches, options),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: .*"));
}
}
TEST(AlignDimensionsToTest, AllLabeledPermuteTranslateOnly) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", "z"})
.origin({3, 5, 4})
.exclusive_max({7, 9, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"z", "x", "y"})
.origin({6, 4, 0})
.exclusive_max({12, 8, 4})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches));
EXPECT_THAT(source_matches, ::testing::ElementsAre(1, 2, 0));
}
TEST(AlignDimensionsToTest, PartiallyLabeled) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", ""})
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(4)
.labels({"", "", "x", "y"})
.origin({0, 6, 4, 0})
.exclusive_max({10, 12, 8, 4})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches));
EXPECT_THAT(source_matches, ::testing::ElementsAre(2, -1, 1));
EXPECT_THAT(AlignDimensionsTo(source, target, source_matches, Dao::none),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Aligning source domain of rank 3 to target "
"domain of rank 4 requires broadcasting"));
}
TEST(AlignDomainToTest, PartiallyLabeled) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", ""})
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(4)
.labels({"", "", "x", "y"})
.origin({0, 6, 4, 0})
.exclusive_max({10, 12, 8, 4})
.Finalize()
.value();
IndexTransform<> alignment = IndexTransformBuilder<>(4, 3)
.input_domain(target)
.output_single_input_dimension(0, -1, 1, 2)
.output_constant(1, 5)
.output_single_input_dimension(2, -2, 1, 1)
.Finalize()
.value();
EXPECT_EQ(alignment, AlignDomainTo(source, target));
}
TEST(AlignDimensionsToTest, BroadcastOnly) {
auto source = IndexDomainBuilder(2)
.origin({2, 3})
.exclusive_max({5, 6})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.origin({1, 2, 3})
.exclusive_max({4, 5, 6})
.Finalize()
.value();
for (auto options : {Dao::broadcast, Dao::broadcast | Dao::translate,
Dao::broadcast | Dao::permute, Dao::all}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches, options));
EXPECT_THAT(source_matches, ::testing::ElementsAre(1, 2));
}
for (auto options : {Dao::none, Dao::permute, Dao::translate,
Dao::permute | Dao::translate}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(AlignDimensionsTo(source, target, source_matches, options),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Aligning source domain of rank 2 to target "
"domain of rank 3 requires broadcasting"));
}
}
TEST(AlignDimensionsToTest, PermuteAndBroadcast) {
auto source = IndexDomainBuilder(2)
.origin({2, 3})
.exclusive_max({5, 4})
.labels({"x", "y"})
.Finalize()
.value();
auto target = IndexDomainBuilder(2)
.origin({2, 5})
.exclusive_max({5, 10})
.labels({"x", "z"})
.Finalize()
.value();
for (auto options : {Dao::permute | Dao::broadcast, Dao::all}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches, options));
EXPECT_THAT(source_matches, ::testing::ElementsAre(0, -1));
}
for (auto options : {Dao::permute, Dao::permute | Dao::translate}) {
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(
AlignDimensionsTo(source, target, source_matches, options),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: "
"unmatched source dimension 1 \"y\": \\[3, 4\\)"));
}
}
TEST(AlignDimensionsToTest, UnmatchedUnlabeledSourceDimension) {
auto source = IndexDomainBuilder(4)
.labels({"x", "y", "", ""})
.origin({3, 5, 7, 4})
.exclusive_max({7, 9, 8, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"", "x", "y"})
.origin({0, 4, 0})
.exclusive_max({6, 8, 4})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_EQ(absl::OkStatus(),
AlignDimensionsTo(source, target, source_matches));
EXPECT_THAT(source_matches, ::testing::ElementsAre(1, 2, -1, 0));
}
TEST(AlignDimensionsToTest, MismatchedLabeled) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", "z"})
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"z", "w", "y"})
.origin({6, 4, 0})
.exclusive_max({12, 8, 4})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(AlignDimensionsTo(source, target, source_matches),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: "
"unmatched source dimension 0 \"x\": \\[3, 7\\) "
"does not have a size of 1"));
}
TEST(AlignDomainToTest, MismatchedLabeled) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", "z"})
.origin({3, 5, 4})
.exclusive_max({7, 6, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"z", "w", "y"})
.origin({6, 4, 0})
.exclusive_max({12, 8, 4})
.Finalize()
.value();
EXPECT_THAT(AlignDomainTo(source, target),
MatchesStatus(absl::StatusCode::kInvalidArgument));
}
TEST(AlignDimensionsToTest, MismatchedSizeLabeled) {
auto source = IndexDomainBuilder(3)
.labels({"x", "y", "z"})
.origin({3, 5, 4})
.exclusive_max({7, 7, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.labels({"z", "x", "y"})
.origin({6, 4, 0})
.exclusive_max({12, 8, 4})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(AlignDimensionsTo(source, target, source_matches),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: "
"source dimension 1 \"y\": \\[5, 7\\) mismatch "
"with target dimension 2 \"y\": \\[0, 4\\)"));
}
TEST(AlignDimensionsToTest, MismatchedSizeUnlabeled) {
auto source = IndexDomainBuilder(3)
.origin({3, 5, 4})
.exclusive_max({7, 7, 10})
.Finalize()
.value();
auto target = IndexDomainBuilder(3)
.origin({4, 0, 6})
.exclusive_max({8, 4, 12})
.Finalize()
.value();
std::vector<DimensionIndex> source_matches(source.rank());
EXPECT_THAT(AlignDimensionsTo(source, target, source_matches),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Error aligning dimensions: "
"source dimension 1 \\[5, 7\\) mismatch with "
"target dimension 1 \\[0, 4\\)"));
}
} | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/index_space/alignment.cc | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/index_space/alignment_test.cc | 4f887a6430414cd6088e1743555015b10f116d50 |
625b1169-0fd7-4eea-9250-58d3f1528a04 | cpp | tensorflow/tensorflow | string_ngrams_op | tensorflow/core/kernels/string_ngrams_op.cc | tensorflow/core/kernels/string_ngrams_op_test.cc | #include <algorithm>
#include <locale>
#include <string>
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/op_requires.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace text {
namespace {
template <typename SPLITS_TYPE>
class StringNGramsOp : public tensorflow::OpKernel {
public:
explicit StringNGramsOp(tensorflow::OpKernelConstruction* context)
: tensorflow::OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("separator", &separator_));
OP_REQUIRES_OK(context, context->GetAttr("ngram_widths", &ngram_widths_));
OP_REQUIRES_OK(context, context->GetAttr("left_pad", &left_pad_));
OP_REQUIRES_OK(context, context->GetAttr("right_pad", &right_pad_));
OP_REQUIRES_OK(context, context->GetAttr("pad_width", &pad_width_));
OP_REQUIRES_OK(context, context->GetAttr("preserve_short_sequences",
&preserve_short_));
}
int get_pad_width(const int ngram_width) const {
return std::min(pad_width_ < 0 ? ngram_width - 1 : pad_width_,
ngram_width - 1);
}
absl::StatusOr<int> get_num_ngrams(const int length,
const int ngram_width) const {
int64 limit = kint32max;
int pad_width = get_pad_width(ngram_width);
if (pad_width > limit / 2 - length) {
return errors::InvalidArgument(
"Pad width could lead to integer overflow, got pad_width = ",
pad_width);
}
return std::max(0, ((length + 2 * pad_width) - ngram_width) + 1);
}
void Compute(tensorflow::OpKernelContext* context) override {
for (int ngram_width : ngram_widths_) {
OP_REQUIRES(
context, ngram_width > 0,
errors::InvalidArgument("ngram_widths must contain positive values"));
}
const tensorflow::Tensor* data;
OP_REQUIRES_OK(context, context->input("data", &data));
const auto& input_data = data->flat<tstring>().data();
const tensorflow::Tensor* splits;
OP_REQUIRES_OK(context, context->input("data_splits", &splits));
const auto& splits_vec = splits->flat<SPLITS_TYPE>();
const int input_data_size = data->flat<tstring>().size();
const int splits_vec_size = splits_vec.size();
if (splits_vec_size > 0) {
int prev_split = splits_vec(0);
OP_REQUIRES(context, prev_split == 0,
errors::InvalidArgument("First split value must be 0, got ",
prev_split));
for (int i = 1; i < splits_vec_size; ++i) {
bool valid_splits = splits_vec(i) >= prev_split;
valid_splits = valid_splits && (splits_vec(i) <= input_data_size);
OP_REQUIRES(context, valid_splits,
errors::InvalidArgument(
"Invalid split value ", splits_vec(i), ", must be in [",
prev_split, ", ", input_data_size, "]"));
prev_split = splits_vec(i);
}
OP_REQUIRES(context, prev_split == input_data_size,
errors::InvalidArgument(
"Last split value must be data size. Expected ",
input_data_size, ", got ", prev_split));
}
int num_batch_items = splits_vec.size() - 1;
tensorflow::Tensor* ngrams_splits;
OP_REQUIRES_OK(
context, context->allocate_output(1, splits->shape(), &ngrams_splits));
auto ngrams_splits_data = ngrams_splits->flat<SPLITS_TYPE>().data();
if (data->flat<tstring>().size() == 0 || splits_vec.size() == 0) {
tensorflow::Tensor* empty;
OP_REQUIRES_OK(context,
context->allocate_output(0, data->shape(), &empty));
for (int i = 0; i <= num_batch_items; ++i) {
ngrams_splits_data[i] = 0;
}
return;
}
ngrams_splits_data[0] = 0;
for (int i = 1; i <= num_batch_items; ++i) {
int length = splits_vec(i) - splits_vec(i - 1);
int num_ngrams = 0;
for (int ngram_width : ngram_widths_) {
auto ngrams_or = get_num_ngrams(length, ngram_width);
OP_REQUIRES_OK(context, ngrams_or.status());
num_ngrams += ngrams_or.value();
}
if (preserve_short_ && length > 0 && num_ngrams == 0) {
num_ngrams = 1;
}
ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams;
}
tensorflow::Tensor* ngrams;
OP_REQUIRES_OK(
context,
context->allocate_output(
0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams));
auto ngrams_data = ngrams->flat<tstring>().data();
for (int i = 0; i < num_batch_items; ++i) {
auto data_start = &input_data[splits_vec(i)];
int output_start_idx = ngrams_splits_data[i];
for (int ngram_width : ngram_widths_) {
auto output_start = &ngrams_data[output_start_idx];
int length = splits_vec(i + 1) - splits_vec(i);
auto ngrams_or = get_num_ngrams(length, ngram_width);
OP_REQUIRES_OK(context, ngrams_or.status());
int num_ngrams = ngrams_or.value();
CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
output_start_idx += num_ngrams;
}
if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) {
int data_length = splits_vec(i + 1) - splits_vec(i);
if (data_length == 0) {
continue;
}
OP_REQUIRES(
context, pad_width_ >= 0,
errors::InvalidArgument("Pad width should be >= 0 when "
"preserve_short_sequences is True and "
"ngram_widths are not provided, got ",
pad_width_));
int ngram_width = data_length + 2 * pad_width_;
auto output_start = &ngrams_data[output_start_idx];
int num_ngrams = 1;
CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
}
}
}
void CreateNgrams(const tstring* data, tstring* output, int num_ngrams,
int ngram_width) const {
for (int ngram_index = 0; ngram_index < num_ngrams; ++ngram_index) {
int pad_width = get_pad_width(ngram_width);
int left_padding = std::max(0, pad_width - ngram_index);
int right_padding =
std::max(0, pad_width - (num_ngrams - (ngram_index + 1)));
int num_tokens = ngram_width - (left_padding + right_padding);
int data_start_index = left_padding > 0 ? 0 : ngram_index - pad_width;
int ngram_size = 0;
ngram_size += left_padding * left_pad_.length();
for (int n = 0; n < num_tokens; ++n) {
ngram_size += data[data_start_index + n].length();
}
ngram_size += right_padding * right_pad_.length();
int num_separators = left_padding + right_padding + num_tokens - 1;
ngram_size += num_separators * separator_.length();
tstring* ngram = &output[ngram_index];
ngram->reserve(ngram_size);
for (int n = 0; n < left_padding; ++n) {
ngram->append(left_pad_);
ngram->append(separator_);
}
for (int n = 0; n < num_tokens - 1; ++n) {
ngram->append(data[data_start_index + n]);
ngram->append(separator_);
}
if (num_tokens > 0) {
ngram->append(data[data_start_index + num_tokens - 1]);
for (int n = 0; n < right_padding; ++n) {
ngram->append(separator_);
ngram->append(right_pad_);
}
} else {
for (int n = 0; n < right_padding - 1; ++n) {
ngram->append(right_pad_);
ngram->append(separator_);
}
ngram->append(right_pad_);
}
DCHECK_EQ(ngram_size, ngram->size());
}
}
string separator_;
string left_pad_;
string right_pad_;
bool use_pad_;
bool extend_pad_;
bool preserve_short_;
std::vector<int> ngram_widths_;
int pad_width_;
};
}
REGISTER_KERNEL_BUILDER(Name("StringNGrams")
.Device(tensorflow::DEVICE_CPU)
.TypeConstraint<int32>("Tsplits"),
StringNGramsOp<int32>);
REGISTER_KERNEL_BUILDER(Name("StringNGrams")
.Device(tensorflow::DEVICE_CPU)
.TypeConstraint<int64_t>("Tsplits"),
StringNGramsOp<int64_t>);
}
} | #include <vector>
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/shape_inference_testutil.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace tensorflow {
namespace text {
using tensorflow::FakeInput;
using tensorflow::NodeDefBuilder;
using tensorflow::Status;
using tensorflow::TensorShape;
class NgramKernelTest : public tensorflow::OpsTestBase {
public:
void MakeOp(string separator, std::vector<int> ngram_width, string left_pad,
string right_pad, int pad_width, bool preserve) {
TF_ASSERT_OK(NodeDefBuilder("tested_op", "StringNGrams")
.Attr("separator", separator)
.Attr("ngram_widths", ngram_width)
.Attr("left_pad", left_pad)
.Attr("right_pad", right_pad)
.Attr("pad_width", pad_width)
.Attr("preserve_short_sequences", preserve)
.Input(FakeInput())
.Input(FakeInput())
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
}
void assert_string_equal(const std::vector<tstring> &expected,
const Tensor &value) {
Tensor expected_tensor(
allocator(), DT_STRING,
TensorShape({static_cast<int64_t>(expected.size())}));
test::FillValues<tstring>(&expected_tensor, expected);
test::ExpectTensorEqual<tstring>(expected_tensor, value);
}
void assert_int64_equal(const std::vector<int64_t> &expected,
const Tensor &value) {
Tensor expected_tensor(
allocator(), DT_INT64,
TensorShape({static_cast<int64_t>(expected.size())}));
test::FillValues<int64_t>(&expected_tensor, expected);
test::ExpectTensorEqual<int64_t>(expected_tensor, value);
}
};
TEST_F(NgramKernelTest, TestPaddedTrigrams) {
MakeOp("|", {3}, "LP", "RP", -1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|LP|a", "LP|a|b", "a|b|c", "b|c|d", "c|d|RP", "d|RP|RP",
"LP|LP|e", "LP|e|f", "e|f|RP", "f|RP|RP"});
std::vector<int64_t> expected_splits({0, 6, 10});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestPaddedBigramsAndTrigrams) {
MakeOp("|", {2, 3}, "LP", "RP", -1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|a", "a|b", "b|c", "c|d", "d|RP", "LP|LP|a", "LP|a|b", "a|b|c",
"b|c|d", "c|d|RP", "d|RP|RP",
"LP|e", "e|f", "f|RP", "LP|LP|e", "LP|e|f", "e|f|RP", "f|RP|RP"});
std::vector<int64_t> expected_splits({0, 11, 18});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestPaddedBigrams) {
MakeOp("|", {2}, "LP", "RP", -1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|a", "a|b", "b|c", "c|d", "d|RP",
"LP|e", "e|f", "f|RP"});
std::vector<int64_t> expected_splits({0, 5, 8});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestPaddingIsAtMostNGramSizeMinus1) {
MakeOp("|", {2}, "LP", "RP", 4, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|a", "a|b", "b|c", "c|d", "d|RP",
"LP|e", "e|f", "f|RP"});
std::vector<int64_t> expected_splits({0, 5, 8});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestPaddedUnigramAndBigrams) {
MakeOp("|", {1, 2}, "LP", "RP", -1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"a", "b", "c", "d", "LP|a", "a|b", "b|c", "c|d", "d|RP",
"e", "f", "LP|e", "e|f", "f|RP"});
std::vector<int64_t> expected_splits({0, 9, 14});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestOverlappingPaddedNGrams) {
MakeOp("|", {3}, "LP", "RP", -1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 1, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|LP|a", "LP|a|RP", "a|RP|RP",
"LP|LP|b", "LP|b|c", "b|c|d", "c|d|RP", "d|RP|RP",
"LP|LP|e", "LP|e|f", "e|f|RP", "f|RP|RP"});
std::vector<int64_t> expected_splits({0, 3, 8, 12});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestOverlappingPaddedMultiCharNGrams) {
MakeOp("|", {3}, "LP", "RP", -1, false);
AddInputFromArray<tstring>(TensorShape({6}),
{"aa", "bb", "cc", "dd", "ee", "ff"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 1, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|LP|aa", "LP|aa|RP", "aa|RP|RP",
"LP|LP|bb", "LP|bb|cc", "bb|cc|dd", "cc|dd|RP", "dd|RP|RP",
"LP|LP|ee", "LP|ee|ff", "ee|ff|RP", "ff|RP|RP"});
std::vector<int64_t> expected_splits({0, 3, 8, 12});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestMultiOverlappingPaddedNGrams) {
MakeOp("|", {5}, "LP", "RP", -1, false);
AddInputFromArray<tstring>(TensorShape({1}), {"a"});
AddInputFromArray<int64_t>(TensorShape({2}), {0, 1});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"LP|LP|LP|LP|a", "LP|LP|LP|a|RP",
"LP|LP|a|RP|RP", "LP|a|RP|RP|RP",
"a|RP|RP|RP|RP"});
std::vector<int64_t> expected_splits({0, 5});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedTrigrams) {
MakeOp("|", {3}, "", "", 0, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"a|b|c", "b|c|d"});
std::vector<int64_t> expected_splits({0, 2, 2});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedTrigramsWithEmptySequence) {
MakeOp("|", {3}, "", "", 0, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 4, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"a|b|c", "b|c|d"});
std::vector<int64_t> expected_splits({0, 2, 2, 2});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedTrigramsWithPreserveShort) {
MakeOp("|", {3}, "", "", 0, true);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"a|b|c", "b|c|d", "e|f"});
std::vector<int64_t> expected_splits({0, 2, 3});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedTrigramsWithPreserveShortAndEmptySequence) {
MakeOp("|", {3}, "", "", 0, true);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 4, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"a|b|c", "b|c|d", "e|f"});
std::vector<int64_t> expected_splits({0, 2, 2, 3});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedTrigramsAndQuadgramsWithPreserveShort) {
MakeOp("|", {4, 3}, "", "", 0, true);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"a|b|c|d", "a|b|c", "b|c|d", "e|f"});
std::vector<int64_t> expected_splits({0, 3, 4});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedBigramsAndTrigrams) {
MakeOp("|", {2, 3}, "", "", 0, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"a|b", "b|c", "c|d", "a|b|c", "b|c|d", "e|f"});
std::vector<int64_t> expected_splits({0, 5, 6});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedBigramsAndTrigramsWithPreserveShort) {
MakeOp("|", {2, 3}, "", "", 0, true);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"a|b", "b|c", "c|d", "a|b|c", "b|c|d", "e|f"});
std::vector<int64_t> expected_splits({0, 5, 6});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedTrigramsAndBigramsWithPreserveShort) {
MakeOp("|", {3, 2}, "", "", 0, true);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"a|b|c", "b|c|d", "a|b", "b|c", "c|d", "e|f"});
std::vector<int64_t> expected_splits({0, 5, 6});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestUnpaddedBigrams) {
MakeOp("|", {2}, "", "", 0, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"a|b", "b|c", "c|d", "e|f"});
std::vector<int64_t> expected_splits({0, 3, 4});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestOverlappingUnpaddedNGrams) {
MakeOp("|", {3}, "", "", 0, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 1, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"b|c|d"});
std::vector<int64_t> expected_splits({0, 0, 1, 1});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestOverlappingUnpaddedNGramsNoOutput) {
MakeOp("|", {5}, "", "", 0, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 1, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({});
std::vector<int64_t> expected_splits({0, 0, 0, 0});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestSinglyPaddedTrigrams) {
MakeOp("|", {3}, "LP", "RP", 1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"LP|a|b", "a|b|c", "b|c|d",
"c|d|RP",
"LP|e|f", "e|f|RP"});
std::vector<int64_t> expected_splits({0, 4, 6});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestSinglyPaddedBigrams) {
MakeOp("|", {2}, "LP", "RP", 1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"LP|a", "a|b", "b|c", "c|d", "d|RP",
"LP|e", "e|f", "f|RP"});
std::vector<int64_t> expected_splits({0, 5, 8});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestSinglyPaddedBigramsAnd5grams) {
MakeOp("|", {2, 5}, "LP", "RP", 1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|a", "a|b", "b|c", "c|d", "d|RP", "LP|a|b|c|d", "a|b|c|d|RP",
"LP|e", "e|f", "f|RP"});
std::vector<int64_t> expected_splits({0, 7, 10});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestSinglyPadded5gramsWithPreserveShort) {
MakeOp("|", {5}, "LP", "RP", 1, true);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|a|b|c|d", "a|b|c|d|RP",
"LP|e|f|RP"});
std::vector<int64_t> expected_splits({0, 2, 3});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestOverlappingSinglyPaddedNGrams) {
MakeOp("|", {3}, "LP", "RP", 1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 1, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"LP|a|RP",
"LP|b|c", "b|c|d", "c|d|RP",
"LP|e|f", "e|f|RP"});
std::vector<int64_t> expected_splits({0, 1, 4, 6});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestOverlappingSinglyPaddedNGramsNoOutput) {
MakeOp("|", {5}, "LP", "RP", 1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({4}), {0, 1, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"LP|b|c|d|RP"});
std::vector<int64_t> expected_splits({0, 0, 1, 1});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestSinglyPaddedUnigrams) {
MakeOp("|", {1}, "LP", "RP", 1, false);
AddInputFromArray<tstring>(TensorShape({6}), {"a", "b", "c", "d", "e", "f"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 4, 6});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({"a", "b", "c", "d", "e", "f"});
std::vector<int64_t> expected_splits({0, 4, 6});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestEmptyInput) {
MakeOp("|", {1}, "LP", "RP", 3, false);
AddInputFromArray<tstring>(TensorShape({0}), {});
AddInputFromArray<int64_t>(TensorShape({0}), {});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({});
std::vector<int64_t> expected_splits({});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestNoTokens) {
MakeOp("|", {3}, "L", "R", -1, false);
AddInputFromArray<tstring>(TensorShape({1}), {"a"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 0, 1});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values(
{"L|L|R", "L|R|R",
"L|L|a", "L|a|R", "a|R|R"});
std::vector<int64_t> expected_splits({0, 2, 5});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, TestNoTokensNoPad) {
MakeOp("|", {3}, "", "", 0, false);
AddInputFromArray<tstring>(TensorShape({1}), {"a"});
AddInputFromArray<int64_t>(TensorShape({3}), {0, 0, 1});
TF_ASSERT_OK(RunOpKernel());
std::vector<tstring> expected_values({});
std::vector<int64_t> expected_splits({0, 0, 0});
assert_string_equal(expected_values, *GetOutput(0));
assert_int64_equal(expected_splits, *GetOutput(1));
}
TEST_F(NgramKernelTest, ShapeFn) {
ShapeInferenceTestOp op("StringNGrams");
INFER_OK(op, "?;?", "[?];[?]");
INFER_OK(op, "[1];?", "[?];[?]");
INFER_OK(op, "[1];[2]", "[?];in1");
INFER_ERROR("Shape must be rank 1 but is rank 0", op, "[];?");
INFER_ERROR("Shape must be rank 1 but is rank 0", op, "?;[]");
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/string_ngrams_op.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/string_ngrams_op_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
1ce618e4-f93e-4209-bb33-5fcea4ce081e | cpp | tensorflow/tensorflow | worker_client | tensorflow/core/data/service/worker_client.cc | tensorflow/core/data/service/worker_client_test.cc | #include "tensorflow/core/data/service/worker_client.h"
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "grpcpp/client_context.h"
#include "grpcpp/create_channel.h"
#include "grpcpp/security/credentials.h"
#include "grpcpp/support/channel_arguments.h"
#include "grpcpp/support/status.h"
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "tensorflow/core/data/service/credentials_factory.h"
#include "tensorflow/core/data/service/data_transfer.h"
#include "tensorflow/core/data/service/grpc_util.h"
#include "tensorflow/core/data/service/worker.grpc.pb.h"
#include "tensorflow/core/data/service/worker.pb.h"
#include "tensorflow/core/data/service/worker_impl.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/dataset.pb.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/host_info.h"
namespace tensorflow {
namespace data {
absl::StatusOr<std::unique_ptr<DataServiceWorkerClient>>
CreateDataServiceWorkerClient(
const std::string& dispatcher_protocol, const DataTransferServerInfo& info,
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info,
Allocator* allocator) {
auto client = std::make_unique<DataServiceWorkerClient>(
info.address(), dispatcher_protocol, info.protocol(),
accelerator_device_info, allocator);
TF_RETURN_IF_ERROR(client->Initialize());
TF_RETURN_WITH_CONTEXT_IF_ERROR(
client->CheckCompatibility(info.compatibility_info()),
"for data transfer protocol '", client->GetDataTransferProtocol(),
"', the compatibility check between the trainer worker and the ",
"tf.data service worker at ", info.address(), "failed");
return client;
}
Status DataServiceWorkerClient::GetElement(const GetElementRequest& req,
GetElementResult& result) {
TF_RETURN_IF_ERROR(EnsureInitialized());
return client_->GetElement(req, result);
}
Status DataServiceWorkerClient::EnsureInitialized() {
mutex_lock l(mu_);
if (client_) {
return absl::OkStatus();
}
TF_RETURN_IF_ERROR(DataTransferClient::Build(
GetDataTransferProtocol(),
{protocol_, address_, accelerator_device_info_, allocator_}, &client_));
return absl::OkStatus();
}
std::string DataServiceWorkerClient::GetDataTransferProtocol() const {
if (ForceLocalProtocol(address_)) {
return kLocalTransferProtocol;
}
return transfer_protocol_;
}
void DataServiceWorkerClient::TryCancel() { client_->TryCancel(); }
class GrpcDataTransferClient : public DataTransferClient {
public:
GrpcDataTransferClient(std::shared_ptr<grpc::ChannelCredentials> credentials,
std::string address, Allocator* allocator)
: allocator_(allocator) {
VLOG(2) << "Create GrpcDataTransferClient for worker " << address << ".";
grpc::ChannelArguments args;
args.SetMaxReceiveMessageSize(-1);
auto channel = grpc::CreateCustomChannel(address, credentials, args);
stub_ = WorkerService::NewStub(channel);
}
Status GetElement(const GetElementRequest& req,
GetElementResult& result) override {
VLOG(3) << "GetElement for task " << req.task_id() << " from gRPC worker "
<< "server.";
{
mutex_lock l(mu_);
if (cancelled_) {
return errors::Cancelled("Client was cancelled.");
}
}
grpc::ClientContext ctx;
gtl::Cleanup<std::function<void()>> cleanup;
{
mutex_lock l(mu_);
active_contexts_.insert(&ctx);
cleanup = gtl::MakeCleanup([this, &ctx] {
mutex_lock l(mu_);
active_contexts_.erase(&ctx);
});
}
GetElementResponse resp;
int64_t start_time_us = env_->NowMicros();
grpc::Status s = stub_->GetElement(&ctx, req, &resp);
int64_t end_time_us = env_->NowMicros();
if (!s.ok()) {
return grpc_util::WrapError("Failed to get element", s);
}
metrics::RecordTFDataServiceGetElementDuration(kGrpcTransferProtocol,
end_time_us - start_time_us);
result.end_of_sequence = resp.end_of_sequence();
result.skip = resp.skip_task();
switch (resp.element_case()) {
case GetElementResponse::kCompressed: {
Tensor tensor(DT_VARIANT, TensorShape{});
tensor.scalar<Variant>()() = std::move(resp.compressed());
result.components.push_back(tensor);
break;
}
case GetElementResponse::kUncompressed:
for (const auto& component : resp.uncompressed().components()) {
result.components.emplace_back();
bool success =
allocator_ != nullptr
? result.components.back().FromProto(allocator_, component)
: result.components.back().FromProto(component);
if (!success) {
return errors::Internal("Failed to parse tensor.");
}
}
break;
case GetElementResponse::ELEMENT_NOT_SET:
break;
}
return absl::OkStatus();
}
void TryCancel() override {
VLOG(2) << "Cancel GrpcDataTransferClient.";
mutex_lock l(mu_);
cancelled_ = true;
for (const auto& ctx : active_contexts_) {
ctx->TryCancel();
}
}
private:
Allocator* const allocator_;
mutex mu_;
std::unique_ptr<WorkerService::Stub> stub_;
absl::flat_hash_set<::grpc::ClientContext*> active_contexts_
TF_GUARDED_BY(mu_);
bool cancelled_ TF_GUARDED_BY(mu_) = false;
};
class GrpcTransferClientRegistrar {
public:
GrpcTransferClientRegistrar() {
DataTransferClient::Register(
kGrpcTransferProtocol, [](DataTransferClient::Config config,
std::unique_ptr<DataTransferClient>* out) {
std::shared_ptr<grpc::ChannelCredentials> credentials;
TF_RETURN_IF_ERROR(CredentialsFactory::CreateClientCredentials(
config.protocol, &credentials));
*out = std::make_unique<GrpcDataTransferClient>(
credentials, config.address, config.allocator);
return absl::OkStatus();
});
}
};
static GrpcTransferClientRegistrar gprc_client_registrar;
class LocalDataTransferClient : public DataTransferClient {
public:
explicit LocalDataTransferClient(absl::string_view worker_address)
: worker_address_(worker_address) {
VLOG(2) << "Create LocalDataTransferClient for worker " << worker_address_
<< ".";
}
Status GetElement(const GetElementRequest& req,
GetElementResult& result) override {
VLOG(3) << "GetElement for task " << req.task_id() << " from local worker.";
TF_RETURN_IF_ERROR(VerifyClientIsNotCancelled());
TF_ASSIGN_OR_RETURN(std::shared_ptr<DataServiceWorkerImpl> worker,
GetWorker(req));
int64_t start_time_us = env_->NowMicros();
Status s = worker->GetElementResult(&req, &result);
int64_t end_time_us = env_->NowMicros();
TF_RETURN_IF_ERROR(s);
metrics::RecordTFDataServiceGetElementDuration(kLocalTransferProtocol,
end_time_us - start_time_us);
return s;
}
void TryCancel() override {
VLOG(2) << "Cancel LocalDataTransferClient for worker " << worker_address_
<< ".";
mutex_lock l(mu_);
cancelled_ = true;
}
private:
Status VerifyClientIsNotCancelled() TF_LOCKS_EXCLUDED(mu_) {
mutex_lock l(mu_);
if (cancelled_) {
return errors::Cancelled(absl::Substitute(
"Client for worker $0 has been cancelled.", worker_address_));
}
return absl::OkStatus();
}
absl::StatusOr<std::shared_ptr<DataServiceWorkerImpl>> GetWorker(
const GetElementRequest& req) const {
std::shared_ptr<DataServiceWorkerImpl> worker =
LocalWorkers::Get(worker_address_);
if (!worker) {
return errors::Cancelled(absl::Substitute(
"Local worker at address $0 is no longer available; cancel request "
"for task $1.",
worker_address_, req.task_id()));
}
return worker;
}
const std::string worker_address_;
mutex mu_;
bool cancelled_ TF_GUARDED_BY(mu_) = false;
};
class LocalTransferClientRegistrar {
public:
LocalTransferClientRegistrar() {
DataTransferClient::Register(
kLocalTransferProtocol, [](DataTransferClient::Config config,
std::unique_ptr<DataTransferClient>* out) {
*out = std::make_unique<LocalDataTransferClient>(config.address);
return absl::OkStatus();
});
}
};
static LocalTransferClientRegistrar local_client_registrar;
bool ForceLocalProtocol(const std::string& worker_address) {
if (tsl::port::JobUid() == -1) {
return false;
}
return LocalWorkers::Get(worker_address) != nullptr;
}
}
} | #include "tensorflow/core/data/service/worker_client.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/substitute.h"
#include "absl/types/optional.h"
#include "tensorflow/core/data/service/common.h"
#include "tensorflow/core/data/service/common.pb.h"
#include "tensorflow/core/data/service/data_transfer.h"
#include "tensorflow/core/data/service/dispatcher.pb.h"
#include "tensorflow/core/data/service/dispatcher_client.h"
#include "tensorflow/core/data/service/test_cluster.h"
#include "tensorflow/core/data/service/test_util.h"
#include "tensorflow/core/data/service/worker.pb.h"
#include "tensorflow/core/data/service/worker_impl.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/status_matchers.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/data_service.pb.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
namespace tensorflow {
namespace data {
namespace {
using ::tensorflow::data::testing::RangeSquareDataset;
using ::tensorflow::testing::StatusIs;
using ::testing::MatchesRegex;
constexpr const char kProtocol[] = "grpc";
constexpr const char kAltTransferProtocol[] = "alt";
class WorkerClientTest : public ::testing::TestWithParam<std::string> {
protected:
void SetUp() override { InitializeTestCluster(); }
void InitializeTestCluster(
std::optional<std::string> data_transfer_protocol = std::nullopt) {
test_cluster_ = std::make_unique<TestCluster>(1,
data_transfer_protocol);
TF_ASSERT_OK(test_cluster_->Initialize());
dispatcher_client_ = std::make_unique<DataServiceDispatcherClient>(
test_cluster_->DispatcherAddress(), kProtocol);
}
absl::StatusOr<std::string> RegisterDataset(const int64_t range) {
const auto dataset_def = RangeSquareDataset(range);
std::string dataset_id;
TF_RETURN_IF_ERROR(dispatcher_client_->RegisterDataset(
dataset_def, DataServiceMetadata(),
std::nullopt, dataset_id));
return dataset_id;
}
absl::StatusOr<int64_t> CreateIteration(const std::string& dataset_id) {
ProcessingModeDef processing_mode;
processing_mode.set_sharding_policy(ProcessingModeDef::OFF);
int64_t job_id = 0;
TF_RETURN_IF_ERROR(dispatcher_client_->GetOrCreateJob(
dataset_id, processing_mode, std::nullopt,
std::nullopt, false,
TARGET_WORKERS_AUTO, job_id));
int64_t iteration_client_id = 0;
TF_RETURN_IF_ERROR(dispatcher_client_->GetOrCreateIteration(
job_id, 0, iteration_client_id));
return iteration_client_id;
}
absl::StatusOr<int64_t> GetTaskToRead(const int64_t iteration_client_id) {
ClientHeartbeatRequest request;
ClientHeartbeatResponse response;
request.set_iteration_client_id(iteration_client_id);
TF_RETURN_IF_ERROR(dispatcher_client_->ClientHeartbeat(request, response));
if (response.task_info().empty()) {
return errors::NotFound(absl::Substitute(
"No task found for iteration $0.", iteration_client_id));
}
return response.task_info(0).task_id();
}
absl::StatusOr<std::unique_ptr<DataServiceWorkerClient>> GetWorkerClient(
const std::string& data_transfer_protocol) {
DataTransferServerInfo info;
info.set_address(GetWorkerAddress());
info.set_protocol(data_transfer_protocol);
return CreateDataServiceWorkerClient(kProtocol, info,
nullptr,
nullptr);
}
absl::StatusOr<GetElementResult> GetElement(DataServiceWorkerClient& client,
const int64_t task_id) {
GetElementRequest request;
GetElementResult result;
request.set_task_id(task_id);
TF_RETURN_IF_ERROR(client.GetElement(request, result));
return result;
}
std::string GetDispatcherAddress() const {
return test_cluster_->DispatcherAddress();
}
std::string GetWorkerAddress() const {
return test_cluster_->WorkerAddress(0);
}
std::unique_ptr<TestCluster> test_cluster_;
std::unique_ptr<DataServiceDispatcherClient> dispatcher_client_;
};
class AltDataTransferServer : public DataTransferServer {
public:
explicit AltDataTransferServer(DataTransferServer::GetElementT get_element)
: get_element_(get_element) {}
absl::Status GetElement(const GetElementRequest& req,
GetElementResult& result) {
return get_element_(&req, &result);
}
absl::Status Start(const experimental::WorkerConfig& config) override {
return absl::OkStatus();
}
int Port() const override { return -1; }
private:
DataTransferServer::GetElementT get_element_;
};
class AltDataTransferClient : public DataTransferClient {
public:
explicit AltDataTransferClient(std::shared_ptr<AltDataTransferServer> server)
: server_(server) {}
absl::Status GetElement(const GetElementRequest& req,
GetElementResult& result) override {
return server_->GetElement(req, result);
}
void TryCancel() override {}
private:
std::shared_ptr<AltDataTransferServer> server_;
};
class AltDataTransferRegistrar {
public:
AltDataTransferRegistrar() {
DataTransferServer::Register(
kAltTransferProtocol,
[this](DataTransferServer::GetElementT get_element,
std::shared_ptr<DataTransferServer>* server) {
server_ = std::make_shared<AltDataTransferServer>(get_element);
*server = server_;
return absl::OkStatus();
});
DataTransferClient::Register(
kAltTransferProtocol,
[this](DataTransferClient::Config config,
std::unique_ptr<DataTransferClient>* client) {
*client = std::make_unique<AltDataTransferClient>(server_);
return absl::OkStatus();
});
}
private:
std::shared_ptr<AltDataTransferServer> server_ = nullptr;
};
static AltDataTransferRegistrar alt_data_transfer_registrar;
class DataTransferProtocolWorkerClientTest : public WorkerClientTest {
protected:
void SetUp() override {
std::string data_transfer_protocol = GetParam();
InitializeTestCluster(data_transfer_protocol);
}
};
TEST_F(WorkerClientTest, LocalRead) {
const int64_t range = 5;
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id, RegisterDataset(range));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
for (int64_t i = 0; i < range; ++i) {
TF_ASSERT_OK_AND_ASSIGN(GetElementResult result,
GetElement(*client, task_id));
test::ExpectEqual(result.components[0], Tensor(int64_t{i * i}));
EXPECT_FALSE(result.end_of_sequence);
}
LocalWorkers::Remove(GetWorkerAddress());
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Local worker.*is no longer available.*")));
}
TEST_F(WorkerClientTest, LocalReadEmptyDataset) {
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id,
RegisterDataset(0));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
TF_ASSERT_OK_AND_ASSIGN(GetElementResult result,
GetElement(*client, task_id));
EXPECT_TRUE(result.end_of_sequence);
LocalWorkers::Remove(GetWorkerAddress());
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Local worker.*is no longer available.*")));
}
TEST_P(DataTransferProtocolWorkerClientTest, NetworkRead) {
std::string data_transfer_protocol = GetParam();
LocalWorkers::Remove(GetWorkerAddress());
const int64_t range = 5;
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id, RegisterDataset(range));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(data_transfer_protocol));
for (int64_t i = 0; i < range; ++i) {
TF_ASSERT_OK_AND_ASSIGN(GetElementResult result,
GetElement(*client, task_id));
test::ExpectEqual(result.components[0], Tensor(int64_t{i * i}));
EXPECT_FALSE(result.end_of_sequence);
}
}
INSTANTIATE_TEST_SUITE_P(
NetworkProtocols, DataTransferProtocolWorkerClientTest,
::testing::Values(kGrpcTransferProtocol, kAltTransferProtocol),
[](const ::testing::TestParamInfo<
DataTransferProtocolWorkerClientTest::ParamType>& info) {
return info.param;
});
TEST_F(WorkerClientTest, LocalServerShutsDown) {
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id,
RegisterDataset(5));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
test_cluster_->StopWorkers();
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Local worker.*is no longer available.*")));
}
TEST_F(WorkerClientTest, CancelClient) {
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id,
RegisterDataset(5));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
client->TryCancel();
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Client for worker.*has been cancelled.")));
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/data/service/worker_client.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/data/service/worker_client_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
4b72f2e1-377f-44c8-8739-38c4935bd9a9 | cpp | tensorflow/tensorflow | preemption_notifier | third_party/xla/xla/tsl/distributed_runtime/preemption/preemption_notifier.cc | third_party/xla/xla/tsl/distributed_runtime/preemption/preemption_notifier_test.cc | #include "xla/tsl/distributed_runtime/preemption/preemption_notifier.h"
#include <atomic>
#include <csignal>
#include <functional>
#include <memory>
#include <utility>
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/statusor.h"
#if defined(PLATFORM_GOOGLE)
#include "thread/executor.h"
#include "thread/signal.h"
#endif
namespace tsl {
namespace {
constexpr absl::Duration kListenInterval = absl::Seconds(1);
constexpr absl::Time kUnsetDeathTime = absl::InfinitePast();
static std::atomic_bool sigterm_received(false);
class SigtermNotifier : public PreemptionNotifier {
public:
explicit SigtermNotifier(Env* env);
~SigtermNotifier() override {
shutdown_notification_.Notify();
}
private:
void StartListenerThread();
absl::Notification shutdown_notification_;
std::unique_ptr<Thread> preempt_listener_thread_;
};
SigtermNotifier::SigtermNotifier(Env* env) : PreemptionNotifier(env) {
sigterm_received.store(false);
StartListenerThread();
#if defined(PLATFORM_GOOGLE)
thread::signal::Token unused_token;
thread::signal::AddHandler(
SIGTERM, thread::Executor::DefaultExecutor(),
[]() { sigterm_received.store(true); },
0,
&unused_token);
#else
std::signal(SIGTERM, [](int signal) { sigterm_received.store(true); });
#endif
}
void SigtermNotifier::StartListenerThread() {
preempt_listener_thread_.reset(
GetEnv()->StartThread({}, "PreemptionNotifier_Listen", [this]() {
while (!sigterm_received.load()) {
if (shutdown_notification_.WaitForNotificationWithTimeout(
kListenInterval)) {
NotifyRegisteredListeners(
errors::Cancelled("Preemption notifier is being deleted."));
return;
}
}
const absl::Time death_time = absl::Now();
LOG(WARNING) << "SIGTERM caught at " << death_time;
NotifyRegisteredListeners(death_time);
}));
}
}
absl::StatusOr<absl::Time> PreemptionNotifier::WillBePreemptedAt() {
absl::Notification n;
absl::StatusOr<absl::Time> result;
WillBePreemptedAtAsync(
[&n, &result](absl::StatusOr<absl::Time> async_result) {
result = async_result;
n.Notify();
});
n.WaitForNotification();
return result;
}
void PreemptionNotifier::WillBePreemptedAtAsync(PreemptTimeCallback callback) {
mutex_lock l(mu_);
if (death_time_ == kUnsetDeathTime) {
callbacks_.push_back(std::move(callback));
} else {
callback(death_time_);
}
}
void PreemptionNotifier::NotifyRegisteredListeners(
absl::StatusOr<absl::Time> death_time) {
mutex_lock l(mu_);
if (death_time.ok()) {
death_time_ = death_time.value();
}
for (const auto& callback : callbacks_) {
callback(death_time);
}
callbacks_.clear();
}
REGISTER_PREEMPTION_NOTIFIER(
"sigterm", [](Env* env) -> std::unique_ptr<PreemptionNotifier> {
return std::make_unique<SigtermNotifier>(env);
});
} | #include "xla/tsl/distributed_runtime/preemption/preemption_notifier.h"
#include <csignal>
#include <functional>
#include <memory>
#include <utility>
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#if defined(PLATFORM_GOOGLE)
#include "thread/executor.h"
#include "thread/signal.h"
#endif
namespace tsl {
namespace {
class PreemptNotifierTest : public ::testing::Test {
public:
PreemptNotifierTest() {
#if defined(PLATFORM_GOOGLE)
thread::signal::Token unused_token;
thread::signal::AddHandler(
SIGTERM, thread::Executor::DefaultExecutor(), []() {},
thread::signal::kOverrideDefault, &unused_token);
#endif
}
};
TEST_F(PreemptNotifierTest, WillBePreemptedAt) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
absl::Time start_time = absl::Now();
env->SchedClosureAfter(absl::ToInt64Microseconds(absl::Seconds(1)),
[]() { std::raise(SIGTERM); });
absl::StatusOr<absl::Time> result = preempt_notifier->WillBePreemptedAt();
TF_CHECK_OK(result.status());
absl::Time preempt_time = result.value();
absl::Duration time_diff = preempt_time - start_time;
EXPECT_GT(time_diff, absl::Seconds(1.0));
EXPECT_LT(time_diff, absl::Seconds(3));
}
TEST_F(PreemptNotifierTest,
WillBePreemptedAt_AlreadyPreempted_ReturnsImmediately) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
absl::Time start_time = absl::Now();
std::raise(SIGTERM);
env->SleepForMicroseconds(absl::ToInt64Microseconds(absl::Seconds(2)));
absl::StatusOr<absl::Time> result = preempt_notifier->WillBePreemptedAt();
TF_CHECK_OK(result.status());
absl::Time preempt_time = result.value();
absl::Duration time_diff = preempt_time - start_time;
EXPECT_GT(time_diff, absl::ZeroDuration());
EXPECT_LT(time_diff, absl::Seconds(2));
}
TEST_F(PreemptNotifierTest, WillBePreemptedAtAsync_SameResultForAllCallbacks) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
env->SchedClosureAfter(absl::ToInt64Microseconds(absl::Seconds(1)),
[]() { std::raise(SIGTERM); });
absl::StatusOr<absl::Time> preempt_time;
absl::StatusOr<absl::Time> preempt_time_2;
absl::Notification n;
absl::Notification n_2;
preempt_notifier->WillBePreemptedAtAsync(
[&preempt_time, &n](absl::StatusOr<absl::Time> result) {
preempt_time = result;
n.Notify();
});
preempt_notifier->WillBePreemptedAtAsync(
[&preempt_time_2, &n_2](absl::StatusOr<absl::Time> result) {
preempt_time_2 = result;
n_2.Notify();
});
n.WaitForNotification();
n_2.WaitForNotification();
TF_CHECK_OK(preempt_time.status());
TF_CHECK_OK(preempt_time_2.status());
EXPECT_EQ(preempt_time.value(), preempt_time_2.value());
}
TEST_F(PreemptNotifierTest, Reset_TwoDifferentPreemptTimesRecorded) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
std::raise(SIGTERM);
absl::StatusOr<absl::Time> result = preempt_notifier->WillBePreemptedAt();
TF_CHECK_OK(result.status());
absl::Time preempt_time = result.value();
preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
std::raise(SIGTERM);
absl::Time preempt_time_2 = preempt_notifier->WillBePreemptedAt().value();
EXPECT_NE(preempt_time, preempt_time_2);
}
TEST_F(PreemptNotifierTest, DestructorCancelsPendingCalls) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
absl::StatusOr<absl::Time> result;
absl::Notification n;
preempt_notifier->WillBePreemptedAtAsync(
[&result, &n](absl::StatusOr<absl::Time> status_or_time) {
result = status_or_time;
n.Notify();
});
preempt_notifier = nullptr;
n.WaitForNotification();
EXPECT_TRUE(errors::IsCancelled(result.status()));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tsl/distributed_runtime/preemption/preemption_notifier.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tsl/distributed_runtime/preemption/preemption_notifier_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
f5697065-59c0-4051-9bd7-069f12d245b5 | cpp | google/cel-cpp | cel_function_adapter | eval/public/cel_function_adapter.h | eval/public/cel_function_adapter_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_FUNCTION_ADAPTER_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CEL_FUNCTION_ADAPTER_H_
#include <cstdint>
#include <functional>
#include <optional>
#include <type_traits>
#include <utility>
#include "google/protobuf/message.h"
#include "absl/status/status.h"
#include "eval/public/cel_function_adapter_impl.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/cel_proto_wrapper.h"
namespace google::api::expr::runtime {
namespace internal {
struct ProtoAdapterTypeCodeMatcher {
template <typename T>
constexpr static std::optional<CelValue::Type> type_code() {
if constexpr (std::is_same_v<T, const google::protobuf::Message*>) {
return CelValue::Type::kMessage;
} else {
return internal::TypeCodeMatcher().type_code<T>();
}
}
};
struct ProtoAdapterValueConverter
: public internal::ValueConverterBase<ProtoAdapterValueConverter> {
using BaseType = internal::ValueConverterBase<ProtoAdapterValueConverter>;
using BaseType::NativeToValue;
using BaseType::ValueToNative;
absl::Status NativeToValue(const ::google::protobuf::Message* value,
::google::protobuf::Arena* arena, CelValue* result) {
if (value == nullptr) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Null Message pointer returned");
}
*result = CelProtoWrapper::CreateMessage(value, arena);
return absl::OkStatus();
}
};
}
template <typename ReturnType, typename... Arguments>
using FunctionAdapter =
internal::FunctionAdapterImpl<internal::ProtoAdapterTypeCodeMatcher,
internal::ProtoAdapterValueConverter>::
FunctionAdapter<ReturnType, Arguments...>;
template <typename ReturnType, typename T>
using UnaryFunctionAdapter = internal::FunctionAdapterImpl<
internal::ProtoAdapterTypeCodeMatcher,
internal::ProtoAdapterValueConverter>::UnaryFunction<ReturnType, T>;
template <typename ReturnType, typename T, typename U>
using BinaryFunctionAdapter = internal::FunctionAdapterImpl<
internal::ProtoAdapterTypeCodeMatcher,
internal::ProtoAdapterValueConverter>::BinaryFunction<ReturnType, T, U>;
}
#endif | #include "eval/public/cel_function_adapter.h"
#include <functional>
#include <string>
#include <utility>
#include <vector>
#include "internal/status_macros.h"
#include "internal/testing.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
TEST(CelFunctionAdapterTest, TestAdapterNoArg) {
auto func = [](google::protobuf::Arena*) -> int64_t { return 100; };
ASSERT_OK_AND_ASSIGN(
auto cel_func, (FunctionAdapter<int64_t>::Create("const", false, func)));
absl::Span<CelValue> args;
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsInt64());
}
TEST(CelFunctionAdapterTest, TestAdapterOneArg) {
std::function<int64_t(google::protobuf::Arena*, int64_t)> func =
[](google::protobuf::Arena* arena, int64_t i) -> int64_t { return i + 1; };
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<int64_t, int64_t>::Create("_++_", false, func)));
std::vector<CelValue> args_vec;
args_vec.push_back(CelValue::CreateInt64(99));
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
absl::Span<CelValue> args(&args_vec[0], args_vec.size());
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 100);
}
TEST(CelFunctionAdapterTest, TestAdapterTwoArgs) {
auto func = [](google::protobuf::Arena* arena, int64_t i, int64_t j) -> int64_t {
return i + j;
};
ASSERT_OK_AND_ASSIGN(auto cel_func,
(FunctionAdapter<int64_t, int64_t, int64_t>::Create(
"_++_", false, func)));
std::vector<CelValue> args_vec;
args_vec.push_back(CelValue::CreateInt64(20));
args_vec.push_back(CelValue::CreateInt64(22));
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
absl::Span<CelValue> args(&args_vec[0], args_vec.size());
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsInt64());
EXPECT_EQ(result.Int64OrDie(), 42);
}
using StringHolder = CelValue::StringHolder;
TEST(CelFunctionAdapterTest, TestAdapterThreeArgs) {
auto func = [](google::protobuf::Arena* arena, StringHolder s1, StringHolder s2,
StringHolder s3) -> StringHolder {
std::string value = absl::StrCat(s1.value(), s2.value(), s3.value());
return StringHolder(
google::protobuf::Arena::Create<std::string>(arena, std::move(value)));
};
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<StringHolder, StringHolder, StringHolder,
StringHolder>::Create("concat", false, func)));
std::string test1 = "1";
std::string test2 = "2";
std::string test3 = "3";
std::vector<CelValue> args_vec;
args_vec.push_back(CelValue::CreateString(&test1));
args_vec.push_back(CelValue::CreateString(&test2));
args_vec.push_back(CelValue::CreateString(&test3));
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
absl::Span<CelValue> args(&args_vec[0], args_vec.size());
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsString());
EXPECT_EQ(result.StringOrDie().value(), "123");
}
TEST(CelFunctionAdapterTest, TestTypeDeductionForCelValueBasicTypes) {
auto func = [](google::protobuf::Arena* arena, bool, int64_t, uint64_t, double,
CelValue::StringHolder, CelValue::BytesHolder,
const google::protobuf::Message*, absl::Duration, absl::Time,
const CelList*, const CelMap*,
const CelError*) -> bool { return false; };
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<bool, bool, int64_t, uint64_t, double,
CelValue::StringHolder, CelValue::BytesHolder,
const google::protobuf::Message*, absl::Duration, absl::Time,
const CelList*, const CelMap*,
const CelError*>::Create("dummy_func", false, func)));
auto descriptor = cel_func->descriptor();
EXPECT_EQ(descriptor.receiver_style(), false);
EXPECT_EQ(descriptor.name(), "dummy_func");
int pos = 0;
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kBool);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kInt64);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kUint64);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kDouble);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kString);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kBytes);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kMessage);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kDuration);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kTimestamp);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kList);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kMap);
ASSERT_EQ(descriptor.types()[pos++], CelValue::Type::kError);
}
TEST(CelFunctionAdapterTest, TestAdapterStatusOrMessage) {
auto func =
[](google::protobuf::Arena* arena) -> absl::StatusOr<const google::protobuf::Message*> {
auto* ret = google::protobuf::Arena::Create<google::protobuf::Timestamp>(arena);
ret->set_seconds(123);
return ret;
};
ASSERT_OK_AND_ASSIGN(
auto cel_func,
(FunctionAdapter<absl::StatusOr<const google::protobuf::Message*>>::Create(
"const", false, func)));
absl::Span<CelValue> args;
CelValue result = CelValue::CreateNull();
google::protobuf::Arena arena;
ASSERT_OK(cel_func->Evaluate(args, &result, &arena));
ASSERT_TRUE(result.IsTimestamp());
EXPECT_EQ(result.TimestampOrDie(), absl::FromUnixSeconds(123));
}
}
}
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_function_adapter.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/cel_function_adapter_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
bfb29bf7-6eab-4ad7-a819-b0a239d934ec | cpp | tensorflow/tensorflow | auto_sharding_solver | third_party/xla/xla/hlo/experimental/auto_sharding/auto_sharding_solver.cc | third_party/xla/xla/hlo/experimental/auto_sharding/auto_sharding_solver_test.cc | #include "xla/hlo/experimental/auto_sharding/auto_sharding_solver.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "absl/container/btree_set.h"
#include "xla/hlo/experimental/auto_sharding/auto_sharding.pb.h"
#ifdef PLATFORM_GOOGLE
#include "file/base/options.h"
#endif
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "xla/hlo/experimental/auto_sharding/auto_sharding_memory.h"
#include "xla/hlo/experimental/auto_sharding/auto_sharding_strategy.h"
#include "xla/status_macros.h"
#include "xla/util.h"
#include "tsl/platform/fingerprint.h"
#include "tsl/platform/hash.h"
#include "tsl/platform/types.h"
#include "ortools/linear_solver/linear_solver.h"
#include "ortools/linear_solver/linear_solver.pb.h"
#ifdef PLATFORM_GOOGLE
#include "file/base/helpers.h"
#include "util/task/status.pb.h"
#endif
namespace xla {
namespace spmd {
using ::operations_research::MPConstraint;
using ::operations_research::MPSolver;
using ::operations_research::MPVariable;
constexpr double kMaxCostEpsilon = 1.0001;
constexpr double kMemoryMultiplier = 1e6;
constexpr double kMaxCostValue = 1e18;
bool AutoShardingSolverOutput::operator==(
const AutoShardingSolverOutput& other) const {
return s_val == other.s_val && cost == other.cost &&
is_optimal == other.is_optimal && peak_times == other.peak_times;
}
void PrintLargestInstructions(
const std::vector<NodeStrategyIdx>& chosen_strategy,
const AutoShardingSolverRequest& request) {
if (!request.node_intervals().empty()) return;
std::vector<std::pair<LivenessIdx, double>> time_memory_usage;
for (LivenessIdx time_idx = 0; time_idx < request.live_size(); ++time_idx) {
double mem = 0.0;
for (NodeIdx node_idx : request.live(time_idx).nodes()) {
mem += request.memory_costs(node_idx).costs(chosen_strategy[node_idx]);
}
time_memory_usage.push_back({time_idx, mem});
}
struct {
bool operator()(std::pair<LivenessIdx, double> a,
std::pair<LivenessIdx, double> b) const {
return a.second > b.second;
}
} MemLarger;
std::sort(time_memory_usage.begin(), time_memory_usage.end(), MemLarger);
LOG(INFO) << "using m[] and L[], max memory usage: "
<< time_memory_usage.front().second / (1024 * 1024 * 1024)
<< " GB at time " << time_memory_usage.front().first;
size_t k = 3;
k = std::min(k, time_memory_usage.size());
std::vector<std::pair<NodeIdx, double>> instruction_mem;
absl::flat_hash_set<NodeIdx> instruction_set;
for (auto usage_idx = 0; usage_idx < k; ++usage_idx) {
LivenessIdx time_idx = time_memory_usage.at(usage_idx).first;
for (NodeIdx node_idx : request.live(time_idx).nodes()) {
double mem =
request.memory_costs(node_idx).costs(chosen_strategy[node_idx]);
if (mem > 100 * 1024 * 1024 &&
instruction_set.find(node_idx) == instruction_set.end()) {
instruction_mem.push_back({node_idx, mem});
instruction_set.insert(node_idx);
}
}
}
std::sort(instruction_mem.begin(), instruction_mem.end(), MemLarger);
size_t top_tensors = 10;
top_tensors = std::min(top_tensors, instruction_mem.size());
VLOG(1) << "Top " << top_tensors << " largest tensors:";
for (size_t i = 0; i < top_tensors; ++i) {
VLOG(1) << "instruction name: "
<< request.instruction_names(instruction_mem.at(i).first)
<< " memory usage: "
<< instruction_mem.at(i).second / (1024 * 1024 * 1024) << "GB";
}
}
absl::StatusOr<AutoShardingSolverOutput> SolveAndExtractSolution(
const AutoShardingSolverRequest& request,
const std::vector<std::vector<MPVariable*>>& s,
const std::vector<std::vector<MPVariable*>>& e,
const MPVariable* overbudget_var, const MPVariable* makespan_var,
MPSolver& solver);
double MinimumMemoryBudgetRequired(const AutoShardingSolverRequest& request) {
double min_memory_budget_required_estimate = 0.0;
for (LivenessIdx time_idx = 0; time_idx < request.live_size(); ++time_idx) {
double min_memory_budget_required_estimate_local = 0.0;
for (NodeIdx node_idx : request.live(time_idx).nodes()) {
const auto& m = request.memory_costs(node_idx).costs();
const double fixed_memory_cost = *std::min_element(m.begin(), m.end());
min_memory_budget_required_estimate_local += fixed_memory_cost;
}
min_memory_budget_required_estimate =
std::max(min_memory_budget_required_estimate,
min_memory_budget_required_estimate_local);
}
return min_memory_budget_required_estimate;
}
double MaxCoeff(
const tsl::protobuf::RepeatedPtrField<AutoShardingSolverRequest_Costs>&
cost_mat) {
double max_coeff = 0.0;
for (auto& costs : cost_mat) {
for (auto& cost : costs.costs()) {
if (cost < kInfinityCost) {
max_coeff = std::max(max_coeff, cost);
}
}
}
return max_coeff;
}
void ScaleCoeffs(
double scaling_factor,
tsl::protobuf::RepeatedPtrField<AutoShardingSolverRequest_Costs>*
cost_mat) {
for (auto& costs : *cost_mat) {
for (auto& cost : *costs.mutable_costs()) {
if (cost < kInfinityCost) {
cost = floor(cost * scaling_factor);
}
}
}
}
AutoShardingSolverRequest ScaleRequest(
const AutoShardingSolverRequest& request) {
if (!request.has_coeff_limit()) return request;
VLOG(0) << "Scaling request by coefficient limit: "
<< request.coeff_limit().coeff();
double max_coeff = 0.0;
max_coeff = std::max(max_coeff, MaxCoeff(request.communication_costs()));
max_coeff = std::max(max_coeff, MaxCoeff(request.computation_costs()));
max_coeff = std::max(max_coeff, MaxCoeff(request.resharding_costs()));
if (max_coeff <= request.coeff_limit().coeff()) return request;
const double scaling_factor = request.coeff_limit().coeff() / max_coeff;
AutoShardingSolverRequest scaled_request = request;
ScaleCoeffs(scaling_factor, scaled_request.mutable_communication_costs());
ScaleCoeffs(scaling_factor, scaled_request.mutable_computation_costs());
ScaleCoeffs(scaling_factor, scaled_request.mutable_resharding_costs());
return scaled_request;
}
std::optional<std::pair<int64_t, int64_t>> ReduceMemoryTerms(
const AutoShardingSolverRequest& request, MPSolver& solver,
int64_t num_lives, int64_t num_primitives,
const std::function<
tsl::protobuf::RepeatedField<int64_t>(int64_t)>&
live,
const tsl::protobuf::RepeatedPtrField<
AutoShardingSolverRequest_Pair>& intervals,
const tsl::protobuf::RepeatedPtrField<
AutoShardingSolverRequest_Group>& groups,
const tsl::protobuf::RepeatedPtrField<
AutoShardingSolverRequest_Costs>& memory_costs,
std::string_view prim_type,
std::vector<std::vector<MPVariable*>>& prim_vars,
std::vector<std::pair<int64_t, int64_t>>& reduced_intervals,
std::vector<MPVariable*>& group_vars,
absl::flat_hash_set<int64_t>& reduced_times) {
const absl::Time term_reduction_start_time = absl::Now();
std::optional<std::pair<int64_t, int64_t>> num_terms = std::nullopt;
std::vector<absl::btree_set<int64_t>> reduced_groups;
if (groups.empty()) {
for (const auto& interval : intervals) {
if (interval.first() > interval.second()) continue;
num_lives = std::max(num_lives, interval.second() + 1);
}
auto Intervals =
[intervals](int64_t prim_idx) -> std::pair<int64_t, int64_t> {
return {intervals.at(prim_idx).first(), intervals.at(prim_idx).second()};
};
MemoryTermReducer reducer;
num_terms =
intervals.empty()
? reducer.Reduce(num_lives, num_primitives, live)
: reducer.Reduce(num_lives, num_primitives, std::move(Intervals));
reduced_intervals = reducer.GetReducedIntervals();
reduced_groups = reducer.GetReducedGroups();
} else {
for (const auto& interval : intervals) {
reduced_intervals.push_back({interval.first(), interval.second()});
}
for (const auto& group : groups) {
reduced_groups.push_back({group.prims().begin(), group.prims().end()});
}
}
solver.MakeNumVarArray(reduced_groups.size(), 0.0, MPSolver::infinity(),
absl::StrCat("group_", prim_type), &group_vars);
for (int64_t group_idx = 0; group_idx < group_vars.size(); ++group_idx) {
MPConstraint* constraint = solver.MakeRowConstraint(
-MPSolver::infinity(), 0.0,
absl::StrCat("group_", prim_type, "[", group_idx, "]"));
constraint->SetCoefficient(group_vars[group_idx], -1.0);
for (const int64_t prim_idx : reduced_groups[group_idx]) {
for (int64_t j = 0; j < prim_vars[prim_idx].size(); ++j) {
double memory_cost = memory_costs.at(prim_idx).costs(j);
memory_cost /= request.memory_budget() / kMemoryMultiplier;
const double accumulated_coefficient =
constraint->GetCoefficient(prim_vars[prim_idx][j]);
constraint->SetCoefficient(prim_vars[prim_idx][j],
accumulated_coefficient + memory_cost);
}
}
}
const absl::flat_hash_set<int64_t> times = MemoryTermReducer::GetReducedTimes(
num_primitives, reduced_intervals, reduced_groups);
reduced_times.insert(times.begin(), times.end());
const absl::Time term_reduction_end_time = absl::Now();
if (num_terms) {
const auto term_reduction_duration =
term_reduction_end_time - term_reduction_start_time;
LOG(INFO) << "Memory Term Reducer for " << prim_type << "s took "
<< absl::ToInt64Milliseconds(term_reduction_duration)
<< " ms and reduced the number of terms from " << num_terms->first
<< " to " << num_terms->second;
}
return num_terms;
}
void AddMemoryTerms(
const AutoShardingSolverRequest& request, MPSolver& solver,
int64_t num_primitives,
const std::vector<std::pair<int64_t, int64_t>>& intervals,
const tsl::protobuf::RepeatedPtrField<
AutoShardingSolverRequest_Costs>& memory_costs,
const MPVariable* overbudget_var,
const absl::flat_hash_set<int64_t>& reduced_times,
std::vector<std::vector<MPVariable*>>& prim_vars,
std::vector<MPVariable*>& group_vars,
absl::flat_hash_map<LivenessIdx, MPConstraint*>& constraints) {
for (int64_t prim_idx = 0; prim_idx < intervals.size(); ++prim_idx) {
for (int64_t time_idx = intervals[prim_idx].first;
time_idx <= intervals[prim_idx].second; ++time_idx) {
if (!reduced_times.contains(time_idx)) continue;
if (!constraints.contains(time_idx)) {
MPConstraint* constraint =
solver.MakeRowConstraint(-MPSolver::infinity(), kMemoryMultiplier,
absl::StrCat("mem[", time_idx, "]"));
if (overbudget_var) {
constraint->SetCoefficient(overbudget_var, -kMemoryMultiplier);
}
constraints[time_idx] = constraint;
}
MPConstraint* constraint = constraints[time_idx];
if (prim_idx >= num_primitives) {
constraint->SetCoefficient(group_vars[prim_idx - num_primitives], 1.0);
continue;
}
for (int64_t j = 0; j < prim_vars[prim_idx].size(); ++j) {
double memory_cost = memory_costs.at(prim_idx).costs(j);
memory_cost /= request.memory_budget() / kMemoryMultiplier;
const double accumulated_coefficient =
constraint->GetCoefficient(prim_vars[prim_idx][j]);
constraint->SetCoefficient(prim_vars[prim_idx][j],
accumulated_coefficient + memory_cost);
}
}
}
}
absl::StatusOr<AutoShardingSolverOutput> FormulateAndSolveMIPFromSolverRequest(
const AutoShardingSolverRequest& unscaled_request) {
const absl::Time start_time = absl::Now();
const AutoShardingSolverRequest& request = ScaleRequest(unscaled_request);
const size_t num_edges = request.edges_size();
const int num_workers = 32;
#ifdef PLATFORM_GOOGLE
std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("SAT"));
#else
std::unique_ptr<MPSolver> solver(
std::make_unique<MPSolver>("", MPSolver::SAT_INTEGER_PROGRAMMING));
#endif
CHECK(solver);
solver->MutableObjective()->SetMinimization();
std::string solver_parameter_str;
if (solver->ProblemType() ==
operations_research::MPSolver::SAT_INTEGER_PROGRAMMING) {
solver_parameter_str = absl::StrCat("num_workers:", num_workers);
if (request.deterministic_mode()) {
absl::StrAppend(
&solver_parameter_str,
",share_binary_clauses:false,random_seed:1,interleave_search:true");
}
if (request.has_solver_timeout()) {
absl::StrAppend(&solver_parameter_str, ",max_deterministic_time:",
request.solver_timeout().solver_timeout_in_seconds());
}
solver->SetSolverSpecificParametersAsString(solver_parameter_str);
}
std::vector<std::vector<MPVariable*>> s(request.num_nodes());
std::vector<std::vector<MPVariable*>> e(num_edges);
MPVariable* overbudget_var = nullptr;
MPVariable* makespan_var = nullptr;
size_t unique_nodes = 0;
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
if (request.s_follow(node_idx) < 0) {
unique_nodes += 1;
solver->MakeBoolVarArray(request.s_len(node_idx),
absl::StrCat("s[", node_idx, "]"), &s[node_idx]);
}
}
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
if (request.s_follow(node_idx) >= 0) {
CHECK_EQ(request.s_len(node_idx),
request.s_len(request.s_follow(node_idx)));
s[node_idx] = s[request.s_follow(node_idx)];
}
}
size_t unique_edges = 0;
std::vector<EdgeIdx> e_follow(num_edges, -1);
absl::flat_hash_map<std::pair<NodeIdx, NodeIdx>, EdgeIdx> edge_map;
for (EdgeIdx edge_idx = 0; edge_idx < num_edges; ++edge_idx) {
const auto& raw_edge = request.edges(edge_idx);
const std::pair<NodeIdx, NodeIdx> edge(raw_edge.first(), raw_edge.second());
auto followed_edge = edge;
if (int f = request.s_follow(edge.first); f >= 0) followed_edge.first = f;
if (int f = request.s_follow(edge.second); f >= 0) followed_edge.second = f;
if (const auto& it = edge_map.find(followed_edge); it != edge_map.end()) {
e[edge_idx] = e[it->second];
e_follow[edge_idx] = it->second;
continue;
}
unique_edges += 1;
solver->MakeBoolVarArray(
request.s_len(edge.first) * request.s_len(edge.second),
absl::StrCat("e[", edge.first, ",", edge.second, "]"), &e[edge_idx]);
edge_map.insert({followed_edge, edge_idx});
}
if (request.memory_budget() > 0 && request.has_overbudget_coeff()) {
overbudget_var =
solver->MakeNumVar(0.0, MPSolver::infinity(), "overbudget");
}
if (request.has_makespan_coeff()) {
makespan_var = CreateMakespanVar(request, e, *solver);
}
absl::flat_hash_set<MPVariable*> infinity_vars;
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
for (NodeStrategyIdx j = 0; j < s[node_idx].size(); ++j) {
double coefficient = request.computation_costs(node_idx).costs(j) +
request.communication_costs(node_idx).costs(j);
if (coefficient >= kInfinityCost) {
infinity_vars.insert(s[node_idx][j]);
continue;
}
if (request.minimize_departures()) continue;
double accumulated_coefficient =
solver->MutableObjective()->GetCoefficient(s[node_idx][j]);
solver->MutableObjective()->SetCoefficient(
s[node_idx][j], accumulated_coefficient + coefficient);
}
}
for (EdgeIdx edge_idx = 0; edge_idx < num_edges; ++edge_idx) {
for (EdgeStrategyIdx j = 0; j < e[edge_idx].size(); ++j) {
double coefficient = request.resharding_costs(edge_idx).costs(j);
if (coefficient >= kInfinityCost) {
infinity_vars.insert(e[edge_idx][j]);
continue;
}
if (request.minimize_departures()) continue;
double accumulated_coefficient =
solver->MutableObjective()->GetCoefficient(e[edge_idx][j]);
solver->MutableObjective()->SetCoefficient(
e[edge_idx][j], accumulated_coefficient + coefficient);
}
}
LOG(INFO) << "Number of infinity terms: " << infinity_vars.size();
const NodeStrategies shaved_strategies =
StrategyShaver(request).FindShavedStrategies();
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
if (s[node_idx].empty() || request.s_follow(node_idx) >= 0) continue;
bool all_infinity = true;
for (NodeStrategyIdx j = 0; j < s[node_idx].size(); ++j) {
if (infinity_vars.contains(s[node_idx][j]) ||
shaved_strategies.contains({node_idx, j})) {
MPConstraint* constraint = solver->MakeRowConstraint(
0.0, 0.0,
absl::StrCat("infinitycost: s[", node_idx, "][", j, "] = 0"));
constraint->SetCoefficient(s[node_idx][j], 1.0);
} else {
all_infinity = false;
}
}
if (all_infinity) {
LOG(FATAL) << "All of s[" << node_idx << "][*] have infinity costs";
}
}
for (EdgeIdx edge_idx = 0; edge_idx < num_edges; ++edge_idx) {
if (e[edge_idx].empty() || e_follow[edge_idx] >= 0) continue;
bool all_infinity = true;
for (EdgeStrategyIdx j = 0; j < e[edge_idx].size(); ++j) {
if (infinity_vars.contains(e[edge_idx][j])) {
MPConstraint* constraint = solver->MakeRowConstraint(
0.0, 0.0,
absl::StrCat("infinitycost: e[", edge_idx, "][", j, "] = 0"));
constraint->SetCoefficient(e[edge_idx][j], 1.0);
} else {
all_infinity = false;
}
}
if (all_infinity) {
auto err_msg = absl::StrCat("All of e[", request.edges(edge_idx).first(),
"][", request.edges(edge_idx).second(),
"][*] have infinity costs");
if (request.crash_at_infinity_costs_check()) {
LOG(FATAL) << err_msg;
} else {
LOG(WARNING) << err_msg;
return absl::InternalError(err_msg);
}
}
}
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
if (request.s_follow(node_idx) >= 0) continue;
MPConstraint* constraint = solver->MakeRowConstraint(
1.0, 1.0,
absl::StrCat("sum(s[", node_idx, "][j] for j = [0 .. ",
s[node_idx].size(), ")) = 1"));
for (NodeStrategyIdx j = 0; j < s[node_idx].size(); ++j) {
constraint->SetCoefficient(s[node_idx][j], 1.0);
}
}
if (request.memory_budget() > 0) {
auto LiveNodes =
[request](int64_t live_idx) -> tsl::protobuf::RepeatedField<int64_t> {
return request.live(live_idx).nodes();
};
auto LiveEdges =
[request](int64_t live_idx) -> tsl::protobuf::RepeatedField<int64_t> {
return request.live_edges(live_idx).edges();
};
std::vector<std::pair<int64_t, int64_t>> reduced_intervals_nodes,
reduced_intervals_edges;
absl::flat_hash_set<int64_t> reduced_times;
std::vector<MPVariable*> group_node_vars, group_edge_vars;
std::optional<std::pair<int64_t, int64_t>> num_node_terms, num_edge_terms;
num_node_terms = ReduceMemoryTerms(
request, *solver, request.live_size(), request.num_nodes(),
std::move(LiveNodes), request.node_intervals(), request.node_groups(),
request.memory_costs(), "node", s, reduced_intervals_nodes,
group_node_vars, reduced_times);
if (request.enable_memory_edge_costs()) {
num_edge_terms = ReduceMemoryTerms(
request, *solver, request.live_edges_size(), request.edges_size(),
std::move(LiveEdges), request.edge_intervals(), request.edge_groups(),
request.memory_edge_costs(), "edge", e, reduced_intervals_edges,
group_edge_vars, reduced_times);
}
absl::flat_hash_map<LivenessIdx, MPConstraint*> constraints;
AddMemoryTerms(request, *solver, request.num_nodes(),
reduced_intervals_nodes, request.memory_costs(),
overbudget_var, reduced_times, s, group_node_vars,
constraints);
if (request.enable_memory_edge_costs()) {
AddMemoryTerms(request, *solver, request.edges_size(),
reduced_intervals_edges, request.memory_edge_costs(),
overbudget_var, reduced_times, e, group_edge_vars,
constraints);
}
if (overbudget_var && !request.minimize_departures()) {
solver->MutableObjective()->SetCoefficient(
overbudget_var,
request.overbudget_coeff().coeff() * request.memory_budget());
}
LOG(INFO) << "Minimum memory budget estimate: "
<< MinimumMemoryBudgetRequired(request);
LOG(INFO) << "Using memory budget: "
<< static_cast<double>(request.memory_budget());
}
for (EdgeIdx edge_idx = 0; edge_idx < num_edges; ++edge_idx) {
if (e_follow[edge_idx] >= 0) continue;
const auto& edge = request.edges(edge_idx);
for (NodeStrategyIdx p = 0; p < s[edge.first()].size(); ++p) {
for (NodeStrategyIdx q = 0; q < s[edge.second()].size(); ++q) {
const EdgeStrategyIdx j = p * s[edge.second()].size() + q;
MPConstraint* constraint = solver->MakeRowConstraint(
-1.0, MPSolver::infinity(),
absl::StrCat("edge[", edge_idx, "][", j, "]"));
double coeff = (s[edge.first()][p] == s[edge.second()][q]) ? 2.0 : 1.0;
constraint->SetCoefficient(s[edge.first()][p], -coeff);
constraint->SetCoefficient(s[edge.second()][q], -coeff);
constraint->SetCoefficient(e[edge_idx][j], 1.0);
}
}
}
absl::flat_hash_set<std::pair<NodeIdx, NodeIdx>> alias_set;
for (auto alias_idx = 0; alias_idx < request.aliases_size(); ++alias_idx) {
const auto& raw_alias = request.aliases(alias_idx);
const std::pair<NodeIdx, NodeIdx> alias(raw_alias.first(),
raw_alias.second());
if (alias_set.contains(alias)) continue;
alias_set.insert(alias);
const auto& value_costs = request.value_costs(alias_idx).costs();
for (NodeStrategyIdx p = 0; p < s[alias.first].size(); ++p) {
for (NodeStrategyIdx q = 0; q < s[alias.second].size(); ++q) {
if (value_costs[p * s[alias.second].size() + q] > 0.5) {
MPConstraint* constraint = solver->MakeRowConstraint(
-MPSolver::infinity(), 1,
absl::StrCat("s[", alias.first, "][", p, "] + s[", alias.second,
"][", q, "] <= 1"));
constraint->SetCoefficient(s[alias.first][p], 1.0);
constraint->SetCoefficient(s[alias.second][q], 1.0);
}
}
}
}
if (request.has_max_departures()) {
MPConstraint* constraint = solver->MakeRowConstraint(
0, request.max_departures().coeff(),
absl::StrCat("departures <= ", request.max_departures().coeff()));
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
for (NodeStrategyIdx j = 0; j < s[node_idx].size(); ++j) {
double accumulated_coefficient =
constraint->GetCoefficient(s[node_idx][j]);
double departure_cost = request.departure_costs(node_idx).costs(j);
constraint->SetCoefficient(s[node_idx][j],
accumulated_coefficient + departure_cost);
}
}
}
if (request.minimize_departures()) {
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
for (NodeStrategyIdx j = 0; j < s[node_idx].size(); ++j) {
double accumulated_coefficient =
solver->MutableObjective()->GetCoefficient(s[node_idx][j]);
double departure_cost = request.departure_costs(node_idx).costs(j);
solver->MutableObjective()->SetCoefficient(
s[node_idx][j], accumulated_coefficient + departure_cost);
}
}
}
if (request.has_max_cost() && request.max_cost().coeff() < kMaxCostValue) {
double max_cost = kMaxCostEpsilon * request.max_cost().coeff();
max_cost -= solver->Objective().offset();
MPConstraint* cost_constraint = solver->MakeRowConstraint(
-MPSolver::infinity(), max_cost, "cost_constraint");
for (const auto [var, coeff] : solver->Objective().terms()) {
cost_constraint->SetCoefficient(var, coeff);
}
}
if (!request.s_hint().empty() && !request.deterministic_mode() &&
(!request.has_max_cost() || request.max_cost().coeff() < kMaxCostValue)) {
std::vector<std::pair<const MPVariable*, double>> hint;
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
if (request.s_follow(node_idx) >= 0) continue;
for (NodeStrategyIdx j = 0; j < s[node_idx].size(); ++j) {
double hint_val = (request.s_hint(node_idx) == j) ? 1.0 : 0.0;
hint.push_back({s[node_idx][j], hint_val});
}
}
solver->SetHint(hint);
}
#ifdef PLATFORM_GOOGLE
bool dump_model = false;
if (dump_model) {
operations_research::MPModelProto model_proto;
solver->ExportModelToProto(&model_proto);
auto write_status = file::SetTextProto(
absl::StrCat("/tmp/model_", solver->NumVariables(), ".proto"),
model_proto, file::Defaults());
if (!write_status.ok()) {
LOG(ERROR) << write_status.message();
}
}
bool dump_solver_request = false;
if (dump_solver_request) {
uint64_t solver_request_fprint =
tsl::Fingerprint64(unscaled_request.SerializeAsString());
std::string request_dump_path =
absl::StrCat("/tmp/solver_request_", unscaled_request.request_name(),
"_", solver_request_fprint, ".proto");
auto write_status = file::SetBinaryProto(
request_dump_path, unscaled_request, file::Defaults());
VLOG(5) << "Dumped solver request to " << request_dump_path;
if (!write_status.ok()) {
LOG(ERROR) << write_status.message();
}
}
#endif
if (request.enable_output()) {
solver->EnableOutput();
}
VLOG(0) << "Starting solver " << solver->ProblemType() << "\n"
<< "Solver parameter string: " << solver_parameter_str << "\n"
<< "Number of workers: " << num_workers << "\n"
<< "Number of threads: " << solver->GetNumThreads() << "\n"
<< "Time limit: " << solver->time_limit() << "\n"
<< "Request valid: " << ValidateRequest(request).ok() << "\n"
<< "Aliases: " << request.aliases_size() << "\n"
<< "Unique nodes: " << unique_nodes << "\n"
<< "Unique edges: " << unique_edges << "\n"
<< "Total instructions: " << request.num_nodes() << "\n"
<< "Total edges: " << request.edges_size() << "\n"
<< "Memory budget: " << request.memory_budget() / (1024 * 1024 * 1024)
<< "GB\n"
<< "Number variables for ILP: " << solver->NumVariables() << "\n"
<< "Number of ILP constraints: " << solver->NumConstraints() << "\n"
<< "Deterministic mode: " << request.deterministic_mode() << "\n"
<< "Module name: " << request.module_name();
if (request.has_max_cost()) {
VLOG(0) << "Max cost: " << request.max_cost().coeff();
}
auto result = SolveAndExtractSolution(request, s, e, overbudget_var,
makespan_var, *solver);
if (result.ok()) {
const AutoShardingEvaluation evaluation =
Evaluate(unscaled_request, *result);
LOG(INFO) << "*** Total costs for the (unscaled) solver request ***";
LOG(INFO) << "Total Communication Cost: "
<< evaluation.total.communication_cost
<< " (lower bound: " << evaluation.lower_bound.communication_cost
<< ")";
LOG(INFO) << "Total Computation Cost: " << evaluation.total.computation_cost
<< " (lower bound: " << evaluation.lower_bound.computation_cost
<< ")";
LOG(INFO) << "Total Resharding Cost: " << evaluation.total.resharding_cost
<< " (lower bound: " << evaluation.lower_bound.resharding_cost
<< ")";
LOG(INFO) << "Total Overbudget Cost: " << evaluation.total.overbudget_cost
<< " (lower bound: " << evaluation.lower_bound.overbudget_cost
<< ")";
LOG(INFO) << "Total Makespan Cost: " << evaluation.total.makespan_cost
<< " (lower bound: " << evaluation.lower_bound.makespan_cost
<< ")";
LOG(INFO) << "Total Cost: " << evaluation.total.cost()
<< " (lower bound: " << evaluation.lower_bound.cost() << ")";
LOG(INFO) << "Total Departures: " << evaluation.total_departures;
LOG(INFO) << "Total Makespan: " << evaluation.total_makespan;
LOG(INFO) << "Total Violations: " << evaluation.violation_codes.size();
}
const absl::Time end_time = absl::Now();
const auto duration = end_time - start_time;
LOG(INFO) << "Solver took " << absl::ToInt64Milliseconds(duration) << " ms";
return result;
}
std::vector<NodeStrategyIdx> GetChosenNodeStrategy(
const AutoShardingSolverRequest& request,
const std::vector<std::vector<MPVariable*>>& s) {
std::vector<NodeStrategyIdx> chosen_node_strategy(request.num_nodes(), -1);
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
for (NodeStrategyIdx j = 0; j < s[node_idx].size(); ++j) {
if (s[node_idx][j]->solution_value() > 0.5) {
chosen_node_strategy[node_idx] = j;
break;
}
}
}
return chosen_node_strategy;
}
absl::StatusOr<AutoShardingSolverOutput> SolveAndExtractSolution(
const AutoShardingSolverRequest& request,
const std::vector<std::vector<MPVariable*>>& s,
const std::vector<std::vector<MPVariable*>>& e,
const MPVariable* overbudget_var, const MPVariable* makespan_var,
MPSolver& solver) {
auto status = solver.Solve();
LOG(INFO) << "Solver absl::Status: " << status;
bool is_optimal = false;
if (status == operations_research::MPSolver::INFEASIBLE) {
LOG(ERROR) << "MPSolver could not find any feasible solution.";
#ifdef PLATFORM_GOOGLE
if (request.compute_iis()) {
operations_research::MPModelRequest model_request;
solver.ExportModelToProto(model_request.mutable_model());
if (solver.ProblemType() ==
operations_research::MPSolver::SAT_INTEGER_PROGRAMMING) {
model_request.set_solver_type(
operations_research::MPModelRequest::SAT_INTEGER_PROGRAMMING);
} else if (solver.ProblemType() == operations_research::MPSolver::
SCIP_MIXED_INTEGER_PROGRAMMING) {
model_request.set_solver_type(operations_research::MPModelRequest::
SCIP_MIXED_INTEGER_PROGRAMMING);
}
model_request.set_solver_time_limit_seconds(100);
auto iis = MPSolver::ComputeIrreducibleInfeasibleSubset(model_request);
LOG(INFO) << iis.status().DebugString();
LOG(INFO) << "Infeasible constraints: ";
for (int index : iis.constraint_index()) {
LOG(INFO) << " - " << model_request.model().constraint(index).name();
}
for (int index : iis.general_constraint_index()) {
LOG(INFO)
<< " - "
<< model_request.model().general_constraint(index).DebugString();
}
}
#endif
return absl::InternalError(
"MPSolver could not find any feasible solution.");
} else if (status == operations_research::MPSolver::MODEL_INVALID) {
LOG(FATAL) << "The MIP fed to the solver is invalid. This is most likely a "
"bug and should be reported.";
return absl::InternalError("Invalid MIP.");
} else if (status == operations_research::MPSolver::NOT_SOLVED) {
LOG(WARNING) << "Solver timeout; no solution was produced";
return absl::InternalError("Solver timed out.");
} else if (status != operations_research::MPSolver::OPTIMAL) {
LOG(WARNING) << "Solver timeout; moving forward with a suboptimal solution";
} else {
is_optimal = true;
}
operations_research::MPModelProto model_proto;
solver.ExportModelToProto(&model_proto);
uint64_t model_fprint = tsl::Fingerprint64(model_proto.SerializeAsString());
operations_research::MPSolutionResponse response;
solver.FillSolutionResponseProto(&response);
response.clear_solve_info();
uint64_t solution_fprint = tsl::Fingerprint64(response.SerializeAsString());
LOG(INFO) << "Objective value: " << solver.Objective().Value()
<< " Model fingerprint: " << model_fprint
<< " Solution fingerprint: " << solution_fprint;
if (solver.Objective().Value() >= kInfinityCost) {
LOG(WARNING) << "Objective (" << solver.Objective().Value()
<< ") is larger than kInfinityCost. It means the solver "
"chooses a solution with kInfinityCost and there may be "
"numerical issues when the solver considering other costs.";
}
if (VLOG_IS_ON(10)) {
VLOG(10) << "MODEL:";
XLA_VLOG_LINES(10, model_proto.DebugString());
VLOG(10) << "RESPONSE:";
XLA_VLOG_LINES(10, response.DebugString());
}
size_t num_edges = request.edges_size();
double unsalted_objective = 0.0;
const std::vector<NodeStrategyIdx> chosen_node_strategy =
GetChosenNodeStrategy(request, s);
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
const NodeStrategyIdx j = chosen_node_strategy[node_idx];
unsalted_objective += request.computation_costs(node_idx).costs(j) +
request.communication_costs(node_idx).costs(j);
}
const auto chosen_edge_strategy = [&](EdgeIdx edge_idx) {
const auto& edge = request.edges(edge_idx);
return chosen_node_strategy[edge.first()] * request.s_len(edge.second()) +
chosen_node_strategy[edge.second()];
};
for (EdgeIdx edge_idx = 0; edge_idx < num_edges; ++edge_idx) {
const EdgeStrategyIdx j = chosen_edge_strategy(edge_idx);
unsalted_objective += request.resharding_costs(edge_idx).costs(j);
}
if (overbudget_var) {
unsalted_objective += request.overbudget_coeff().coeff() *
overbudget_var->solution_value() *
request.memory_budget();
}
if (makespan_var) {
unsalted_objective +=
request.makespan_coeff().coeff() * makespan_var->solution_value();
}
LOG(INFO) << "Unsalted objective value: " << unsalted_objective;
LOG(INFO) << "N = " << request.num_nodes();
if (request.memory_budget() < 0) {
LOG(INFO) << "memory budget: -1";
} else {
LOG(INFO) << "memory budget: "
<< request.memory_budget() / (1024 * 1024 * 1024) << " GB";
}
PrintLargestInstructions(chosen_node_strategy, request);
return AutoShardingSolverOutput{.s_val = std::move(chosen_node_strategy),
.cost = solver.Objective().Value(),
.is_optimal = is_optimal};
}
bool CostComponents::operator==(const CostComponents& other) const {
return communication_cost == other.communication_cost &&
computation_cost == other.computation_cost &&
resharding_cost == other.resharding_cost &&
overbudget_cost == other.overbudget_cost &&
makespan_cost == other.makespan_cost;
}
double CostComponents::cost() const {
return communication_cost + computation_cost + resharding_cost +
overbudget_cost + makespan_cost;
}
bool AutoShardingEvaluation::operator==(
const AutoShardingEvaluation& other) const {
return violation_codes == other.violation_codes && total == other.total &&
lower_bound == other.lower_bound &&
total_departures == other.total_departures;
}
AutoShardingEvaluation Evaluate(const AutoShardingSolverRequest& request,
const AutoShardingSolverOutput& result) {
const auto& c = request.computation_costs();
const auto& d = request.communication_costs();
const auto& r = request.resharding_costs();
const auto& v = request.value_costs();
const auto& p = request.departure_costs();
const std::vector<NodeStrategyIdx>& s_val = result.s_val;
const auto e_val = [&](EdgeIdx edge_idx) {
const auto& edge = request.edges(edge_idx);
return s_val[edge.first()] * request.s_len(edge.second()) +
s_val[edge.second()];
};
AutoShardingEvaluation evaluation;
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
NodeIdx s_follow = request.s_follow(node_idx);
if (s_follow >= 0 && s_val[node_idx] != s_val[s_follow]) {
evaluation.violation_codes.insert(kFollowerViolationCode);
}
}
for (auto alias_idx = 0; alias_idx < request.aliases_size(); ++alias_idx) {
const auto& alias = request.aliases(alias_idx);
NodeStrategyIdx p = s_val[alias.first()], q = s_val[alias.second()];
if (v.at(alias_idx).costs(p * request.s_len(alias.second()) + q) > 0.5) {
evaluation.violation_codes.insert(kAliasViolationCode);
}
}
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
NodeStrategyIdx strat_idx = s_val[node_idx];
const double node_cost =
c.at(node_idx).costs(strat_idx) + d.at(node_idx).costs(strat_idx);
if (node_cost >= kInfinityCost) {
evaluation.violation_codes.insert(kInfiniteCostViolationCode);
}
}
for (EdgeIdx edge_idx = 0; edge_idx < request.edges_size(); ++edge_idx) {
if (r.at(edge_idx).costs(e_val(edge_idx)) >= kInfinityCost) {
evaluation.violation_codes.insert(kInfiniteCostViolationCode);
}
}
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
evaluation.total_departures += p.at(node_idx).costs(s_val[node_idx]);
if (request.has_max_departures() &&
evaluation.total_departures > request.max_departures().coeff()) {
evaluation.violation_codes.insert(kMaxDeparturesViolationCode);
}
}
if (request.memory_budget() > 0) {
double total_overbudget = 0.0;
double lower_bound_overbudget = 0.0;
std::vector<double> total_memory_costs, lower_bound_memory_costs;
if (request.node_intervals().empty()) {
total_memory_costs.resize(request.live_size(), 0.0);
lower_bound_memory_costs.resize(request.live_size(), 0.0);
for (LivenessIdx time_idx = 0; time_idx < request.live_size();
++time_idx) {
for (NodeIdx node_idx : request.live(time_idx).nodes()) {
const auto& m = request.memory_costs(node_idx).costs();
total_memory_costs[time_idx] += m[s_val[node_idx]];
lower_bound_memory_costs[time_idx] +=
*std::min_element(m.begin(), m.end());
}
if (!request.live_edges().empty() &&
request.enable_memory_edge_costs()) {
for (EdgeIdx edge_idx : request.live_edges(time_idx).edges()) {
const auto& m = request.memory_edge_costs(edge_idx).costs();
total_memory_costs[time_idx] += m[e_val(edge_idx)];
lower_bound_memory_costs[time_idx] +=
*std::min_element(m.begin(), m.end());
}
}
}
} else {
std::vector<double> total_node_group_costs, total_edge_group_costs,
lower_bound_node_group_costs, lower_bound_edge_group_costs;
for (const auto& group : request.node_groups()) {
double total_group_cost = 0.0;
double lower_bound_group_cost = 0.0;
for (const NodeIdx node_idx : group.prims()) {
const auto& m = request.memory_costs(node_idx).costs();
total_group_cost += m[s_val[node_idx]];
lower_bound_group_cost += *std::min_element(m.begin(), m.end());
}
total_node_group_costs.push_back(total_group_cost);
lower_bound_node_group_costs.push_back(lower_bound_group_cost);
}
for (const auto& group : request.edge_groups()) {
double total_group_cost = 0.0;
double lower_bound_group_cost = 0.0;
for (const EdgeIdx edge_idx : group.prims()) {
const auto& m = request.memory_edge_costs(edge_idx).costs();
total_group_cost += m[e_val(edge_idx)];
lower_bound_group_cost += *std::min_element(m.begin(), m.end());
}
total_edge_group_costs.push_back(total_group_cost);
lower_bound_edge_group_costs.push_back(lower_bound_group_cost);
}
for (NodeIdx node_idx = 0; node_idx < request.node_intervals_size();
++node_idx) {
const auto& interval = request.node_intervals(node_idx);
if (interval.first() > interval.second()) continue;
while (total_memory_costs.size() <= interval.second()) {
total_memory_costs.push_back(0.0);
lower_bound_memory_costs.push_back(0.0);
}
double total_memory_cost = 0.0, lower_bound_memory_cost = 0.0;
if (node_idx < request.num_nodes()) {
const auto& m = request.memory_costs(node_idx).costs();
total_memory_cost = m[s_val[node_idx]];
lower_bound_memory_cost = *std::min_element(m.begin(), m.end());
} else {
int64_t group_idx = node_idx - request.num_nodes();
total_memory_cost = total_node_group_costs[group_idx];
lower_bound_memory_cost = lower_bound_node_group_costs[group_idx];
}
for (LivenessIdx time_idx = interval.first();
time_idx <= interval.second(); ++time_idx) {
total_memory_costs[time_idx] += total_memory_cost;
lower_bound_memory_costs[time_idx] += lower_bound_memory_cost;
}
}
if (request.enable_memory_edge_costs()) {
for (EdgeIdx edge_idx = 0; edge_idx < request.edge_intervals_size();
++edge_idx) {
const auto& interval = request.edge_intervals(edge_idx);
if (interval.first() > interval.second()) continue;
while (total_memory_costs.size() <= interval.second()) {
total_memory_costs.push_back(0.0);
lower_bound_memory_costs.push_back(0.0);
}
double total_memory_cost = 0.0, lower_bound_memory_cost = 0.0;
if (edge_idx < request.edges_size()) {
const auto& m = request.memory_edge_costs(edge_idx).costs();
total_memory_cost = m[e_val(edge_idx)];
lower_bound_memory_cost = *std::min_element(m.begin(), m.end());
} else {
int64_t group_idx = edge_idx - request.edges_size();
total_memory_cost = total_edge_group_costs[group_idx];
lower_bound_memory_cost = lower_bound_edge_group_costs[group_idx];
}
for (LivenessIdx time_idx = interval.first();
time_idx <= interval.second(); ++time_idx) {
total_memory_costs[time_idx] += total_memory_cost;
lower_bound_memory_costs[time_idx] += lower_bound_memory_cost;
}
}
}
}
for (LivenessIdx time_idx = 0; time_idx < total_memory_costs.size();
++time_idx) {
if (request.has_overbudget_coeff()) {
total_overbudget =
std::max(total_overbudget,
total_memory_costs[time_idx] - request.memory_budget());
lower_bound_overbudget = std::max(
lower_bound_overbudget,
lower_bound_memory_costs[time_idx] - request.memory_budget());
} else if (total_memory_costs[time_idx] > request.memory_budget()) {
evaluation.violation_codes.insert(kMemoryViolationCode);
}
}
if (request.has_overbudget_coeff()) {
evaluation.total.overbudget_cost =
request.overbudget_coeff().coeff() * total_overbudget;
evaluation.lower_bound.overbudget_cost =
request.overbudget_coeff().coeff() * lower_bound_overbudget;
}
}
for (NodeIdx node_idx = 0; node_idx < request.num_nodes(); ++node_idx) {
evaluation.total.communication_cost +=
d.at(node_idx).costs(s_val[node_idx]);
evaluation.total.computation_cost += c.at(node_idx).costs(s_val[node_idx]);
evaluation.lower_bound.communication_cost += *std::min_element(
d.at(node_idx).costs().begin(), d.at(node_idx).costs().end());
evaluation.lower_bound.computation_cost += *std::min_element(
c.at(node_idx).costs().begin(), c.at(node_idx).costs().end());
}
for (EdgeIdx edge_idx = 0; edge_idx < request.edges_size(); ++edge_idx) {
evaluation.total.resharding_cost += r.at(edge_idx).costs(e_val(edge_idx));
evaluation.lower_bound.resharding_cost += *std::min_element(
r.at(edge_idx).costs().begin(), r.at(edge_idx).costs().end());
}
evaluation.total_makespan = EvaluateMakespan(request, result, evaluation);
return evaluation;
}
absl::Status ValidateRequest(const AutoShardingSolverRequest& request) {
const int num_nodes = request.num_nodes();
const int num_edges = request.edges_size();
TF_RET_CHECK(num_nodes == request.computation_costs_size());
TF_RET_CHECK(num_nodes == request.communication_costs_size());
TF_RET_CHECK(num_nodes == request.memory_costs_size());
TF_RET_CHECK(num_edges == request.resharding_costs_size());
for (NodeIdx u = 0; u < num_nodes; ++u) {
const int num_strategies = request.computation_costs(u).costs_size();
TF_RET_CHECK(num_strategies >= 1);
TF_RET_CHECK(num_strategies == request.communication_costs(u).costs_size());
TF_RET_CHECK(num_strategies == request.memory_costs(u).costs_size());
for (NodeStrategyIdx strategy = 0; strategy < num_strategies; ++strategy) {
TF_RET_CHECK(request.computation_costs(u).costs(strategy) >= 0.0);
TF_RET_CHECK(request.communication_costs(u).costs(strategy) >= 0.0);
TF_RET_CHECK(request.memory_costs(u).costs(strategy) >= 0.0);
}
}
absl::btree_set<std::pair<int, int>> edges_seen;
for (EdgeIdx e = 0; e < num_edges; ++e) {
const int u = request.edges(e).first();
const int v = request.edges(e).second();
TF_RET_CHECK(u >= 0);
TF_RET_CHECK(u < num_nodes);
TF_RET_CHECK(v >= 0);
TF_RET_CHECK(v < num_nodes);
TF_RET_CHECK(u < v);
TF_RET_CHECK(edges_seen.count({u, v}) == 0);
edges_seen.insert({u, v});
const int num_strategies = request.resharding_costs(e).costs_size();
const int num_u_strategies = request.computation_costs(u).costs_size();
const int num_v_strategies = request.computation_costs(v).costs_size();
CHECK_EQ(num_strategies, num_u_strategies * num_v_strategies);
}
return absl::OkStatus();
}
}
} | #include "xla/hlo/experimental/auto_sharding/auto_sharding_solver.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "xla/hlo/experimental/auto_sharding/auto_sharding.pb.h"
#include "xla/hlo/experimental/auto_sharding/auto_sharding_strategy.h"
#include "tsl/platform/platform.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace spmd {
namespace {
using CostMatrix = std::vector<std::vector<double>>;
using NodeMatrix = std::vector<std::vector<int64_t>>;
using EdgeMatrix = std::vector<std::vector<int64_t>>;
void AddCosts(proto2::RepeatedPtrField<AutoShardingSolverRequest_Costs>* costs,
const CostMatrix& cost_matrix) {
for (const auto& cost_row : cost_matrix) {
AutoShardingSolverRequest_Costs cost;
cost.mutable_costs()->Add(cost_row.begin(), cost_row.end());
costs->Add(std::move(cost));
}
}
void AddNodes(proto2::RepeatedPtrField<AutoShardingSolverRequest_Nodes>* nodes,
const NodeMatrix& node_matrix) {
for (const auto& node_row : node_matrix) {
AutoShardingSolverRequest_Nodes node;
node.mutable_nodes()->Add(node_row.begin(), node_row.end());
nodes->Add(std::move(node));
}
}
void AddEdges(proto2::RepeatedPtrField<AutoShardingSolverRequest_Edges>* edges,
const EdgeMatrix& edge_matrix) {
for (const auto& edge_row : edge_matrix) {
AutoShardingSolverRequest_Edges edge;
edge.mutable_edges()->Add(edge_row.begin(), edge_row.end());
edges->Add(std::move(edge));
}
}
void AddIntervals(
proto2::RepeatedPtrField<AutoShardingSolverRequest_Pair>* pairs,
const std::vector<std::pair<int64_t, int64_t>>& intervals) {
for (const auto& interval : intervals) {
AutoShardingSolverRequest_Pair pair;
pair.set_first(interval.first);
pair.set_second(interval.second);
pairs->Add(std::move(pair));
}
}
void AddGroups(
proto2::RepeatedPtrField<AutoShardingSolverRequest_Group>* groups,
const std::vector<std::vector<int64_t>>& reduced_groups) {
for (const auto& reduced_group : reduced_groups) {
AutoShardingSolverRequest_Group group;
group.mutable_prims()->Add(reduced_group.begin(), reduced_group.end());
groups->Add(std::move(group));
}
}
AutoShardingSolverRequest DefaultAutoShardingSolverRequest() {
const auto s_len = {4, 3, 4, 4, 3};
const auto s_follow = {-1, -1, -1, 2, -1};
AutoShardingSolverRequest_Pair edge1, edge2;
edge1.set_first(0);
edge1.set_second(2);
edge2.set_first(1);
edge2.set_second(2);
const auto edges = {edge1, edge2};
const NodeMatrix live = {{1, 0},
{1, 0},
{1, 2, 0},
{1, 2, 3, 0},
{1, 3, 0}};
const CostMatrix c = {{10, 11, 12, 13},
{20, 21, 22},
{30, 31, 32, 33},
{40, 41, 42, 43},
{50, 51, 52}};
const CostMatrix d = {{100, 110, 120, 130},
{200, 210, 220},
{300, 310, 320, 330},
{400, 410, 420, 430},
{500, 510, 520}};
const CostMatrix m = {{100000, 110000, 990000, 130000},
{200000, 210000, 220000},
{300000, 310000, 320000, 330000},
{400000, 410000, 420000, 430000},
{500000, 510000, 520000}};
const CostMatrix p = {{1.0, 0.0, 1.0, 1.0},
{1.0, 0.0, 1.0},
{1.0, 0.0, 1.0, 1.0},
{1.0, 0.0, 1.0, 1.0},
{1.0, 0.0, 1.0}};
const CostMatrix r = {{1000, 1100, 1200, 1300,
2000, 2100, 2200, 2300,
3000, 3100, 3200, 3300,
4000, 4100, 4200, 4300},
{5000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 7300}};
const CostMatrix t = {{73000, 72000, 71000, 70000,
63000, 62000, 61000, 60000,
53000, 52000, 51000, 50000,
43000, 42000, 41000, 40000},
{33000, 32000, 31000, 30000,
23000, 22000, 21000, 20000,
13000, 12000, 11000, 10000}};
AutoShardingSolverRequest_Pair alias;
alias.set_first(1);
alias.set_second(4);
const auto aliases = {alias};
const CostMatrix v = {{0, 1, 1,
1, 0, 1,
1, 1, 0}};
const std::vector<std::string> instruction_names = {"A", "B", "C", "D", "E"};
const std::vector<std::string> metadata_source_files = {"attention.py",
"convolution.py",
"layers.py",
"logits.py",
"pipeline.py"};
AutoShardingSolverRequest request;
request.set_num_nodes(5);
request.set_memory_budget(1500000);
request.mutable_s_len()->Add(s_len.begin(), s_len.end());
request.mutable_s_follow()->Add(s_follow.begin(), s_follow.end());
request.mutable_edges()->Add(edges.begin(), edges.end());
AddNodes(request.mutable_live(), live);
AddCosts(request.mutable_computation_costs(), c);
AddCosts(request.mutable_communication_costs(), d);
AddCosts(request.mutable_memory_costs(), m);
AddCosts(request.mutable_departure_costs(), p);
AddCosts(request.mutable_resharding_costs(), r);
AddCosts(request.mutable_duration_costs(), t);
request.mutable_aliases()->Add(aliases.begin(), aliases.end());
AddCosts(request.mutable_value_costs(), v);
request.mutable_instruction_names()->Add(instruction_names.begin(),
instruction_names.end());
request.mutable_metadata_source_files()->Add(metadata_source_files.begin(),
metadata_source_files.end());
return request;
}
AutoShardingSolverRequest AutoShardingSolverRequestWithEquivalences() {
const auto s_len = {4, 3, 7, 7, 3};
const auto s_follow = {-1, -1, -1, 2, -1};
AutoShardingSolverRequest_Pair edge1, edge2;
edge1.set_first(0);
edge1.set_second(2);
edge2.set_first(1);
edge2.set_second(2);
const auto edges = {edge1, edge2};
const NodeMatrix live = {{1, 0},
{1, 0},
{1, 2, 0},
{1, 2, 3, 0},
{1, 3, 0}};
const CostMatrix c = {{10, 10, 10, 10},
{20, 20, 20},
{30, 30, 31, 30, 30, 30, 30},
{40, 40, 40, 40, 40, 40, 40},
{50, 50, 50}};
const CostMatrix d = {{100, 100, 100, 100},
{200, 200, 200},
{300, 300, 300, 300, 300, 300, 300},
{400, 400, 400, 400, 400, 400, 410},
{500, 500, 500}};
const CostMatrix m = {{10000, 10000, 10000, 10000},
{20000, 20000, 20000},
{30000, 30000, 30000, 31000, 30000, 30000, 30000},
{40000, 40000, 40000, 40000, 40000, 40000, 40000},
{50000, 50000, 50000}};
const CostMatrix p = {{1.0, 0.0, 1.0, 1.0},
{1.0, 0.0, 1.0},
{1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0},
{1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0},
{1.0, 0.0, 1.0}};
const CostMatrix r = {{1000, 1000, 1000, 1000, 1000, 1000, 1000,
2000, 2000, 2000, 2000, 2000, 2000, 2000,
3000, 3000, 3000, 3000, 3100, 3000, 3000,
4000, 4000, 4000, 4000, 4000, 4000, 4000},
{5000, 5000, 5000, 5000, 5000, 5000, 5000,
6000, 6000, 6000, 6000, 6000, 6000, 6000,
7000, 7000, 7000, 7000, 7000, 7000, 7000}};
const CostMatrix t = {{70000, 70000, 70000, 70000, 70000, 70000, 70000,
60000, 60000, 60000, 60000, 60000, 60000, 60000,
50000, 50000, 50000, 50000, 50000, 50000, 50000,
40000, 40000, 40000, 40000, 40000, 40000, 40000},
{30000, 30000, 30000, 30000, 30000, 30000, 30000,
20000, 20000, 20000, 20000, 20000, 20000, 20000,
10000, 10000, 10000, 10000, 10000, 10000, 10000}};
AutoShardingSolverRequest_Pair alias;
alias.set_first(2);
alias.set_second(4);
const auto aliases = {alias};
const CostMatrix v = {{0, 1, 0,
0, 1, 0,
0, 1, 0,
0, 1, 0,
0, 1, 0,
1, 0, 1,
0, 1, 0}};
const std::vector<std::string> instruction_names = {"A", "B", "C", "D", "E"};
AutoShardingSolverRequest request;
request.set_num_nodes(5);
request.set_memory_budget(1500000);
request.mutable_s_len()->Add(s_len.begin(), s_len.end());
request.mutable_s_follow()->Add(s_follow.begin(), s_follow.end());
request.mutable_edges()->Add(edges.begin(), edges.end());
AddNodes(request.mutable_live(), live);
AddCosts(request.mutable_computation_costs(), c);
AddCosts(request.mutable_communication_costs(), d);
AddCosts(request.mutable_memory_costs(), m);
AddCosts(request.mutable_departure_costs(), p);
AddCosts(request.mutable_resharding_costs(), r);
AddCosts(request.mutable_duration_costs(), t);
request.mutable_aliases()->Add(aliases.begin(), aliases.end());
AddCosts(request.mutable_value_costs(), v);
request.mutable_instruction_names()->Add(instruction_names.begin(),
instruction_names.end());
return request;
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, SolvesOptimally) {
const AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 0, 0, 0};
const double objective_value = 7650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, SolvesOverbudget) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.set_memory_budget(100000);
request.mutable_overbudget_coeff()->set_coeff(10.0);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 0, 0, 0};
const double objective_value = 9007650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, SolvesMaxDepartures) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_max_departures()->set_coeff(3.0);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 1, 1, 0};
const double objective_value = 7872.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, MinimizesDepartures) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.set_minimize_departures(true);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 1, 0, 0, 1};
const double objective_value = 3.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, AvoidsInfiniteNodeCosts) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_computation_costs(0)->set_costs(0, kInfinityCost);
request.mutable_computation_costs(0)->set_costs(1, kInfinityCost);
request.mutable_computation_costs(0)->set_costs(2, kInfinityCost);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {3, 0, 0, 0, 0};
const double objective_value = 10683.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, AvoidsInfiniteEdgeCosts) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_resharding_costs(0)->set_costs(0, kInfinityCost);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 1, 1, 0};
const double objective_value = 7872.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, HandlesFollowedEdges) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
AutoShardingSolverRequest_Pair edge;
edge.set_first(1);
edge.set_second(3);
*request.mutable_edges()->Add() = edge;
const CostMatrix r = {{5000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 7300}};
AddCosts(request.mutable_resharding_costs(), r);
const CostMatrix t = {{50000, 51000, 52000, 53000,
60000, 61000, 62000, 63000,
70000, 71000, 72000, 73000}};
AddCosts(request.mutable_duration_costs(), t);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 0, 0, 0};
const double objective_value = 12650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, HandlesCollapsedEdge) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
AutoShardingSolverRequest_Pair edge;
edge.set_first(2);
edge.set_second(3);
*request.mutable_edges()->Add() = edge;
const CostMatrix r = {{9000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 7300,
8000, 8100, 8200, 8300}};
AddCosts(request.mutable_resharding_costs(), r);
const CostMatrix t = {{50000, 51000, 52000, 53000,
60000, 61000, 62000, 63000,
70000, 71000, 72000, 73000,
80000, 81000, 82000, 83000}};
AddCosts(request.mutable_duration_costs(), t);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 1, 1, 0};
const double objective_value = 13972.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, UsesHint) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const auto s_hint = {1, 0, 0, 0, 0};
request.mutable_s_hint()->Add(s_hint.begin(), s_hint.end());
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 0, 0, 0};
const double objective_value = 7650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, HonorsMaxCost) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_max_cost()->set_coeff(7600.0);
const absl::StatusOr<AutoShardingSolverOutput> result =
FormulateAndSolveMIPFromSolverRequest(request);
EXPECT_TRUE(absl::IsInternal(result.status()));
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, HandlesExtremelyHighMaxCost) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_max_cost()->set_coeff(1e19);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 0, 0, 0};
const double objective_value = 7650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, HandlesMemoryEdgeCosts) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const EdgeMatrix live_edges = {{}, {0}, {0, 1}, {1}, {}};
const CostMatrix memory_edge_costs = {{1000000, 1100, 1200, 1300,
2000, 2100, 2200, 2300,
3000, 3100, 3200, 3300,
4000, 4100, 4200, 4300},
{5000000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 7300}};
AddEdges(request.mutable_live_edges(), live_edges);
AddCosts(request.mutable_memory_edge_costs(), memory_edge_costs);
request.set_enable_memory_edge_costs(true);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 1, 1, 0};
const double objective_value = 7872.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, HandlesIntervals) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<std::pair<int64_t, int64_t>> node_intervals =
{{0, 4}, {0, 4}, {2, 3}, {3, 4}, {100, -1}};
const std::vector<std::pair<int64_t, int64_t>> edge_intervals =
{{1, 2}, {2, 3}};
const CostMatrix memory_edge_costs = {{1000000, 1100, 1200, 1300,
2000, 2100, 2200, 2300,
3000, 3100, 3200, 3300,
4000, 4100, 4200, 4300},
{5000000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 7300}};
request.clear_live();
AddIntervals(request.mutable_node_intervals(), node_intervals);
AddIntervals(request.mutable_edge_intervals(), edge_intervals);
AddCosts(request.mutable_memory_edge_costs(), memory_edge_costs);
request.set_enable_memory_edge_costs(true);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 1, 1, 0};
const double objective_value = 7872.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest,
HandlesReducedIntervalsAndGroups) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<std::pair<int64_t, int64_t>> node_intervals =
{{5, -1}, {5, -1}, {2, 3}, {3, 4}, {100, -1}, {0, 4}};
const std::vector<std::pair<int64_t, int64_t>> edge_intervals =
{{1, 2}, {2, 3}};
const std::vector<std::vector<int64_t>> node_groups = {{0, 1}};
const std::vector<std::vector<int64_t>> edge_groups = {};
const CostMatrix memory_edge_costs = {{1000000, 1100, 1200, 1300,
2000, 2100, 2200, 2300,
3000, 3100, 3200, 3300,
4000, 4100, 4200, 4300},
{5000000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 7300}};
request.clear_live();
AddIntervals(request.mutable_node_intervals(), node_intervals);
AddIntervals(request.mutable_edge_intervals(), edge_intervals);
AddGroups(request.mutable_node_groups(), node_groups);
AddGroups(request.mutable_edge_groups(), edge_groups);
AddCosts(request.mutable_memory_edge_costs(), memory_edge_costs);
request.set_enable_memory_edge_costs(true);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 1, 1, 0};
const double objective_value = 7872.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest,
HandlesReducedIntervalsAndGroupsNoMemoryEdgeCosts) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<std::pair<int64_t, int64_t>> node_intervals =
{{5, -1}, {5, -1}, {2, 3}, {3, 4}, {100, -1}, {0, 4}};
const std::vector<std::vector<int64_t>> node_groups = {{0, 1}};
request.clear_live();
AddIntervals(request.mutable_node_intervals(), node_intervals);
AddGroups(request.mutable_node_groups(), node_groups);
request.set_enable_memory_edge_costs(false);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 0, 0, 0};
const double objective_value = 7650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest,
HandlesGroupsWithTinyMemoryCosts) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<std::pair<int64_t, int64_t>> node_intervals =
{{5, -1}, {5, -1}, {2, 3}, {3, 4}, {100, -1}, {0, 4}};
const std::vector<std::pair<int64_t, int64_t>> edge_intervals =
{{1, 2}, {2, 3}};
const std::vector<std::vector<int64_t>> node_groups = {{0, 1}};
const std::vector<std::vector<int64_t>> edge_groups = {};
const CostMatrix memory_costs = {{1, 1, 1, 1},
{2, 2, 2},
{300, 300, 300, 300, 300, 300, 300},
{4000, 4000, 4000, 4000, 4000, 4000, 4000},
{50000, 50000, 50000}};
const CostMatrix memory_edge_costs = {{0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0},
{0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0}};
request.clear_live();
request.clear_memory_costs();
AddIntervals(request.mutable_node_intervals(), node_intervals);
AddIntervals(request.mutable_edge_intervals(), edge_intervals);
AddGroups(request.mutable_node_groups(), node_groups);
AddGroups(request.mutable_edge_groups(), edge_groups);
AddCosts(request.mutable_memory_costs(), memory_costs);
AddCosts(request.mutable_memory_edge_costs(), memory_edge_costs);
request.set_enable_memory_edge_costs(true);
request.set_memory_budget(4321);
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 0, 0, 0};
const double objective_value = 7650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(FormulateAndSolveMIPFromSolverRequestTest, SolvesWithEquivalences) {
const AutoShardingSolverRequest request =
AutoShardingSolverRequestWithEquivalences();
TF_ASSERT_OK_AND_ASSIGN(const AutoShardingSolverOutput result,
FormulateAndSolveMIPFromSolverRequest(request));
const std::vector<NodeStrategyIdx> s_val = {0, 0, 5, 5, 1};
const double objective_value = 7650.0;
const AutoShardingSolverOutput expected_output = {s_val, objective_value};
EXPECT_EQ(result, expected_output);
}
TEST(AutoShardingEvaluatorTest, NoViolations) {
const AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<NodeStrategyIdx> s_val = {3, 1, 2, 2, 1};
const double objective_value = 12149.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.total.computation_cost = 159.0;
expected_evaluation.total.communication_cost = 1590.0;
expected_evaluation.total.resharding_cost = 10400.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, EvaluatesOverbudget) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.set_memory_budget(100000);
request.mutable_overbudget_coeff()->set_coeff(10.0);
const std::vector<NodeStrategyIdx> s_val = {2 , 1, 2, 2, 1};
const double objective_value = 11138.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.total.computation_cost = 158.0;
expected_evaluation.total.communication_cost = 1580.0;
expected_evaluation.total.resharding_cost = 9400.0;
expected_evaluation.total.overbudget_cost = 18400000.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.lower_bound.overbudget_cost = 9000000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, EvaluatesOverbudgetWithIntervals) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<std::pair<int64_t, int64_t>> node_intervals =
{{0, 4}, {0, 4}, {2, 3}, {3, 4}, {100, -1}};
request.set_memory_budget(100000);
request.mutable_overbudget_coeff()->set_coeff(10.0);
request.clear_live();
AddIntervals(request.mutable_node_intervals(), node_intervals);
const std::vector<NodeStrategyIdx> s_val = {2 , 1, 2, 2, 1};
const double objective_value = 11138.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.total.computation_cost = 158.0;
expected_evaluation.total.communication_cost = 1580.0;
expected_evaluation.total.resharding_cost = 9400.0;
expected_evaluation.total.overbudget_cost = 18400000.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.lower_bound.overbudget_cost = 9000000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest,
EvaluatesOverbudgetWithReducedIntervalsAndGroups) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<std::pair<int64_t, int64_t>> node_intervals =
{{5, -1}, {5, -1}, {2, 3}, {3, 4}, {100, -1}, {0, 4}};
const std::vector<std::vector<int64_t>> node_groups = {{0, 1}};
request.set_memory_budget(100000);
request.mutable_overbudget_coeff()->set_coeff(10.0);
request.clear_live();
AddIntervals(request.mutable_node_intervals(), node_intervals);
AddGroups(request.mutable_node_groups(), node_groups);
const std::vector<NodeStrategyIdx> s_val = {2 , 1, 2, 2, 1};
const double objective_value = 11138.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.total.computation_cost = 158.0;
expected_evaluation.total.communication_cost = 1580.0;
expected_evaluation.total.resharding_cost = 9400.0;
expected_evaluation.total.overbudget_cost = 18400000.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.lower_bound.overbudget_cost = 9000000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, ViolatesFollower) {
const AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<NodeStrategyIdx> s_val = {3, 1, 2, 1 , 1};
const double objective_value = 12138.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.violation_codes = {kFollowerViolationCode};
expected_evaluation.total.computation_cost = 158.0;
expected_evaluation.total.communication_cost = 1580.0;
expected_evaluation.total.resharding_cost = 10400.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.total_departures = 2.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, ViolatesAlias) {
const AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<NodeStrategyIdx> s_val = {3, 1, 2, 2, 0 };
const double objective_value = 12138.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.violation_codes = {kAliasViolationCode};
expected_evaluation.total.computation_cost = 158.0;
expected_evaluation.total.communication_cost = 1580.0;
expected_evaluation.total.resharding_cost = 10400.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.total_departures = 4.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, ViolatesMemory) {
const AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
const std::vector<NodeStrategyIdx> s_val = {2 , 1, 2, 2, 1};
const double objective_value = 11138.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.violation_codes = {kMemoryViolationCode};
expected_evaluation.total.computation_cost = 158.0;
expected_evaluation.total.communication_cost = 1580.0;
expected_evaluation.total.resharding_cost = 9400.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, ViolatesInfiniteCostForNode) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_computation_costs(0)->set_costs(0, kInfinityCost);
request.mutable_computation_costs(0)->set_costs(1, kInfinityCost);
request.mutable_computation_costs(0)->set_costs(2, kInfinityCost);
const std::vector<NodeStrategyIdx> s_val = {0 , 1, 2, 2, 1};
const double objective_value = 1e+20;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.violation_codes = {kInfiniteCostViolationCode};
expected_evaluation.total.computation_cost = 1e+20;
expected_evaluation.total.communication_cost = 1560.0;
expected_evaluation.total.resharding_cost = 7400.0;
expected_evaluation.lower_bound.computation_cost = 153.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, ViolatesInfiniteCostForEdge) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_resharding_costs(0)->set_costs(2, kInfinityCost);
const std::vector<NodeStrategyIdx> s_val = {0, 1, 2, 2, 1};
const double objective_value = 1e+20;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.violation_codes = {kInfiniteCostViolationCode};
expected_evaluation.total.computation_cost = 156.0;
expected_evaluation.total.communication_cost = 1560.0;
expected_evaluation.total.resharding_cost = 1e+20;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(AutoShardingEvaluatorTest, ViolatesMaxDepartures) {
AutoShardingSolverRequest request = DefaultAutoShardingSolverRequest();
request.mutable_max_departures()->set_coeff(2.0);
const std::vector<NodeStrategyIdx> s_val = {3, 1, 2, 2, 1};
const double objective_value = 12149.0;
const AutoShardingSolverOutput output = {s_val, objective_value};
const AutoShardingEvaluation evaluation = Evaluate(request, output);
AutoShardingEvaluation expected_evaluation;
expected_evaluation.violation_codes = {kMaxDeparturesViolationCode};
expected_evaluation.total.computation_cost = 159.0;
expected_evaluation.total.communication_cost = 1590.0;
expected_evaluation.total.resharding_cost = 10400.0;
expected_evaluation.lower_bound.computation_cost = 150.0;
expected_evaluation.lower_bound.communication_cost = 1500.0;
expected_evaluation.lower_bound.resharding_cost = 6000.0;
expected_evaluation.total_departures = 3.0;
EXPECT_EQ(evaluation, expected_evaluation);
}
TEST(ScaleRequest, ScalesProperly) {
AutoShardingSolverRequest unscaled_request;
const CostMatrix c = {{10000000, 11000000, 12000000, 13000000},
{20000000, 21000000, 22000000},
{30000000, 31000000, 32000000, 33000000},
{40000000, 41000000, 42000000, 43000000},
{50000000, 51000000, 52000000, 53000000}};
const CostMatrix d = {{100000000, 110000000, 120000000, 130000000},
{200000000, 210000000, 220000000},
{300000000, 310000000, 320000000, 330000000},
{400000000, 410000000, 420000000, 430000000},
{500000000, 510000000, 520000000}};
const CostMatrix r = {{1000000000, 1100000000, 1200000000, 1300000000,
2000000000, 2100000000, 2200000000, 2300000000,
3000000000, 3100000000, 3200000000, 3300000000,
4000000000, 4100000000, 4200000000, 4300000000},
{5000000000, 5100000000, 5200000000, 5300000000,
6000000000, 6100000000, 6200000000, 6300000000,
7000000000, 7100000000, 7200000000, 10000000000000}};
AddCosts(unscaled_request.mutable_computation_costs(), c);
AddCosts(unscaled_request.mutable_communication_costs(), d);
AddCosts(unscaled_request.mutable_resharding_costs(), r);
unscaled_request.mutable_coeff_limit()->set_coeff(1e7);
AutoShardingSolverRequest request = ScaleRequest(unscaled_request);
AutoShardingSolverRequest expected_request;
const CostMatrix expected_c = {{10, 11, 12, 13},
{20, 21, 22},
{30, 31, 32, 33},
{40, 41, 42, 43},
{50, 51, 52, 53}};
const CostMatrix expected_d = {{100, 110, 120, 130},
{200, 210, 220},
{300, 310, 320, 330},
{400, 410, 420, 430},
{500, 510, 520}};
const CostMatrix expected_r = {{1000, 1100, 1200, 1300,
2000, 2100, 2200, 2300,
3000, 3100, 3200, 3300,
4000, 4100, 4200, 4300},
{5000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 10000000}};
AddCosts(expected_request.mutable_computation_costs(), expected_c);
AddCosts(expected_request.mutable_communication_costs(), expected_d);
AddCosts(expected_request.mutable_resharding_costs(), expected_r);
expected_request.mutable_coeff_limit()->set_coeff(1e7);
EXPECT_THAT(request, ::testing::EqualsProto(expected_request));
}
TEST(ScaleRequest, SkipsScaling) {
AutoShardingSolverRequest unscaled_request;
const CostMatrix c = {{10, 11, 12, 13},
{20, 21, 22},
{30, 31, 32, 33},
{40, 41, 42, 43},
{50, 51, 52, 53}};
const CostMatrix d = {{100, 110, 120, 130},
{200, 210, 220},
{300, 310, 320, 330},
{400, 410, 420, 430},
{500, 510, 520}};
const CostMatrix r = {{1000, 1100, 1200, 1300,
2000, 2100, 2200, 2300,
3000, 3100, 3200, 3300,
4000, 4100, 4200, 4300},
{5000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 10000000}};
AddCosts(unscaled_request.mutable_computation_costs(), c);
AddCosts(unscaled_request.mutable_communication_costs(), d);
AddCosts(unscaled_request.mutable_resharding_costs(), r);
unscaled_request.mutable_coeff_limit()->set_coeff(1e7);
AutoShardingSolverRequest request = ScaleRequest(unscaled_request);
AutoShardingSolverRequest expected_request;
const CostMatrix expected_c = {{10, 11, 12, 13},
{20, 21, 22},
{30, 31, 32, 33},
{40, 41, 42, 43},
{50, 51, 52, 53}};
const CostMatrix expected_d = {{100, 110, 120, 130},
{200, 210, 220},
{300, 310, 320, 330},
{400, 410, 420, 430},
{500, 510, 520}};
const CostMatrix expected_r = {{1000, 1100, 1200, 1300,
2000, 2100, 2200, 2300,
3000, 3100, 3200, 3300,
4000, 4100, 4200, 4300},
{5000, 5100, 5200, 5300,
6000, 6100, 6200, 6300,
7000, 7100, 7200, 10000000}};
AddCosts(expected_request.mutable_computation_costs(), expected_c);
AddCosts(expected_request.mutable_communication_costs(), expected_d);
AddCosts(expected_request.mutable_resharding_costs(), expected_r);
expected_request.mutable_coeff_limit()->set_coeff(1e7);
EXPECT_THAT(request, ::testing::EqualsProto(expected_request));
}
TEST(StableMap, IterationOrderDeterminism){
StableMap<int, int> map;
std::vector<int> insertion_order = {6, 3, 1, 2, 4, 5, 10, 0, 7, 9, 8};
for (int key : insertion_order) {
map[key] = key;
}
std::vector<int> iteration_order;
for (const auto& [key, value] : map) {
iteration_order.push_back(key);
}
EXPECT_THAT(iteration_order,
::testing::ElementsAre(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
TEST(ValidateRequest, AcceptsAutoShardingSolverRequest) {
CHECK_OK(ValidateRequest(DefaultAutoShardingSolverRequest()));
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/hlo/experimental/auto_sharding/auto_sharding_solver.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/hlo/experimental/auto_sharding/auto_sharding_solver_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
0db15f84-b317-42b6-b4e2-ea434fdcf309 | cpp | google/quiche | uber_loss_algorithm | quiche/quic/core/congestion_control/uber_loss_algorithm.cc | quiche/quic/core/congestion_control/uber_loss_algorithm_test.cc | #include "quiche/quic/core/congestion_control/uber_loss_algorithm.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
namespace quic {
UberLossAlgorithm::UberLossAlgorithm() {
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
general_loss_algorithms_[i].Initialize(static_cast<PacketNumberSpace>(i),
this);
}
}
void UberLossAlgorithm::SetFromConfig(const QuicConfig& config,
Perspective perspective) {
if (config.HasClientRequestedIndependentOption(kELDT, perspective) &&
tuner_ != nullptr) {
tuning_configured_ = true;
MaybeStartTuning();
}
}
LossDetectionInterface::DetectionStats UberLossAlgorithm::DetectLosses(
const QuicUnackedPacketMap& unacked_packets, QuicTime time,
const RttStats& rtt_stats, QuicPacketNumber ,
const AckedPacketVector& packets_acked, LostPacketVector* packets_lost) {
DetectionStats overall_stats;
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
const QuicPacketNumber largest_acked =
unacked_packets.GetLargestAckedOfPacketNumberSpace(
static_cast<PacketNumberSpace>(i));
if (!largest_acked.IsInitialized() ||
unacked_packets.GetLeastUnacked() > largest_acked) {
continue;
}
DetectionStats stats = general_loss_algorithms_[i].DetectLosses(
unacked_packets, time, rtt_stats, largest_acked, packets_acked,
packets_lost);
overall_stats.sent_packets_max_sequence_reordering =
std::max(overall_stats.sent_packets_max_sequence_reordering,
stats.sent_packets_max_sequence_reordering);
overall_stats.sent_packets_num_borderline_time_reorderings +=
stats.sent_packets_num_borderline_time_reorderings;
overall_stats.total_loss_detection_response_time +=
stats.total_loss_detection_response_time;
}
return overall_stats;
}
QuicTime UberLossAlgorithm::GetLossTimeout() const {
QuicTime loss_timeout = QuicTime::Zero();
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
const QuicTime timeout = general_loss_algorithms_[i].GetLossTimeout();
if (!loss_timeout.IsInitialized()) {
loss_timeout = timeout;
continue;
}
if (timeout.IsInitialized()) {
loss_timeout = std::min(loss_timeout, timeout);
}
}
return loss_timeout;
}
void UberLossAlgorithm::SpuriousLossDetected(
const QuicUnackedPacketMap& unacked_packets, const RttStats& rtt_stats,
QuicTime ack_receive_time, QuicPacketNumber packet_number,
QuicPacketNumber previous_largest_acked) {
general_loss_algorithms_[unacked_packets.GetPacketNumberSpace(packet_number)]
.SpuriousLossDetected(unacked_packets, rtt_stats, ack_receive_time,
packet_number, previous_largest_acked);
}
void UberLossAlgorithm::SetLossDetectionTuner(
std::unique_ptr<LossDetectionTunerInterface> tuner) {
if (tuner_ != nullptr) {
QUIC_BUG(quic_bug_10469_1)
<< "LossDetectionTuner can only be set once when session begins.";
return;
}
tuner_ = std::move(tuner);
}
void UberLossAlgorithm::MaybeStartTuning() {
if (tuner_started_ || !tuning_configured_ || !min_rtt_available_ ||
!user_agent_known_ || !reorder_happened_) {
return;
}
tuner_started_ = tuner_->Start(&tuned_parameters_);
if (!tuner_started_) {
return;
}
if (tuned_parameters_.reordering_shift.has_value() &&
tuned_parameters_.reordering_threshold.has_value()) {
QUIC_DLOG(INFO) << "Setting reordering shift to "
<< *tuned_parameters_.reordering_shift
<< ", and reordering threshold to "
<< *tuned_parameters_.reordering_threshold;
SetReorderingShift(*tuned_parameters_.reordering_shift);
SetReorderingThreshold(*tuned_parameters_.reordering_threshold);
} else {
QUIC_BUG(quic_bug_10469_2)
<< "Tuner started but some parameters are missing";
}
}
void UberLossAlgorithm::OnConfigNegotiated() {}
void UberLossAlgorithm::OnMinRttAvailable() {
min_rtt_available_ = true;
MaybeStartTuning();
}
void UberLossAlgorithm::OnUserAgentIdKnown() {
user_agent_known_ = true;
MaybeStartTuning();
}
void UberLossAlgorithm::OnConnectionClosed() {
if (tuner_ != nullptr && tuner_started_) {
tuner_->Finish(tuned_parameters_);
}
}
void UberLossAlgorithm::OnReorderingDetected() {
const bool tuner_started_before = tuner_started_;
const bool reorder_happened_before = reorder_happened_;
reorder_happened_ = true;
MaybeStartTuning();
if (!tuner_started_before && tuner_started_) {
if (reorder_happened_before) {
QUIC_CODE_COUNT(quic_loss_tuner_started_after_first_reorder);
} else {
QUIC_CODE_COUNT(quic_loss_tuner_started_on_first_reorder);
}
}
}
void UberLossAlgorithm::SetReorderingShift(int reordering_shift) {
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
general_loss_algorithms_[i].set_reordering_shift(reordering_shift);
}
}
void UberLossAlgorithm::SetReorderingThreshold(
QuicPacketCount reordering_threshold) {
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
general_loss_algorithms_[i].set_reordering_threshold(reordering_threshold);
}
}
void UberLossAlgorithm::EnableAdaptiveReorderingThreshold() {
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
general_loss_algorithms_[i].set_use_adaptive_reordering_threshold(true);
}
}
void UberLossAlgorithm::DisableAdaptiveReorderingThreshold() {
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
general_loss_algorithms_[i].set_use_adaptive_reordering_threshold(false);
}
}
void UberLossAlgorithm::EnableAdaptiveTimeThreshold() {
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
general_loss_algorithms_[i].enable_adaptive_time_threshold();
}
}
QuicPacketCount UberLossAlgorithm::GetPacketReorderingThreshold() const {
return general_loss_algorithms_[APPLICATION_DATA].reordering_threshold();
}
int UberLossAlgorithm::GetPacketReorderingShift() const {
return general_loss_algorithms_[APPLICATION_DATA].reordering_shift();
}
void UberLossAlgorithm::DisablePacketThresholdForRuntPackets() {
for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) {
general_loss_algorithms_[i].disable_packet_threshold_for_runt_packets();
}
}
void UberLossAlgorithm::ResetLossDetection(PacketNumberSpace space) {
if (space >= NUM_PACKET_NUMBER_SPACES) {
QUIC_BUG(quic_bug_10469_3) << "Invalid packet number space: " << space;
return;
}
general_loss_algorithms_[space].Reset();
}
} | #include "quiche/quic/core/congestion_control/uber_loss_algorithm.h"
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#include "quiche/quic/core/congestion_control/rtt_stats.h"
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/mock_clock.h"
#include "quiche/quic/test_tools/quic_unacked_packet_map_peer.h"
namespace quic {
namespace test {
namespace {
const uint32_t kDefaultLength = 1000;
class UberLossAlgorithmTest : public QuicTest {
protected:
UberLossAlgorithmTest() {
unacked_packets_ =
std::make_unique<QuicUnackedPacketMap>(Perspective::IS_CLIENT);
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), clock_.Now());
EXPECT_LT(0, rtt_stats_.smoothed_rtt().ToMicroseconds());
}
void SendPacket(uint64_t packet_number, EncryptionLevel encryption_level) {
QuicStreamFrame frame;
QuicTransportVersion version =
CurrentSupportedVersions()[0].transport_version;
frame.stream_id = QuicUtils::GetFirstBidirectionalStreamId(
version, Perspective::IS_CLIENT);
if (encryption_level == ENCRYPTION_INITIAL) {
if (QuicVersionUsesCryptoFrames(version)) {
frame.stream_id = QuicUtils::GetFirstBidirectionalStreamId(
version, Perspective::IS_CLIENT);
} else {
frame.stream_id = QuicUtils::GetCryptoStreamId(version);
}
}
SerializedPacket packet(QuicPacketNumber(packet_number),
PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength,
false, false);
packet.encryption_level = encryption_level;
packet.retransmittable_frames.push_back(QuicFrame(frame));
unacked_packets_->AddSentPacket(&packet, NOT_RETRANSMISSION, clock_.Now(),
true, true, ECN_NOT_ECT);
}
void AckPackets(const std::vector<uint64_t>& packets_acked) {
packets_acked_.clear();
for (uint64_t acked : packets_acked) {
unacked_packets_->RemoveFromInFlight(QuicPacketNumber(acked));
packets_acked_.push_back(AckedPacket(
QuicPacketNumber(acked), kMaxOutgoingPacketSize, QuicTime::Zero()));
}
}
void VerifyLosses(uint64_t largest_newly_acked,
const AckedPacketVector& packets_acked,
const std::vector<uint64_t>& losses_expected) {
return VerifyLosses(largest_newly_acked, packets_acked, losses_expected,
std::nullopt);
}
void VerifyLosses(
uint64_t largest_newly_acked, const AckedPacketVector& packets_acked,
const std::vector<uint64_t>& losses_expected,
std::optional<QuicPacketCount> max_sequence_reordering_expected) {
LostPacketVector lost_packets;
LossDetectionInterface::DetectionStats stats = loss_algorithm_.DetectLosses(
*unacked_packets_, clock_.Now(), rtt_stats_,
QuicPacketNumber(largest_newly_acked), packets_acked, &lost_packets);
if (max_sequence_reordering_expected.has_value()) {
EXPECT_EQ(stats.sent_packets_max_sequence_reordering,
max_sequence_reordering_expected.value());
}
ASSERT_EQ(losses_expected.size(), lost_packets.size());
for (size_t i = 0; i < losses_expected.size(); ++i) {
EXPECT_EQ(lost_packets[i].packet_number,
QuicPacketNumber(losses_expected[i]));
}
}
MockClock clock_;
std::unique_ptr<QuicUnackedPacketMap> unacked_packets_;
RttStats rtt_stats_;
UberLossAlgorithm loss_algorithm_;
AckedPacketVector packets_acked_;
};
TEST_F(UberLossAlgorithmTest, ScenarioA) {
SendPacket(1, ENCRYPTION_INITIAL);
SendPacket(2, ENCRYPTION_ZERO_RTT);
SendPacket(3, ENCRYPTION_ZERO_RTT);
unacked_packets_->RemoveFromInFlight(QuicPacketNumber(1));
SendPacket(4, ENCRYPTION_INITIAL);
AckPackets({1, 4});
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
HANDSHAKE_DATA, QuicPacketNumber(4));
VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}, 0);
EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout());
}
TEST_F(UberLossAlgorithmTest, ScenarioB) {
SendPacket(3, ENCRYPTION_ZERO_RTT);
SendPacket(4, ENCRYPTION_ZERO_RTT);
SendPacket(5, ENCRYPTION_FORWARD_SECURE);
SendPacket(6, ENCRYPTION_FORWARD_SECURE);
AckPackets({4});
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
APPLICATION_DATA, QuicPacketNumber(4));
VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}, 1);
EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(),
loss_algorithm_.GetLossTimeout());
AckPackets({6});
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
APPLICATION_DATA, QuicPacketNumber(6));
VerifyLosses(6, packets_acked_, std::vector<uint64_t>{3}, 3);
EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(),
loss_algorithm_.GetLossTimeout());
packets_acked_.clear();
clock_.AdvanceTime(1.25 * rtt_stats_.latest_rtt());
VerifyLosses(6, packets_acked_, {5}, 1);
}
TEST_F(UberLossAlgorithmTest, ScenarioC) {
QuicUnackedPacketMapPeer::SetPerspective(unacked_packets_.get(),
Perspective::IS_SERVER);
SendPacket(1, ENCRYPTION_ZERO_RTT);
SendPacket(2, ENCRYPTION_FORWARD_SECURE);
SendPacket(3, ENCRYPTION_FORWARD_SECURE);
SendPacket(4, ENCRYPTION_FORWARD_SECURE);
unacked_packets_->RemoveFromInFlight(QuicPacketNumber(1));
SendPacket(5, ENCRYPTION_ZERO_RTT);
AckPackets({4, 5});
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
APPLICATION_DATA, QuicPacketNumber(4));
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
HANDSHAKE_DATA, QuicPacketNumber(5));
VerifyLosses(5, packets_acked_, std::vector<uint64_t>{}, 2);
EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(),
loss_algorithm_.GetLossTimeout());
packets_acked_.clear();
clock_.AdvanceTime(1.25 * rtt_stats_.latest_rtt());
VerifyLosses(5, packets_acked_, std::vector<uint64_t>{2, 3}, 2);
}
TEST_F(UberLossAlgorithmTest, PacketInLimbo) {
QuicUnackedPacketMapPeer::SetPerspective(unacked_packets_.get(),
Perspective::IS_SERVER);
SendPacket(1, ENCRYPTION_ZERO_RTT);
SendPacket(2, ENCRYPTION_FORWARD_SECURE);
SendPacket(3, ENCRYPTION_FORWARD_SECURE);
SendPacket(4, ENCRYPTION_ZERO_RTT);
SendPacket(5, ENCRYPTION_FORWARD_SECURE);
AckPackets({1, 3, 4});
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
APPLICATION_DATA, QuicPacketNumber(3));
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
HANDSHAKE_DATA, QuicPacketNumber(4));
VerifyLosses(4, packets_acked_, std::vector<uint64_t>{});
SendPacket(6, ENCRYPTION_FORWARD_SECURE);
AckPackets({5, 6});
unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace(
APPLICATION_DATA, QuicPacketNumber(6));
VerifyLosses(6, packets_acked_, std::vector<uint64_t>{2});
}
class TestLossTuner : public LossDetectionTunerInterface {
public:
TestLossTuner(bool forced_start_result,
LossDetectionParameters forced_parameters)
: forced_start_result_(forced_start_result),
forced_parameters_(std::move(forced_parameters)) {}
~TestLossTuner() override = default;
bool Start(LossDetectionParameters* params) override {
start_called_ = true;
*params = forced_parameters_;
return forced_start_result_;
}
void Finish(const LossDetectionParameters& ) override {}
bool start_called() const { return start_called_; }
private:
bool forced_start_result_;
LossDetectionParameters forced_parameters_;
bool start_called_ = false;
};
TEST_F(UberLossAlgorithmTest, LossDetectionTuning_SetFromConfigFirst) {
const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift();
const QuicPacketCount old_reordering_threshold =
loss_algorithm_.GetPacketReorderingThreshold();
loss_algorithm_.OnUserAgentIdKnown();
TestLossTuner* test_tuner = new TestLossTuner(
true,
LossDetectionParameters{
old_reordering_shift + 1,
old_reordering_threshold * 2});
loss_algorithm_.SetLossDetectionTuner(
std::unique_ptr<LossDetectionTunerInterface>(test_tuner));
QuicConfig config;
QuicTagVector connection_options;
connection_options.push_back(kELDT);
config.SetInitialReceivedConnectionOptions(connection_options);
loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER);
EXPECT_FALSE(test_tuner->start_called());
EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift());
EXPECT_EQ(old_reordering_threshold,
loss_algorithm_.GetPacketReorderingThreshold());
loss_algorithm_.OnMinRttAvailable();
EXPECT_FALSE(test_tuner->start_called());
loss_algorithm_.OnReorderingDetected();
EXPECT_TRUE(test_tuner->start_called());
EXPECT_NE(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift());
EXPECT_NE(old_reordering_threshold,
loss_algorithm_.GetPacketReorderingThreshold());
}
TEST_F(UberLossAlgorithmTest, LossDetectionTuning_OnMinRttAvailableFirst) {
const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift();
const QuicPacketCount old_reordering_threshold =
loss_algorithm_.GetPacketReorderingThreshold();
loss_algorithm_.OnUserAgentIdKnown();
TestLossTuner* test_tuner = new TestLossTuner(
true,
LossDetectionParameters{
old_reordering_shift + 1,
old_reordering_threshold * 2});
loss_algorithm_.SetLossDetectionTuner(
std::unique_ptr<LossDetectionTunerInterface>(test_tuner));
loss_algorithm_.OnMinRttAvailable();
EXPECT_FALSE(test_tuner->start_called());
EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift());
EXPECT_EQ(old_reordering_threshold,
loss_algorithm_.GetPacketReorderingThreshold());
loss_algorithm_.OnReorderingDetected();
EXPECT_FALSE(test_tuner->start_called());
QuicConfig config;
QuicTagVector connection_options;
connection_options.push_back(kELDT);
config.SetInitialReceivedConnectionOptions(connection_options);
loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER);
EXPECT_TRUE(test_tuner->start_called());
EXPECT_NE(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift());
EXPECT_NE(old_reordering_threshold,
loss_algorithm_.GetPacketReorderingThreshold());
}
TEST_F(UberLossAlgorithmTest, LossDetectionTuning_StartFailed) {
const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift();
const QuicPacketCount old_reordering_threshold =
loss_algorithm_.GetPacketReorderingThreshold();
loss_algorithm_.OnUserAgentIdKnown();
TestLossTuner* test_tuner = new TestLossTuner(
false,
LossDetectionParameters{
old_reordering_shift + 1,
old_reordering_threshold * 2});
loss_algorithm_.SetLossDetectionTuner(
std::unique_ptr<LossDetectionTunerInterface>(test_tuner));
QuicConfig config;
QuicTagVector connection_options;
connection_options.push_back(kELDT);
config.SetInitialReceivedConnectionOptions(connection_options);
loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER);
EXPECT_FALSE(test_tuner->start_called());
EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift());
EXPECT_EQ(old_reordering_threshold,
loss_algorithm_.GetPacketReorderingThreshold());
loss_algorithm_.OnReorderingDetected();
EXPECT_FALSE(test_tuner->start_called());
loss_algorithm_.OnMinRttAvailable();
EXPECT_TRUE(test_tuner->start_called());
EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift());
EXPECT_EQ(old_reordering_threshold,
loss_algorithm_.GetPacketReorderingThreshold());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/uber_loss_algorithm.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/uber_loss_algorithm_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
16a28cdd-9ae5-45f7-b5be-371ad5429024 | cpp | tensorflow/tensorflow | runtime_topk | third_party/xla/xla/service/cpu/runtime_topk.cc | third_party/xla/xla/tests/runtime_topk_test.cc | #include "xla/service/cpu/runtime_topk.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <limits>
#include <numeric>
#include <vector>
#include "absl/base/casts.h"
#include "absl/base/dynamic_annotations.h"
template <typename T>
static void TopK(int64_t batch_size, int64_t input_size, int64_t k,
const T* values, T* out_values, int32_t* out_indices) {
ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(values,
input_size * batch_size * sizeof(T));
static constexpr auto convert_to_int = [](T value) {
uint32_t x = absl::bit_cast<uint32_t>(value);
return static_cast<int32_t>(x) < 0 ? std::numeric_limits<int32_t>::max() - x
: x;
};
std::vector<int32_t> temp_indices(input_size);
for (int64_t batch = 0; batch != batch_size; ++batch) {
std::iota(temp_indices.begin(), temp_indices.end(), 0);
const T* values_batch = values + batch * input_size;
auto kth_element = temp_indices.begin() + k;
std::partial_sort(temp_indices.begin(), kth_element, temp_indices.end(),
[values_batch](size_t i1, size_t i2) {
int32_t v1 = convert_to_int(values_batch[i1]);
int32_t v2 = convert_to_int(values_batch[i2]);
if (v1 == v2) {
return i1 < i2;
}
return v1 > v2;
});
T* out_values_batch = out_values + batch * k;
int32_t* out_indices_batch = out_indices + batch * k;
std::copy(temp_indices.begin(), kth_element, out_indices_batch);
for (int64_t i = 0; i < k; i++) {
out_values_batch[i] = values_batch[temp_indices[i]];
}
}
}
ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_TopKF32(
int64_t batch_size, int64_t input_size, int64_t k, const float* values,
float* out_values, int32_t* out_indices) {
TopK(batch_size, input_size, k, values, out_values, out_indices);
} | #include <string_view>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/tests/hlo_test_base.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tests/test_macros.h"
#include "tsl/platform/statusor.h"
namespace xla::cpu {
namespace {
class TopkTest : public HloTestBase {};
XLA_TEST_F(TopkTest, CustomCallTarget) {
std::string_view hlo_text_module = R"(
HloModule topk
ENTRY TopK {
x = f32[10,10] parameter(0)
ROOT topk = (f32[10,3], s32[10,3]) custom-call(x), custom_call_target="TopK"
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_text_module));
auto input =
LiteralUtil::CreateR2<float>({{98, 21, 67, 27, 54, 67, 98, 84, 9, 62},
{65, 68, 49, 3, 9, 0, 52, 78, 36, 96},
{44, 50, 35, 62, 33, 19, 37, 26, 23, 90},
{34, 55, 10, 98, 19, 35, 11, 77, 25, 1},
{87, 19, 15, 98, 35, 90, 64, 60, 80, 12},
{8, 11, 77, 52, 76, 33, 39, 55, 74, 96},
{75, 69, 2, 85, 85, 65, 48, 29, 91, 25},
{26, 4, 76, 48, 88, 96, 71, 2, 58, 68},
{42, 90, 38, 86, 18, 0, 22, 28, 1, 39},
{90, 34, 63, 92, 30, 54, 3, 98, 85, 4}});
TF_ASSERT_OK_AND_ASSIGN(auto result, Execute(std::move(module), {&input}));
std::vector<Literal> results = result.DecomposeTuple();
ASSERT_EQ(results.size(), 2);
LiteralTestUtil::ExpectR2Equal<float>({{98, 98, 84},
{96, 78, 68},
{90, 62, 50},
{98, 77, 55},
{98, 90, 87},
{96, 77, 76},
{91, 85, 85},
{96, 88, 76},
{90, 86, 42},
{98, 92, 90}},
results[0]);
LiteralTestUtil::ExpectR2Equal({{0, 6, 7},
{9, 7, 1},
{9, 3, 1},
{3, 7, 1},
{3, 5, 0},
{9, 2, 4},
{8, 3, 4},
{5, 4, 2},
{1, 3, 0},
{7, 3, 0}},
results[1]);
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/cpu/runtime_topk.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tests/runtime_topk_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
4d1c1e7d-aee8-4526-8ad0-2a8d3a0803f6 | cpp | tensorflow/tensorflow | list_reserve | tensorflow/lite/kernels/variants/list_kernels/list_reserve.cc | tensorflow/lite/kernels/variants/list_kernels/list_reserve_test.cc | #include <cstring>
#include <utility>
#include "tensorflow/lite/array.h"
#include "tensorflow/lite/core/c/c_api_types.h"
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/variants/list_ops_lib.h"
#include "tensorflow/lite/kernels/variants/list_ops_util.h"
#include "tensorflow/lite/kernels/variants/tensor_array.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/util.h"
namespace tflite {
namespace variants {
namespace ops {
namespace list_reserve {
namespace {
using ::tflite::variants::TensorArray;
using ::tflite::variants::detail::ListReserveOptions;
TfLiteType ConvertTensorType(TensorType src) {
switch (src) {
case TensorType_INT32:
return kTfLiteInt32;
case TensorType_FLOAT32:
return kTfLiteFloat32;
case TensorType_BOOL:
return kTfLiteBool;
case TensorType_INT64:
return kTfLiteInt64;
default:
return kTfLiteNoType;
}
}
constexpr int kListOut = 0;
struct SemanticOutType {
TfLiteType element_type;
IntArrayUniquePtr element_shape;
int num_elements;
};
class ReserveSemantic {
public:
ReserveSemantic(TfLiteContext* context, TfLiteNode* node)
: context_(context), node_(node) {}
constexpr static int kElementShapeInput = 0;
constexpr static int kNumElementsInput = 1;
TfLiteStatus CheckInputs() const {
TF_LITE_ENSURE_EQ(context_, NumInputs(node_), 2);
const TfLiteTensor* element_shape;
TF_LITE_ENSURE_OK(
context_,
GetInputSafe(context_, node_, kElementShapeInput, &element_shape));
TF_LITE_ENSURE(context_, element_shape->type == kTfLiteInt32);
const TfLiteTensor* num_elements;
TF_LITE_ENSURE_OK(context_, GetInputSafe(context_, node_, kNumElementsInput,
&num_elements));
TF_LITE_ENSURE_TYPES_EQ(context_, num_elements->type, kTfLiteInt32);
return kTfLiteOk;
}
TfLiteStatus Compute(SemanticOutType& result) const {
auto* options =
reinterpret_cast<const ListReserveOptions*>(node_->custom_initial_data);
TfLiteType element_type = ConvertTensorType(options->element_type);
TF_LITE_ENSURE(context_, element_type != kTfLiteNoType);
const TfLiteTensor* num_elements;
TF_LITE_ENSURE_OK(context_, GetInputSafe(context_, node_, kNumElementsInput,
&num_elements));
TF_LITE_ENSURE_TYPES_EQ(context_, num_elements->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context_, num_elements->dims->size, 0);
const int num_elements_value = num_elements->data.i32[0];
TF_LITE_ENSURE(context_, num_elements_value >= 0);
const TfLiteTensor* element_shape_tensor;
TF_LITE_ENSURE_OK(context_,
GetInputSafe(context_, node_, kElementShapeInput,
&element_shape_tensor));
IntArrayUniquePtr element_shape = TensorAsShape(*element_shape_tensor);
result = SemanticOutType{element_type, std::move(element_shape),
num_elements_value};
return kTfLiteOk;
}
TfLiteStatus PopulateOutput(TensorArray* const output) const {
return kTfLiteOk;
}
private:
TfLiteContext* const context_;
TfLiteNode* const node_;
};
class ZerosLikeSemantic {
public:
ZerosLikeSemantic(TfLiteContext* context, TfLiteNode* node)
: context_(context), node_(node) {}
constexpr static int kListInput = 0;
TfLiteStatus CheckInputs() const {
TF_LITE_ENSURE_EQ(context_, NumInputs(node_), 1);
const TfLiteTensor* list_input;
TF_LITE_ENSURE_OK(context_,
GetInputSafe(context_, node_, kListInput, &list_input));
TF_LITE_ENSURE(context_, list_input->type == kTfLiteVariant);
return kTfLiteOk;
}
TfLiteStatus Compute(SemanticOutType& result) const {
const TfLiteTensor* list_input;
TF_LITE_ENSURE_OK(context_,
GetInputSafe(context_, node_, kListInput, &list_input));
const TensorArray* const input =
reinterpret_cast<const TensorArray*>(list_input->data.data);
result = SemanticOutType{input->ElementType(),
BuildTfLiteArray(*input->ElementShape()),
input->NumElements()};
return kTfLiteOk;
}
TfLiteStatus PopulateOutput(TensorArray* const output) const {
const TfLiteTensor* list_input;
TF_LITE_ENSURE_OK(context_,
GetInputSafe(context_, node_, kListInput, &list_input));
const TensorArray* const input =
reinterpret_cast<const TensorArray*>(list_input->data.data);
for (int i = 0; i < input->NumElements(); ++i) {
const TfLiteTensor* const at = input->At(i);
if (at == nullptr) continue;
TensorUniquePtr output_at = BuildTfLiteTensor(
at->type, BuildTfLiteArray(*at->dims), kTfLiteDynamic);
memset(output_at->data.data, 0, output_at->bytes);
TF_LITE_ENSURE(context_, output->Set(i, std::move(output_at)));
}
return kTfLiteOk;
}
private:
TfLiteContext* const context_;
TfLiteNode* const node_;
};
template <class Semantic>
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const Semantic sem(context, node);
TF_LITE_ENSURE_OK(context, sem.CheckInputs());
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kListOut, &output));
TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteVariant);
output->allocation_type = kTfLiteVariantObject;
return kTfLiteOk;
}
template <class Semantic>
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const Semantic sem(context, node);
SemanticOutType data;
TF_LITE_ENSURE_OK(context, sem.Compute(data));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kListOut, &output));
TfLiteStatus stat = TfLiteTensorVariantRealloc<TensorArray>(
output, data.element_type, std::move(data.element_shape));
TF_LITE_ENSURE_OK(context, stat);
TensorArray* const arr =
static_cast<TensorArray*>(static_cast<VariantData*>(output->data.data));
arr->Resize(data.num_elements);
TF_LITE_ENSURE_OK(context, sem.PopulateOutput(arr));
return kTfLiteOk;
}
}
}
TfLiteRegistration* Register_LIST_RESERVE() {
static TfLiteRegistration r = {
nullptr, nullptr, list_reserve::Prepare<list_reserve::ReserveSemantic>,
list_reserve::Eval<list_reserve::ReserveSemantic>};
return &r;
}
TfLiteRegistration* Register_VARIANT_ZEROS_LIKE() {
static TfLiteRegistration r = {
nullptr, nullptr, list_reserve::Prepare<list_reserve::ZerosLikeSemantic>,
list_reserve::Eval<list_reserve::ZerosLikeSemantic>};
return &r;
}
}
}
} | #include <cstring>
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/lite/core/c/c_api_types.h"
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/kernels/variants/list_ops_lib.h"
#include "tensorflow/lite/kernels/variants/tensor_array.h"
#include "tensorflow/lite/schema/schema_generated.h"
namespace tflite {
namespace variants {
namespace ops {
namespace {
using ::tflite::variants::TensorArray;
std::vector<uint8_t> CustomOptionsToRaw(const std::vector<int32_t>& options) {
std::vector<uint8_t> raw(options.size() * sizeof(int32_t));
std::memcpy(raw.data(), options.data(), raw.size());
return raw;
}
class ListReserveModel : public SingleOpModel {
public:
explicit ListReserveModel(TensorType element_type) {
element_shape_input_ = AddInput({TensorType_INT32, {1}});
list_len_input_ = AddInput({TensorType_INT32, {}});
reserve_output_ = AddOutput({TensorType_VARIANT, {}});
SetCustomOp("ListReserve", CustomOptionsToRaw({element_type}),
Register_LIST_RESERVE);
BuildInterpreter({{1}, {}});
}
const TfLiteTensor* GetOutputTensor(int index) {
return interpreter_->tensor(index);
}
int list_len_input_;
int reserve_output_;
int element_shape_input_;
};
TEST(ListReserveTest, NonZeroNumElements_StaticShape) {
ListReserveModel m(TensorType_INT32);
m.PopulateTensor(m.list_len_input_, {5});
m.PopulateTensor(m.element_shape_input_, {2});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
const TfLiteTensor* tensor = m.GetOutputTensor(m.reserve_output_);
EXPECT_EQ(tensor->type, kTfLiteVariant);
EXPECT_EQ(tensor->allocation_type, kTfLiteVariantObject);
TensorArray* arr = reinterpret_cast<TensorArray*>(tensor->data.data);
EXPECT_EQ(arr->ElementType(), kTfLiteInt32);
EXPECT_EQ(arr->ElementShape()->size, 1);
ASSERT_EQ(arr->ElementShape()->data[0], 2);
ASSERT_EQ(arr->NumElements(), 5);
for (int i = 0; i < 5; ++i) {
ASSERT_EQ(arr->At(i), nullptr);
}
}
TEST(ListReserveTest, NegativeNumElements_Fails) {
ListReserveModel m(TensorType_INT32);
m.PopulateTensor(m.list_len_input_, {-1});
m.PopulateTensor(m.element_shape_input_, {2});
ASSERT_EQ(m.Invoke(), kTfLiteError);
}
TEST(ListReserveTest, NumElements0_StaticShape_Succeeds) {
ListReserveModel m(TensorType_INT32);
m.PopulateTensor(m.list_len_input_, {0});
m.PopulateTensor(m.element_shape_input_, {2});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
const TfLiteTensor* tensor = m.GetOutputTensor(m.reserve_output_);
TensorArray* arr = reinterpret_cast<TensorArray*>(tensor->data.data);
EXPECT_EQ(arr->NumElements(), 0);
EXPECT_EQ(arr->ElementType(), kTfLiteInt32);
}
TEST(ListReserveTest, NumElements0_StaticShape_FloatType) {
ListReserveModel m(TensorType_FLOAT32);
m.PopulateTensor(m.list_len_input_, {0});
m.PopulateTensor(m.element_shape_input_, {2});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
const TfLiteTensor* tensor = m.GetOutputTensor(m.reserve_output_);
TensorArray* arr = reinterpret_cast<TensorArray*>(tensor->data.data);
EXPECT_EQ(arr->NumElements(), 0);
EXPECT_EQ(arr->ElementType(), kTfLiteFloat32);
}
TEST(ListReserveTest, UnsupportedDataType_Fails) {
ListReserveModel m(TensorType_COMPLEX64);
m.PopulateTensor(m.list_len_input_, {0});
m.PopulateTensor(m.element_shape_input_, {2});
ASSERT_EQ(m.Invoke(), kTfLiteError);
}
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/variants/list_kernels/list_reserve.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/variants/list_kernels/list_reserve_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
a6800de3-849c-48b0-9041-0987170573d6 | cpp | abseil/abseil-cpp | bind | absl/strings/internal/str_format/bind.cc | absl/strings/internal/str_format/bind_test.cc | #include "absl/strings/internal/str_format/bind.h"
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstddef>
#include <cstdio>
#include <ios>
#include <limits>
#include <ostream>
#include <sstream>
#include <string>
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#include "absl/strings/internal/str_format/arg.h"
#include "absl/strings/internal/str_format/constexpr_parser.h"
#include "absl/strings/internal/str_format/extension.h"
#include "absl/strings/internal/str_format/output.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
inline bool BindFromPosition(int position, int* value,
absl::Span<const FormatArgImpl> pack) {
assert(position > 0);
if (static_cast<size_t>(position) > pack.size()) {
return false;
}
return FormatArgImplFriend::ToInt(pack[static_cast<size_t>(position) - 1],
value);
}
class ArgContext {
public:
explicit ArgContext(absl::Span<const FormatArgImpl> pack) : pack_(pack) {}
bool Bind(const UnboundConversion* unbound, BoundConversion* bound);
private:
absl::Span<const FormatArgImpl> pack_;
};
inline bool ArgContext::Bind(const UnboundConversion* unbound,
BoundConversion* bound) {
const FormatArgImpl* arg = nullptr;
int arg_position = unbound->arg_position;
if (static_cast<size_t>(arg_position - 1) >= pack_.size()) return false;
arg = &pack_[static_cast<size_t>(arg_position - 1)];
if (unbound->flags != Flags::kBasic) {
int width = unbound->width.value();
bool force_left = false;
if (unbound->width.is_from_arg()) {
if (!BindFromPosition(unbound->width.get_from_arg(), &width, pack_))
return false;
if (width < 0) {
force_left = true;
width = -std::max(width, -std::numeric_limits<int>::max());
}
}
int precision = unbound->precision.value();
if (unbound->precision.is_from_arg()) {
if (!BindFromPosition(unbound->precision.get_from_arg(), &precision,
pack_))
return false;
}
FormatConversionSpecImplFriend::SetWidth(width, bound);
FormatConversionSpecImplFriend::SetPrecision(precision, bound);
if (force_left) {
FormatConversionSpecImplFriend::SetFlags(unbound->flags | Flags::kLeft,
bound);
} else {
FormatConversionSpecImplFriend::SetFlags(unbound->flags, bound);
}
FormatConversionSpecImplFriend::SetLengthMod(unbound->length_mod, bound);
} else {
FormatConversionSpecImplFriend::SetFlags(unbound->flags, bound);
FormatConversionSpecImplFriend::SetWidth(-1, bound);
FormatConversionSpecImplFriend::SetPrecision(-1, bound);
}
FormatConversionSpecImplFriend::SetConversionChar(unbound->conv, bound);
bound->set_arg(arg);
return true;
}
template <typename Converter>
class ConverterConsumer {
public:
ConverterConsumer(Converter converter, absl::Span<const FormatArgImpl> pack)
: converter_(converter), arg_context_(pack) {}
bool Append(string_view s) {
converter_.Append(s);
return true;
}
bool ConvertOne(const UnboundConversion& conv, string_view conv_string) {
BoundConversion bound;
if (!arg_context_.Bind(&conv, &bound)) return false;
return converter_.ConvertOne(bound, conv_string);
}
private:
Converter converter_;
ArgContext arg_context_;
};
template <typename Converter>
bool ConvertAll(const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args, Converter converter) {
if (format.has_parsed_conversion()) {
return format.parsed_conversion()->ProcessFormat(
ConverterConsumer<Converter>(converter, args));
} else {
return ParseFormatString(format.str(),
ConverterConsumer<Converter>(converter, args));
}
}
class DefaultConverter {
public:
explicit DefaultConverter(FormatSinkImpl* sink) : sink_(sink) {}
void Append(string_view s) const { sink_->Append(s); }
bool ConvertOne(const BoundConversion& bound, string_view ) const {
return FormatArgImplFriend::Convert(*bound.arg(), bound, sink_);
}
private:
FormatSinkImpl* sink_;
};
class SummarizingConverter {
public:
explicit SummarizingConverter(FormatSinkImpl* sink) : sink_(sink) {}
void Append(string_view s) const { sink_->Append(s); }
bool ConvertOne(const BoundConversion& bound, string_view ) const {
UntypedFormatSpecImpl spec("%d");
std::ostringstream ss;
ss << "{" << Streamable(spec, {*bound.arg()}) << ":"
<< FormatConversionSpecImplFriend::FlagsToString(bound);
if (bound.width() >= 0) ss << bound.width();
if (bound.precision() >= 0) ss << "." << bound.precision();
ss << bound.conversion_char() << "}";
Append(ss.str());
return true;
}
private:
FormatSinkImpl* sink_;
};
}
bool BindWithPack(const UnboundConversion* props,
absl::Span<const FormatArgImpl> pack,
BoundConversion* bound) {
return ArgContext(pack).Bind(props, bound);
}
std::string Summarize(const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
typedef SummarizingConverter Converter;
std::string out;
{
FormatSinkImpl sink(&out);
if (!ConvertAll(format, args, Converter(&sink))) {
return "";
}
}
return out;
}
bool FormatUntyped(FormatRawSinkImpl raw_sink,
const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
FormatSinkImpl sink(raw_sink);
using Converter = DefaultConverter;
return ConvertAll(format, args, Converter(&sink));
}
std::ostream& Streamable::Print(std::ostream& os) const {
if (!FormatUntyped(&os, format_, args_)) os.setstate(std::ios::failbit);
return os;
}
std::string& AppendPack(std::string* out, const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
size_t orig = out->size();
if (ABSL_PREDICT_FALSE(!FormatUntyped(out, format, args))) {
out->erase(orig);
}
return *out;
}
std::string FormatPack(UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
std::string out;
if (ABSL_PREDICT_FALSE(!FormatUntyped(&out, format, args))) {
out.clear();
}
return out;
}
int FprintF(std::FILE* output, const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
FILERawSink sink(output);
if (!FormatUntyped(&sink, format, args)) {
errno = EINVAL;
return -1;
}
if (sink.error()) {
errno = sink.error();
return -1;
}
if (sink.count() > static_cast<size_t>(std::numeric_limits<int>::max())) {
errno = EFBIG;
return -1;
}
return static_cast<int>(sink.count());
}
int SnprintF(char* output, size_t size, const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
BufferRawSink sink(output, size ? size - 1 : 0);
if (!FormatUntyped(&sink, format, args)) {
errno = EINVAL;
return -1;
}
size_t total = sink.total_written();
if (size) output[std::min(total, size - 1)] = 0;
return static_cast<int>(total);
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/str_format/bind.h"
#include <string.h>
#include <limits>
#include "gtest/gtest.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
class FormatBindTest : public ::testing::Test {
public:
bool Extract(const char *s, UnboundConversion *props, int *next) const {
return ConsumeUnboundConversion(s, s + strlen(s), props, next) ==
s + strlen(s);
}
};
TEST_F(FormatBindTest, BindSingle) {
struct Expectation {
int line;
const char *fmt;
int ok_phases;
const FormatArgImpl *arg;
int width;
int precision;
int next_arg;
};
const int no = -1;
const int ia[] = { 10, 20, 30, 40};
const FormatArgImpl args[] = {FormatArgImpl(ia[0]), FormatArgImpl(ia[1]),
FormatArgImpl(ia[2]), FormatArgImpl(ia[3])};
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
const Expectation kExpect[] = {
{__LINE__, "d", 2, &args[0], no, no, 2},
{__LINE__, "4d", 2, &args[0], 4, no, 2},
{__LINE__, ".5d", 2, &args[0], no, 5, 2},
{__LINE__, "4.5d", 2, &args[0], 4, 5, 2},
{__LINE__, "*d", 2, &args[1], 10, no, 3},
{__LINE__, ".*d", 2, &args[1], no, 10, 3},
{__LINE__, "*.*d", 2, &args[2], 10, 20, 4},
{__LINE__, "1$d", 2, &args[0], no, no, 0},
{__LINE__, "2$d", 2, &args[1], no, no, 0},
{__LINE__, "3$d", 2, &args[2], no, no, 0},
{__LINE__, "4$d", 2, &args[3], no, no, 0},
{__LINE__, "2$*1$d", 2, &args[1], 10, no, 0},
{__LINE__, "2$*2$d", 2, &args[1], 20, no, 0},
{__LINE__, "2$*3$d", 2, &args[1], 30, no, 0},
{__LINE__, "2$.*1$d", 2, &args[1], no, 10, 0},
{__LINE__, "2$.*2$d", 2, &args[1], no, 20, 0},
{__LINE__, "2$.*3$d", 2, &args[1], no, 30, 0},
{__LINE__, "2$*3$.*1$d", 2, &args[1], 30, 10, 0},
{__LINE__, "2$*2$.*2$d", 2, &args[1], 20, 20, 0},
{__LINE__, "2$*1$.*3$d", 2, &args[1], 10, 30, 0},
{__LINE__, "2$*3$.*1$d", 2, &args[1], 30, 10, 0},
{__LINE__, "1$*d", 0},
{__LINE__, "*2$d", 0},
{__LINE__, "6$d", 1},
{__LINE__, "1$6$d", 0},
{__LINE__, "1$.6$d", 0},
{__LINE__, "1$*6$d", 1},
{__LINE__, "1$.*6$d", 1},
};
#pragma GCC diagnostic pop
for (const Expectation &e : kExpect) {
SCOPED_TRACE(e.line);
SCOPED_TRACE(e.fmt);
UnboundConversion props;
BoundConversion bound;
int ok_phases = 0;
int next = 0;
if (Extract(e.fmt, &props, &next)) {
++ok_phases;
if (BindWithPack(&props, args, &bound)) {
++ok_phases;
}
}
EXPECT_EQ(e.ok_phases, ok_phases);
if (e.ok_phases < 2) continue;
if (e.arg != nullptr) {
EXPECT_EQ(e.arg, bound.arg());
}
EXPECT_EQ(e.width, bound.width());
EXPECT_EQ(e.precision, bound.precision());
}
}
TEST_F(FormatBindTest, WidthUnderflowRegression) {
UnboundConversion props;
BoundConversion bound;
int next = 0;
const int args_i[] = {std::numeric_limits<int>::min(), 17};
const FormatArgImpl args[] = {FormatArgImpl(args_i[0]),
FormatArgImpl(args_i[1])};
ASSERT_TRUE(Extract("*d", &props, &next));
ASSERT_TRUE(BindWithPack(&props, args, &bound));
EXPECT_EQ(bound.width(), std::numeric_limits<int>::max());
EXPECT_EQ(bound.arg(), args + 1);
}
TEST_F(FormatBindTest, FormatPack) {
struct Expectation {
int line;
const char *fmt;
const char *summary;
};
const int ia[] = { 10, 20, 30, 40, -10 };
const FormatArgImpl args[] = {FormatArgImpl(ia[0]), FormatArgImpl(ia[1]),
FormatArgImpl(ia[2]), FormatArgImpl(ia[3]),
FormatArgImpl(ia[4])};
const Expectation kExpect[] = {
{__LINE__, "a%4db%dc", "a{10:4d}b{20:d}c"},
{__LINE__, "a%.4db%dc", "a{10:.4d}b{20:d}c"},
{__LINE__, "a%4.5db%dc", "a{10:4.5d}b{20:d}c"},
{__LINE__, "a%db%4.5dc", "a{10:d}b{20:4.5d}c"},
{__LINE__, "a%db%*.*dc", "a{10:d}b{40:20.30d}c"},
{__LINE__, "a%.*fb", "a{20:.10f}b"},
{__LINE__, "a%1$db%2$*3$.*4$dc", "a{10:d}b{20:30.40d}c"},
{__LINE__, "a%4$db%3$*2$.*1$dc", "a{40:d}b{30:20.10d}c"},
{__LINE__, "a%04ldb", "a{10:04d}b"},
{__LINE__, "a%-#04lldb", "a{10:-#04d}b"},
{__LINE__, "a%1$*5$db", "a{10:-10d}b"},
{__LINE__, "a%1$.*5$db", "a{10:d}b"},
};
for (const Expectation &e : kExpect) {
absl::string_view fmt = e.fmt;
SCOPED_TRACE(e.line);
SCOPED_TRACE(e.fmt);
UntypedFormatSpecImpl format(fmt);
EXPECT_EQ(e.summary,
str_format_internal::Summarize(format, absl::MakeSpan(args)))
<< "line:" << e.line;
}
}
}
}
ABSL_NAMESPACE_END
} | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/bind.cc | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/bind_test.cc | 03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4 |
96eac068-aee0-4173-954e-e2d2797caf66 | cpp | google/tensorstore | single_producer_queue | tensorstore/internal/container/single_producer_queue.h | tensorstore/internal/container/single_producer_queue_test.cc | #ifndef TENSORSTORE_INTERNAL_THREAD_SINGLE_PRODUCER_QUEUE_H_
#define TENSORSTORE_INTERNAL_THREAD_SINGLE_PRODUCER_QUEUE_H_
#include <stdint.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <memory>
#include <optional>
#include <type_traits>
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/log/absl_check.h"
namespace tensorstore {
namespace internal_container {
template <typename T, bool kCanResize = true,
typename Allocator = std::allocator<T>>
class SingleProducerQueue;
template <typename T, typename Allocator>
class SPQArray {
private:
static_assert(std::is_trivially_destructible_v<T>);
using ArrayAllocator = typename std::allocator_traits<
Allocator>::template rebind_alloc<SPQArray>;
using ByteAllocator =
typename std::allocator_traits<Allocator>::template rebind_alloc<char>;
constexpr static ptrdiff_t start_offset() {
struct X {
SPQArray array;
std::atomic<T> item[1];
};
return offsetof(X, item);
}
constexpr static size_t alloc_size(int64_t c) {
struct X {
SPQArray array;
std::atomic<T> item[1];
};
return sizeof(X) + (c - 1) * sizeof(std::atomic<T>);
}
struct private_t {
private:
friend class SPQArray;
private_t() = default;
};
public:
static SPQArray* New(int64_t c, SPQArray* retired, Allocator* alloc) {
size_t allocation_bytes = alloc_size(c);
ByteAllocator byte_alloc(*alloc);
void* mem = std::allocator_traits<ByteAllocator>::allocate(
byte_alloc, allocation_bytes);
auto* as_array = static_cast<SPQArray*>(mem);
ArrayAllocator array_alloc(*alloc);
std::allocator_traits<ArrayAllocator>::construct(array_alloc, as_array,
private_t{}, c, retired);
return as_array;
}
static void Delete(SPQArray* ptr, Allocator* alloc) {
const size_t allocation_bytes = alloc_size(ptr->capacity);
void* mem = ptr;
ByteAllocator byte_alloc(*alloc);
std::allocator_traits<ByteAllocator>::deallocate(
byte_alloc, static_cast<char*>(mem), allocation_bytes);
}
SPQArray(private_t, int64_t c, SPQArray* retired)
: capacity(c), mask(c - 1), retired(retired) {}
SPQArray* resize(int64_t b, int64_t t, Allocator* alloc) {
auto* a = SPQArray::New(2 * capacity, this, alloc);
for (int64_t i = t; i != b; ++i) {
a->item(i).store(
item(i).load(std::memory_order_relaxed), std::memory_order_relaxed);
}
return a;
}
std::atomic<T>* buffer() {
return reinterpret_cast<std::atomic<T>*>(reinterpret_cast<char*>(this) +
start_offset());
}
std::atomic<T>& item(int64_t i) { return buffer()[i & mask]; }
int64_t capacity;
int64_t mask;
SPQArray* retired;
};
template <typename T, bool kCanResize, typename Allocator>
class SingleProducerQueue {
static_assert(std::is_trivially_destructible_v<T>);
std::nullopt_t missing(std::false_type) { return std::nullopt; }
std::nullptr_t missing(std::true_type) { return nullptr; }
using Array = SPQArray<T, Allocator>;
public:
using optional_t =
std::conditional_t<std::is_pointer_v<T>, T, std::optional<T>>;
SingleProducerQueue(int64_t n, Allocator alloc)
: top_(0),
bottom_(0),
allocator_(alloc),
array_(Array::New(n, nullptr, &allocator_)) {
ABSL_CHECK_EQ(n & (n - 1), 0);
}
explicit SingleProducerQueue(int64_t n)
: SingleProducerQueue(n, Allocator()) {}
~SingleProducerQueue() {
Array* a = array_.load(std::memory_order_relaxed);
while (a) {
Array* b = a->retired;
a->retired = nullptr;
Array::Delete(a, &allocator_);
a = b;
}
}
int64_t capacity() const {
return array_.load(std::memory_order_relaxed)->capacity;
}
size_t size() const {
int64_t b = bottom_.load(std::memory_order_relaxed);
int64_t t = top_.load(std::memory_order_relaxed);
return static_cast<size_t>(b > t ? b - t : 0);
}
bool empty() const { return !size(); }
bool push(T x) {
auto b = bottom_.load(std::memory_order_relaxed);
auto t = top_.load(std::memory_order_acquire);
Array* a = array_.load(std::memory_order_relaxed);
if (a->capacity < (b - t) + 1) {
if (!kCanResize) return false;
a = a->resize(b, t, &allocator_);
array_.store(a, std::memory_order_release);
}
a->item(b).store(std::move(x), std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
bottom_.store(b + 1, std::memory_order_relaxed);
return true;
}
optional_t try_pop() {
auto b = bottom_.load(std::memory_order_relaxed) - 1;
Array* a = array_.load(std::memory_order_relaxed);
bottom_.store(b, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_seq_cst);
auto t = top_.load(std::memory_order_relaxed);
if (t > b) {
bottom_.store(b + 1, std::memory_order_relaxed);
return missing(std::is_pointer<T>{});
}
if (t == b) {
if (!top_.compare_exchange_strong(t, t + 1, std::memory_order_seq_cst,
std::memory_order_relaxed)) {
bottom_.store(b + 1, std::memory_order_relaxed);
return missing(std::is_pointer<T>{});
}
bottom_.store(b + 1, std::memory_order_relaxed);
}
return a->item(b).load(std::memory_order_relaxed);
}
optional_t try_steal() {
auto t = top_.load(std::memory_order_acquire);
std::atomic_thread_fence(std::memory_order_seq_cst);
auto b = bottom_.load(std::memory_order_acquire);
if (t >= b) {
return missing(std::is_pointer<T>{});
}
Array* a = array_.load(std::memory_order_consume);
T x = a->item(t).load(std::memory_order_relaxed);
if (!top_.compare_exchange_strong(t, t + 1, std::memory_order_seq_cst,
std::memory_order_relaxed)) {
return missing(std::is_pointer<T>{});
}
return x;
}
private:
ABSL_CACHELINE_ALIGNED std::atomic<int64_t> top_;
std::atomic<int64_t> bottom_;
ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS Allocator allocator_;
std::atomic<Array*> array_;
};
}
}
#endif | #include "tensorstore/internal/container/single_producer_queue.h"
#include <stddef.h>
#include <atomic>
#include <optional>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/log/absl_check.h"
#include "tensorstore/internal/thread/thread.h"
using ::tensorstore::internal_container::SingleProducerQueue;
using ::testing::Eq;
using ::testing::Optional;
namespace {
TEST(SingleProducerQueueTest, Basic) {
SingleProducerQueue<int> q(32);
EXPECT_THAT(q.capacity(), Eq(32));
EXPECT_THAT(q.empty(), true);
EXPECT_THAT(q.size(), Eq(0));
q.push(1);
EXPECT_THAT(q.capacity(), Eq(32));
EXPECT_THAT(q.empty(), false);
EXPECT_THAT(q.size(), Eq(1));
EXPECT_THAT(q.try_pop(), Optional(1));
EXPECT_THAT(q.try_pop(), Eq(std::nullopt));
q.push(2);
EXPECT_THAT(q.try_steal(), Optional(2));
EXPECT_THAT(q.try_pop(), Eq(std::nullopt));
}
TEST(SingleProducerQueueTest, BasicPtr) {
SingleProducerQueue<int*> q(32);
int a[2];
EXPECT_THAT(q.capacity(), Eq(32));
EXPECT_THAT(q.empty(), true);
EXPECT_THAT(q.size(), Eq(0));
q.push(&a[0]);
EXPECT_THAT(q.capacity(), Eq(32));
EXPECT_THAT(q.empty(), false);
EXPECT_THAT(q.size(), Eq(1));
EXPECT_THAT(q.try_pop(), Eq(a));
EXPECT_THAT(q.try_pop(), Eq(nullptr));
q.push(&a[1]);
EXPECT_THAT(q.try_steal(), Eq(a + 1));
EXPECT_THAT(q.try_pop(), Eq(nullptr));
}
TEST(SimpleQueue, PushPop) {
SingleProducerQueue<int, false> q(1);
for (int i = 0; i < 4096; i++) {
if (!q.push(i)) {
q.try_pop();
q.push(i);
if (i & 0x2) q.try_pop();
}
}
}
TEST(SingleProducerQueueTest, ConcurrentSteal) {
static constexpr size_t kNumThreads = 4;
static constexpr int kSize = 10000;
SingleProducerQueue<int> q(32);
std::atomic<int> remaining(kSize);
std::vector<tensorstore::internal::Thread> threads;
threads.reserve(kNumThreads + 1);
for (size_t thread_i = 0; thread_i < kNumThreads; ++thread_i) {
bool c = thread_i & 1;
threads.emplace_back(
tensorstore::internal::Thread({"steal"}, [c, &remaining, &q]() {
while (remaining.load(std::memory_order_seq_cst) > 0) {
if (auto v = q.try_steal(); v.has_value()) {
ABSL_CHECK_EQ(*v, 1);
remaining.fetch_sub(1);
}
if (c) {
q.capacity();
} else {
q.size();
}
}
}));
}
threads.emplace_back(tensorstore::internal::Thread({"create"}, [&q]() {
for (int i = 0; i < kSize; ++i) q.push(1);
}));
for (auto& t : threads) t.Join();
EXPECT_THAT(remaining.load(std::memory_order_seq_cst), 0);
EXPECT_THAT(q.try_steal(), Eq(std::nullopt));
}
} | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/internal/container/single_producer_queue.h | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/internal/container/single_producer_queue_test.cc | 4f887a6430414cd6088e1743555015b10f116d50 |
b8debb4c-34f9-42e0-8dc5-dcfb180414bb | cpp | tensorflow/tensorflow | flatset | tensorflow/core/lib/gtl/flatset.h | third_party/xla/xla/tsl/lib/gtl/flatset_test.cc | #ifndef TENSORFLOW_CORE_LIB_GTL_FLATSET_H_
#define TENSORFLOW_CORE_LIB_GTL_FLATSET_H_
#include "xla/tsl/lib/gtl/flatset.h"
namespace tensorflow {
namespace gtl {
using tsl::gtl::FlatSet;
}
}
#endif | #include "xla/tsl/lib/gtl/flatset.h"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "tsl/platform/hash.h"
#include "tsl/platform/test.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace gtl {
namespace {
typedef FlatSet<int64_t> NumSet;
bool Has(const NumSet& set, int64_t k) {
auto iter = set.find(k);
if (iter == set.end()) {
EXPECT_EQ(set.count(k), 0);
return false;
} else {
EXPECT_EQ(set.count(k), 1);
EXPECT_EQ(*iter, k);
return true;
}
}
typedef std::vector<int64_t> NumSetContents;
NumSetContents Contents(const NumSet& set) {
NumSetContents result(set.begin(), set.end());
std::sort(result.begin(), result.end());
return result;
}
void Fill(NumSet* set, int64_t start, int64_t limit) {
for (int64_t i = start; i < limit; i++) {
set->insert(i);
}
}
TEST(FlatSetTest, Find) {
NumSet set;
EXPECT_FALSE(Has(set, 1));
set.insert(1);
set.insert(2);
EXPECT_TRUE(Has(set, 1));
EXPECT_TRUE(Has(set, 2));
EXPECT_FALSE(Has(set, 3));
}
TEST(FlatSetTest, Insert) {
NumSet set;
EXPECT_FALSE(Has(set, 1));
auto result = set.insert(1);
EXPECT_TRUE(result.second);
EXPECT_EQ(*result.first, 1);
EXPECT_TRUE(Has(set, 1));
result = set.insert(1);
EXPECT_FALSE(result.second);
EXPECT_EQ(*result.first, 1);
EXPECT_TRUE(Has(set, 1));
}
TEST(FlatSetTest, InsertGrowth) {
NumSet set;
const int n = 100;
Fill(&set, 0, 100);
EXPECT_EQ(set.size(), n);
for (int i = 0; i < n; i++) {
EXPECT_TRUE(Has(set, i)) << i;
}
}
TEST(FlatSetTest, Emplace) {
NumSet set;
auto result = set.emplace(73);
EXPECT_TRUE(result.second);
EXPECT_EQ(*result.first, 73);
EXPECT_TRUE(Has(set, 73));
result = set.emplace(73);
EXPECT_FALSE(result.second);
EXPECT_EQ(*result.first, 73);
EXPECT_TRUE(Has(set, 73));
result = set.emplace(103);
EXPECT_TRUE(result.second);
EXPECT_EQ(*result.first, 103);
EXPECT_TRUE(Has(set, 103));
}
TEST(FlatSetTest, Size) {
NumSet set;
EXPECT_EQ(set.size(), 0);
set.insert(1);
set.insert(2);
EXPECT_EQ(set.size(), 2);
}
TEST(FlatSetTest, Empty) {
NumSet set;
EXPECT_TRUE(set.empty());
set.insert(1);
set.insert(2);
EXPECT_FALSE(set.empty());
}
TEST(FlatSetTest, Count) {
NumSet set;
EXPECT_EQ(set.count(1), 0);
EXPECT_EQ(set.count(2), 0);
set.insert(1);
EXPECT_EQ(set.count(1), 1);
EXPECT_EQ(set.count(2), 0);
set.insert(2);
EXPECT_EQ(set.count(1), 1);
EXPECT_EQ(set.count(2), 1);
}
TEST(FlatSetTest, Iter) {
NumSet set;
EXPECT_EQ(Contents(set), NumSetContents());
set.insert(1);
set.insert(2);
EXPECT_EQ(Contents(set), NumSetContents({1, 2}));
}
TEST(FlatSetTest, Erase) {
NumSet set;
EXPECT_EQ(set.erase(1), 0);
set.insert(1);
set.insert(2);
EXPECT_EQ(set.erase(3), 0);
EXPECT_EQ(set.erase(1), 1);
EXPECT_EQ(set.size(), 1);
EXPECT_TRUE(Has(set, 2));
EXPECT_EQ(Contents(set), NumSetContents({2}));
EXPECT_EQ(set.erase(2), 1);
EXPECT_EQ(Contents(set), NumSetContents());
}
TEST(FlatSetTest, EraseIter) {
NumSet set;
Fill(&set, 1, 11);
size_t size = 10;
for (auto iter = set.begin(); iter != set.end();) {
iter = set.erase(iter);
size--;
EXPECT_EQ(set.size(), size);
}
EXPECT_EQ(Contents(set), NumSetContents());
}
TEST(FlatSetTest, EraseIterPair) {
NumSet set;
Fill(&set, 1, 11);
NumSet expected;
auto p1 = set.begin();
expected.insert(*p1);
++p1;
expected.insert(*p1);
++p1;
auto p2 = set.end();
EXPECT_EQ(set.erase(p1, p2), set.end());
EXPECT_EQ(set.size(), 2);
EXPECT_EQ(Contents(set), Contents(expected));
}
TEST(FlatSetTest, EraseLongChains) {
NumSet set;
const int num = 128;
Fill(&set, 0, num);
for (int i = 0; i < num; i += 3) {
EXPECT_EQ(set.erase(i), 1);
}
for (int i = 0; i < num; i++) {
EXPECT_EQ(Has(set, i), ((i % 3) != 0)) << i;
}
const size_t orig_buckets = set.bucket_count();
for (int i = 0; i < num; i++) {
set.erase(i);
}
EXPECT_TRUE(set.empty());
EXPECT_EQ(set.bucket_count(), orig_buckets);
set.insert(1);
EXPECT_LT(set.bucket_count(), orig_buckets);
}
TEST(FlatSet, ClearNoResize) {
NumSet set;
Fill(&set, 0, 100);
const size_t orig = set.bucket_count();
set.clear_no_resize();
EXPECT_EQ(set.size(), 0);
EXPECT_EQ(Contents(set), NumSetContents());
EXPECT_EQ(set.bucket_count(), orig);
}
TEST(FlatSet, Clear) {
NumSet set;
Fill(&set, 0, 100);
const size_t orig = set.bucket_count();
set.clear();
EXPECT_EQ(set.size(), 0);
EXPECT_EQ(Contents(set), NumSetContents());
EXPECT_LT(set.bucket_count(), orig);
}
TEST(FlatSet, Copy) {
for (int n = 0; n < 10; n++) {
NumSet src;
Fill(&src, 0, n);
NumSet copy = src;
EXPECT_EQ(Contents(src), Contents(copy));
NumSet copy2;
copy2 = src;
EXPECT_EQ(Contents(src), Contents(copy2));
copy2 = *©2;
EXPECT_EQ(Contents(src), Contents(copy2));
}
}
TEST(FlatSet, InitFromIter) {
for (int n = 0; n < 10; n++) {
NumSet src;
Fill(&src, 0, n);
auto vec = Contents(src);
NumSet dst(vec.begin(), vec.end());
EXPECT_EQ(Contents(dst), vec);
}
}
TEST(FlatSet, InitializerList) {
NumSet a{1, 2, 3};
NumSet b({1, 2, 3});
NumSet c = {1, 2, 3};
for (NumSet* set : std::vector<NumSet*>({&a, &b, &c})) {
EXPECT_TRUE(Has(*set, 1));
EXPECT_TRUE(Has(*set, 2));
EXPECT_TRUE(Has(*set, 3));
EXPECT_EQ(Contents(*set), NumSetContents({1, 2, 3}));
}
}
TEST(FlatSet, InsertIter) {
NumSet a, b;
Fill(&a, 1, 10);
Fill(&b, 8, 20);
b.insert(9);
a.insert(b.begin(), b.end());
NumSet expected;
Fill(&expected, 1, 20);
EXPECT_EQ(Contents(a), Contents(expected));
}
TEST(FlatSet, Eq) {
NumSet empty;
NumSet elems;
Fill(&elems, 0, 5);
EXPECT_FALSE(empty == elems);
EXPECT_TRUE(empty != elems);
NumSet copy = elems;
EXPECT_TRUE(copy == elems);
EXPECT_FALSE(copy != elems);
NumSet changed = elems;
changed.insert(7);
EXPECT_FALSE(changed == elems);
EXPECT_TRUE(changed != elems);
NumSet changed2 = elems;
changed2.erase(3);
EXPECT_FALSE(changed2 == elems);
EXPECT_TRUE(changed2 != elems);
}
TEST(FlatSet, Swap) {
NumSet a, b;
Fill(&a, 1, 5);
Fill(&b, 100, 200);
NumSet c = a;
NumSet d = b;
EXPECT_EQ(c, a);
EXPECT_EQ(d, b);
c.swap(d);
EXPECT_EQ(c, b);
EXPECT_EQ(d, a);
}
TEST(FlatSet, Reserve) {
NumSet src;
Fill(&src, 1, 100);
NumSet a = src;
a.reserve(10);
EXPECT_EQ(a, src);
NumSet b = src;
b.rehash(1000);
EXPECT_EQ(b, src);
}
TEST(FlatSet, EqualRangeMutable) {
NumSet set;
Fill(&set, 1, 10);
auto p1 = set.equal_range(3);
EXPECT_TRUE(p1.first != p1.second);
EXPECT_EQ(*p1.first, 3);
++p1.first;
EXPECT_TRUE(p1.first == p1.second);
auto p2 = set.equal_range(100);
EXPECT_TRUE(p2.first == p2.second);
}
TEST(FlatSet, EqualRangeConst) {
NumSet tmp;
Fill(&tmp, 1, 10);
const NumSet set = tmp;
auto p1 = set.equal_range(3);
EXPECT_TRUE(p1.first != p1.second);
EXPECT_EQ(*p1.first, 3);
++p1.first;
EXPECT_TRUE(p1.first == p1.second);
auto p2 = set.equal_range(100);
EXPECT_TRUE(p2.first == p2.second);
}
TEST(FlatSet, Prefetch) {
NumSet set;
Fill(&set, 0, 1000);
for (int i = 0; i < 2000; i++) {
set.prefetch_value(i);
}
}
struct NA {
int64_t value;
NA() : value(-1) {}
explicit NA(int64_t v) : value(v) {}
NA(const NA& x) : value(x.value) {}
bool operator==(const NA& x) const { return value == x.value; }
};
struct HashNA {
size_t operator()(NA x) const { return x.value; }
};
TEST(FlatSet, NonAssignable) {
FlatSet<NA, HashNA> set;
for (int i = 0; i < 100; i++) {
set.insert(NA(i));
}
for (int i = 0; i < 100; i++) {
EXPECT_EQ(set.count(NA(i)), 1);
auto iter = set.find(NA(i));
EXPECT_NE(iter, set.end());
EXPECT_EQ(*iter, NA(i));
}
set.erase(NA(10));
EXPECT_EQ(set.count(NA(10)), 0);
}
TEST(FlatSet, ForwardIterator) {
typedef FlatSet<NA, HashNA> NASet;
NASet set({NA(1), NA(2)});
NASet::iterator it1 = set.find(NA(1));
NASet::iterator it2 = set.find(NA(2));
EXPECT_TRUE(it1 != set.end());
EXPECT_TRUE(it2 != set.end());
EXPECT_FALSE(it1 == set.end());
EXPECT_FALSE(it2 == set.end());
EXPECT_TRUE(it1 != it2);
EXPECT_FALSE(it1 == it2);
EXPECT_EQ(*it1, NA(1));
EXPECT_EQ(*it2, NA(2));
EXPECT_EQ(it1->value, 1);
EXPECT_EQ(it2->value, 2);
NASet::iterator copy_it1 = it1;
NASet::iterator copy_it2 = it2;
EXPECT_EQ(*copy_it1, NA(1));
EXPECT_EQ(*copy_it2, NA(2));
NASet::iterator& pp_copy_it1 = ++copy_it1;
NASet::iterator& pp_copy_it2 = ++copy_it2;
EXPECT_TRUE(pp_copy_it1 == copy_it1);
EXPECT_TRUE(pp_copy_it2 == copy_it2);
EXPECT_TRUE(copy_it1 != it1);
EXPECT_TRUE(copy_it2 != it2);
if (copy_it1 == set.end()) {
EXPECT_TRUE(copy_it2 != set.end());
EXPECT_EQ(*copy_it2, NA(1));
EXPECT_EQ(*pp_copy_it2, NA(1));
} else {
EXPECT_TRUE(copy_it2 == set.end());
EXPECT_EQ(*copy_it1, NA(2));
EXPECT_EQ(*pp_copy_it1, NA(2));
}
EXPECT_EQ(*it1, NA(1));
EXPECT_EQ(*it2, NA(2));
copy_it1 = it1;
copy_it2 = it2;
EXPECT_EQ(*copy_it1, NA(1));
EXPECT_EQ(*copy_it2, NA(2));
NASet::iterator copy_it1_pp = copy_it1++;
NASet::iterator copy_it2_pp = copy_it2++;
EXPECT_TRUE(copy_it1_pp != copy_it1);
EXPECT_TRUE(copy_it2_pp != copy_it2);
EXPECT_TRUE(copy_it1_pp == it1);
EXPECT_TRUE(copy_it2_pp == it2);
EXPECT_EQ(*copy_it1_pp, NA(1));
EXPECT_EQ(*copy_it2_pp, NA(2));
EXPECT_TRUE(copy_it1 != it1);
EXPECT_TRUE(copy_it2 != it2);
if (copy_it1 == set.end()) {
EXPECT_TRUE(copy_it2 != set.end());
EXPECT_EQ(*copy_it2, NA(1));
} else {
EXPECT_TRUE(copy_it2 == set.end());
EXPECT_EQ(*copy_it1, NA(2));
}
EXPECT_EQ(*it1, NA(1));
EXPECT_EQ(*it2, NA(2));
}
TEST(FlatSet, ConstructDestruct) {
FlatSet<string> set;
string k1 = "the quick brown fox jumped over the lazy dog";
string k2 = k1 + k1;
string k3 = k1 + k2;
set.insert(k1);
set.insert(k3);
EXPECT_EQ(set.count(k1), 1);
EXPECT_EQ(set.count(k2), 0);
EXPECT_EQ(set.count(k3), 1);
set.erase(k3);
EXPECT_EQ(set.count(k3), 0);
set.clear();
set.insert(k1);
EXPECT_EQ(set.count(k1), 1);
EXPECT_EQ(set.count(k3), 0);
set.reserve(100);
EXPECT_EQ(set.count(k1), 1);
EXPECT_EQ(set.count(k3), 0);
}
struct CustomCmpKey {
int64_t a;
int64_t b;
CustomCmpKey(int64_t v1, int64_t v2) : a(v1), b(v2) {}
bool operator==(const CustomCmpKey& x) const { return a == x.a && b == x.b; }
};
struct HashA {
size_t operator()(CustomCmpKey x) const { return x.a; }
};
struct EqA {
bool operator()(CustomCmpKey x, CustomCmpKey y) const { return x.a == y.a; }
};
TEST(FlatSet, CustomCmp) {
FlatSet<CustomCmpKey, HashA, EqA> set;
set.insert(CustomCmpKey(100, 200));
EXPECT_EQ(set.count(CustomCmpKey(100, 200)), 1);
EXPECT_EQ(set.count(CustomCmpKey(100, 500)), 1);
}
typedef std::unique_ptr<int> UniqInt;
static UniqInt MakeUniq(int i) { return std::make_unique<int>(i); }
struct HashUniq {
size_t operator()(const UniqInt& p) const { return *p; }
};
struct EqUniq {
bool operator()(const UniqInt& a, const UniqInt& b) const { return *a == *b; }
};
typedef FlatSet<UniqInt, HashUniq, EqUniq> UniqSet;
TEST(FlatSet, UniqueSet) {
UniqSet set;
const int N = 10;
for (int i = 0; i < N; i++) {
set.emplace(MakeUniq(i));
}
EXPECT_EQ(set.size(), N);
UniqSet set2(std::move(set));
for (int i = 0; i < N; i++) {
EXPECT_EQ(set2.count(MakeUniq(i)), 1);
}
UniqSet set3;
set3 = std::move(set2);
set3.erase(MakeUniq(2));
EXPECT_EQ(set3.count(MakeUniq(2)), 0);
set.clear();
EXPECT_EQ(set.size(), 0);
EXPECT_GE(set.size(), 0);
EXPECT_GE(set2.size(), 0);
EXPECT_TRUE(set.emplace(MakeUniq(-1)).second);
}
TEST(FlatSet, UniqueSetIter) {
UniqSet set;
const int kCount = 10;
for (int i = 1; i <= kCount; i++) {
set.emplace(MakeUniq(i));
}
int sum = 0;
for (const auto& p : set) {
sum += *p;
}
EXPECT_EQ(sum, (kCount * (kCount + 1)) / 2);
}
TEST(FlatSet, InsertUncopyable) {
UniqSet set;
EXPECT_TRUE(set.insert(MakeUniq(0)).second);
EXPECT_EQ(set.size(), 1);
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/lib/gtl/flatset.h | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tsl/lib/gtl/flatset_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
8086529a-480b-40f5-ae84-ebac1bbb68bd | cpp | abseil/abseil-cpp | status | absl/status/status.cc | absl/status/status_test.cc | #include "absl/status/status.h"
#include <errno.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <ostream>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/strerror.h"
#include "absl/base/macros.h"
#include "absl/base/no_destructor.h"
#include "absl/base/nullability.h"
#include "absl/debugging/stacktrace.h"
#include "absl/debugging/symbolize.h"
#include "absl/status/internal/status_internal.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
static_assert(
alignof(status_internal::StatusRep) >= 4,
"absl::Status assumes it can use the bottom 2 bits of a StatusRep*.");
std::string StatusCodeToString(StatusCode code) {
switch (code) {
case StatusCode::kOk:
return "OK";
case StatusCode::kCancelled:
return "CANCELLED";
case StatusCode::kUnknown:
return "UNKNOWN";
case StatusCode::kInvalidArgument:
return "INVALID_ARGUMENT";
case StatusCode::kDeadlineExceeded:
return "DEADLINE_EXCEEDED";
case StatusCode::kNotFound:
return "NOT_FOUND";
case StatusCode::kAlreadyExists:
return "ALREADY_EXISTS";
case StatusCode::kPermissionDenied:
return "PERMISSION_DENIED";
case StatusCode::kUnauthenticated:
return "UNAUTHENTICATED";
case StatusCode::kResourceExhausted:
return "RESOURCE_EXHAUSTED";
case StatusCode::kFailedPrecondition:
return "FAILED_PRECONDITION";
case StatusCode::kAborted:
return "ABORTED";
case StatusCode::kOutOfRange:
return "OUT_OF_RANGE";
case StatusCode::kUnimplemented:
return "UNIMPLEMENTED";
case StatusCode::kInternal:
return "INTERNAL";
case StatusCode::kUnavailable:
return "UNAVAILABLE";
case StatusCode::kDataLoss:
return "DATA_LOSS";
default:
return "";
}
}
std::ostream& operator<<(std::ostream& os, StatusCode code) {
return os << StatusCodeToString(code);
}
absl::Nonnull<const std::string*> Status::EmptyString() {
static const absl::NoDestructor<std::string> kEmpty;
return kEmpty.get();
}
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr const char Status::kMovedFromString[];
#endif
absl::Nonnull<const std::string*> Status::MovedFromString() {
static const absl::NoDestructor<std::string> kMovedFrom(kMovedFromString);
return kMovedFrom.get();
}
Status::Status(absl::StatusCode code, absl::string_view msg)
: rep_(CodeToInlinedRep(code)) {
if (code != absl::StatusCode::kOk && !msg.empty()) {
rep_ = PointerToRep(new status_internal::StatusRep(code, msg, nullptr));
}
}
absl::Nonnull<status_internal::StatusRep*> Status::PrepareToModify(
uintptr_t rep) {
if (IsInlined(rep)) {
return new status_internal::StatusRep(InlinedRepToCode(rep),
absl::string_view(), nullptr);
}
return RepToPointer(rep)->CloneAndUnref();
}
std::string Status::ToStringSlow(uintptr_t rep, StatusToStringMode mode) {
if (IsInlined(rep)) {
return absl::StrCat(absl::StatusCodeToString(InlinedRepToCode(rep)), ": ");
}
return RepToPointer(rep)->ToString(mode);
}
std::ostream& operator<<(std::ostream& os, const Status& x) {
os << x.ToString(StatusToStringMode::kWithEverything);
return os;
}
Status AbortedError(absl::string_view message) {
return Status(absl::StatusCode::kAborted, message);
}
Status AlreadyExistsError(absl::string_view message) {
return Status(absl::StatusCode::kAlreadyExists, message);
}
Status CancelledError(absl::string_view message) {
return Status(absl::StatusCode::kCancelled, message);
}
Status DataLossError(absl::string_view message) {
return Status(absl::StatusCode::kDataLoss, message);
}
Status DeadlineExceededError(absl::string_view message) {
return Status(absl::StatusCode::kDeadlineExceeded, message);
}
Status FailedPreconditionError(absl::string_view message) {
return Status(absl::StatusCode::kFailedPrecondition, message);
}
Status InternalError(absl::string_view message) {
return Status(absl::StatusCode::kInternal, message);
}
Status InvalidArgumentError(absl::string_view message) {
return Status(absl::StatusCode::kInvalidArgument, message);
}
Status NotFoundError(absl::string_view message) {
return Status(absl::StatusCode::kNotFound, message);
}
Status OutOfRangeError(absl::string_view message) {
return Status(absl::StatusCode::kOutOfRange, message);
}
Status PermissionDeniedError(absl::string_view message) {
return Status(absl::StatusCode::kPermissionDenied, message);
}
Status ResourceExhaustedError(absl::string_view message) {
return Status(absl::StatusCode::kResourceExhausted, message);
}
Status UnauthenticatedError(absl::string_view message) {
return Status(absl::StatusCode::kUnauthenticated, message);
}
Status UnavailableError(absl::string_view message) {
return Status(absl::StatusCode::kUnavailable, message);
}
Status UnimplementedError(absl::string_view message) {
return Status(absl::StatusCode::kUnimplemented, message);
}
Status UnknownError(absl::string_view message) {
return Status(absl::StatusCode::kUnknown, message);
}
bool IsAborted(const Status& status) {
return status.code() == absl::StatusCode::kAborted;
}
bool IsAlreadyExists(const Status& status) {
return status.code() == absl::StatusCode::kAlreadyExists;
}
bool IsCancelled(const Status& status) {
return status.code() == absl::StatusCode::kCancelled;
}
bool IsDataLoss(const Status& status) {
return status.code() == absl::StatusCode::kDataLoss;
}
bool IsDeadlineExceeded(const Status& status) {
return status.code() == absl::StatusCode::kDeadlineExceeded;
}
bool IsFailedPrecondition(const Status& status) {
return status.code() == absl::StatusCode::kFailedPrecondition;
}
bool IsInternal(const Status& status) {
return status.code() == absl::StatusCode::kInternal;
}
bool IsInvalidArgument(const Status& status) {
return status.code() == absl::StatusCode::kInvalidArgument;
}
bool IsNotFound(const Status& status) {
return status.code() == absl::StatusCode::kNotFound;
}
bool IsOutOfRange(const Status& status) {
return status.code() == absl::StatusCode::kOutOfRange;
}
bool IsPermissionDenied(const Status& status) {
return status.code() == absl::StatusCode::kPermissionDenied;
}
bool IsResourceExhausted(const Status& status) {
return status.code() == absl::StatusCode::kResourceExhausted;
}
bool IsUnauthenticated(const Status& status) {
return status.code() == absl::StatusCode::kUnauthenticated;
}
bool IsUnavailable(const Status& status) {
return status.code() == absl::StatusCode::kUnavailable;
}
bool IsUnimplemented(const Status& status) {
return status.code() == absl::StatusCode::kUnimplemented;
}
bool IsUnknown(const Status& status) {
return status.code() == absl::StatusCode::kUnknown;
}
StatusCode ErrnoToStatusCode(int error_number) {
switch (error_number) {
case 0:
return StatusCode::kOk;
case EINVAL:
case ENAMETOOLONG:
case E2BIG:
case EDESTADDRREQ:
case EDOM:
case EFAULT:
case EILSEQ:
case ENOPROTOOPT:
case ENOTSOCK:
case ENOTTY:
case EPROTOTYPE:
case ESPIPE:
return StatusCode::kInvalidArgument;
case ETIMEDOUT:
return StatusCode::kDeadlineExceeded;
case ENODEV:
case ENOENT:
#ifdef ENOMEDIUM
case ENOMEDIUM:
#endif
case ENXIO:
case ESRCH:
return StatusCode::kNotFound;
case EEXIST:
case EADDRNOTAVAIL:
case EALREADY:
#ifdef ENOTUNIQ
case ENOTUNIQ:
#endif
return StatusCode::kAlreadyExists;
case EPERM:
case EACCES:
#ifdef ENOKEY
case ENOKEY:
#endif
case EROFS:
return StatusCode::kPermissionDenied;
case ENOTEMPTY:
case EISDIR:
case ENOTDIR:
case EADDRINUSE:
case EBADF:
#ifdef EBADFD
case EBADFD:
#endif
case EBUSY:
case ECHILD:
case EISCONN:
#ifdef EISNAM
case EISNAM:
#endif
#ifdef ENOTBLK
case ENOTBLK:
#endif
case ENOTCONN:
case EPIPE:
#ifdef ESHUTDOWN
case ESHUTDOWN:
#endif
case ETXTBSY:
#ifdef EUNATCH
case EUNATCH:
#endif
return StatusCode::kFailedPrecondition;
case ENOSPC:
#ifdef EDQUOT
case EDQUOT:
#endif
case EMFILE:
case EMLINK:
case ENFILE:
case ENOBUFS:
case ENOMEM:
#ifdef EUSERS
case EUSERS:
#endif
return StatusCode::kResourceExhausted;
#ifdef ECHRNG
case ECHRNG:
#endif
case EFBIG:
case EOVERFLOW:
case ERANGE:
return StatusCode::kOutOfRange;
#ifdef ENOPKG
case ENOPKG:
#endif
case ENOSYS:
case ENOTSUP:
case EAFNOSUPPORT:
#ifdef EPFNOSUPPORT
case EPFNOSUPPORT:
#endif
case EPROTONOSUPPORT:
#ifdef ESOCKTNOSUPPORT
case ESOCKTNOSUPPORT:
#endif
case EXDEV:
return StatusCode::kUnimplemented;
case EAGAIN:
#ifdef ECOMM
case ECOMM:
#endif
case ECONNREFUSED:
case ECONNABORTED:
case ECONNRESET:
case EINTR:
#ifdef EHOSTDOWN
case EHOSTDOWN:
#endif
case EHOSTUNREACH:
case ENETDOWN:
case ENETRESET:
case ENETUNREACH:
case ENOLCK:
case ENOLINK:
#ifdef ENONET
case ENONET:
#endif
return StatusCode::kUnavailable;
case EDEADLK:
#ifdef ESTALE
case ESTALE:
#endif
return StatusCode::kAborted;
case ECANCELED:
return StatusCode::kCancelled;
default:
return StatusCode::kUnknown;
}
}
namespace {
std::string MessageForErrnoToStatus(int error_number,
absl::string_view message) {
return absl::StrCat(message, ": ",
absl::base_internal::StrError(error_number));
}
}
Status ErrnoToStatus(int error_number, absl::string_view message) {
return Status(ErrnoToStatusCode(error_number),
MessageForErrnoToStatus(error_number, message));
}
absl::Nonnull<const char*> StatusMessageAsCStr(const Status& status) {
auto sv_message = status.message();
return sv_message.empty() ? "" : sv_message.data();
}
ABSL_NAMESPACE_END
} | #include "absl/status/status.h"
#include <errno.h>
#include <array>
#include <cstddef>
#include <sstream>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
namespace {
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Optional;
using ::testing::UnorderedElementsAreArray;
TEST(StatusCode, InsertionOperator) {
const absl::StatusCode code = absl::StatusCode::kUnknown;
std::ostringstream oss;
oss << code;
EXPECT_EQ(oss.str(), absl::StatusCodeToString(code));
}
struct ErrorTest {
absl::StatusCode code;
using Creator = absl::Status (*)(
absl::string_view
);
using Classifier = bool (*)(const absl::Status&);
Creator creator;
Classifier classifier;
};
constexpr ErrorTest kErrorTests[]{
{absl::StatusCode::kCancelled, absl::CancelledError, absl::IsCancelled},
{absl::StatusCode::kUnknown, absl::UnknownError, absl::IsUnknown},
{absl::StatusCode::kInvalidArgument, absl::InvalidArgumentError,
absl::IsInvalidArgument},
{absl::StatusCode::kDeadlineExceeded, absl::DeadlineExceededError,
absl::IsDeadlineExceeded},
{absl::StatusCode::kNotFound, absl::NotFoundError, absl::IsNotFound},
{absl::StatusCode::kAlreadyExists, absl::AlreadyExistsError,
absl::IsAlreadyExists},
{absl::StatusCode::kPermissionDenied, absl::PermissionDeniedError,
absl::IsPermissionDenied},
{absl::StatusCode::kResourceExhausted, absl::ResourceExhaustedError,
absl::IsResourceExhausted},
{absl::StatusCode::kFailedPrecondition, absl::FailedPreconditionError,
absl::IsFailedPrecondition},
{absl::StatusCode::kAborted, absl::AbortedError, absl::IsAborted},
{absl::StatusCode::kOutOfRange, absl::OutOfRangeError, absl::IsOutOfRange},
{absl::StatusCode::kUnimplemented, absl::UnimplementedError,
absl::IsUnimplemented},
{absl::StatusCode::kInternal, absl::InternalError, absl::IsInternal},
{absl::StatusCode::kUnavailable, absl::UnavailableError,
absl::IsUnavailable},
{absl::StatusCode::kDataLoss, absl::DataLossError, absl::IsDataLoss},
{absl::StatusCode::kUnauthenticated, absl::UnauthenticatedError,
absl::IsUnauthenticated},
};
TEST(Status, CreateAndClassify) {
for (const auto& test : kErrorTests) {
SCOPED_TRACE(absl::StatusCodeToString(test.code));
std::string message =
absl::StrCat("error code ", test.code, " test message");
absl::Status status = test.creator(
message
);
EXPECT_EQ(test.code, status.code());
EXPECT_EQ(message, status.message());
EXPECT_TRUE(test.classifier(status));
for (const auto& other : kErrorTests) {
if (other.code != test.code) {
EXPECT_FALSE(test.classifier(absl::Status(other.code, "")))
<< " other.code = " << other.code;
}
}
}
}
TEST(Status, DefaultConstructor) {
absl::Status status;
EXPECT_TRUE(status.ok());
EXPECT_EQ(absl::StatusCode::kOk, status.code());
EXPECT_EQ("", status.message());
}
TEST(Status, OkStatus) {
absl::Status status = absl::OkStatus();
EXPECT_TRUE(status.ok());
EXPECT_EQ(absl::StatusCode::kOk, status.code());
EXPECT_EQ("", status.message());
}
TEST(Status, ConstructorWithCodeMessage) {
{
absl::Status status(absl::StatusCode::kCancelled, "");
EXPECT_FALSE(status.ok());
EXPECT_EQ(absl::StatusCode::kCancelled, status.code());
EXPECT_EQ("", status.message());
}
{
absl::Status status(absl::StatusCode::kInternal, "message");
EXPECT_FALSE(status.ok());
EXPECT_EQ(absl::StatusCode::kInternal, status.code());
EXPECT_EQ("message", status.message());
}
}
TEST(Status, StatusMessageCStringTest) {
{
absl::Status status = absl::OkStatus();
EXPECT_EQ(status.message(), "");
EXPECT_STREQ(absl::StatusMessageAsCStr(status), "");
EXPECT_EQ(status.message(), absl::StatusMessageAsCStr(status));
EXPECT_NE(absl::StatusMessageAsCStr(status), nullptr);
}
{
absl::Status status;
EXPECT_EQ(status.message(), "");
EXPECT_NE(absl::StatusMessageAsCStr(status), nullptr);
EXPECT_STREQ(absl::StatusMessageAsCStr(status), "");
}
{
absl::Status status(absl::StatusCode::kInternal, "message");
EXPECT_FALSE(status.ok());
EXPECT_EQ(absl::StatusCode::kInternal, status.code());
EXPECT_EQ("message", status.message());
EXPECT_STREQ("message", absl::StatusMessageAsCStr(status));
}
}
TEST(Status, ConstructOutOfRangeCode) {
const int kRawCode = 9999;
absl::Status status(static_cast<absl::StatusCode>(kRawCode), "");
EXPECT_EQ(absl::StatusCode::kUnknown, status.code());
EXPECT_EQ(kRawCode, status.raw_code());
}
constexpr char kUrl1[] = "url.payload.1";
constexpr char kUrl2[] = "url.payload.2";
constexpr char kUrl3[] = "url.payload.3";
constexpr char kUrl4[] = "url.payload.xx";
constexpr char kPayload1[] = "aaaaa";
constexpr char kPayload2[] = "bbbbb";
constexpr char kPayload3[] = "ccccc";
using PayloadsVec = std::vector<std::pair<std::string, absl::Cord>>;
TEST(Status, TestGetSetPayload) {
absl::Status ok_status = absl::OkStatus();
ok_status.SetPayload(kUrl1, absl::Cord(kPayload1));
ok_status.SetPayload(kUrl2, absl::Cord(kPayload2));
EXPECT_FALSE(ok_status.GetPayload(kUrl1));
EXPECT_FALSE(ok_status.GetPayload(kUrl2));
absl::Status bad_status(absl::StatusCode::kInternal, "fail");
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status.SetPayload(kUrl2, absl::Cord(kPayload2));
EXPECT_THAT(bad_status.GetPayload(kUrl1), Optional(Eq(kPayload1)));
EXPECT_THAT(bad_status.GetPayload(kUrl2), Optional(Eq(kPayload2)));
EXPECT_FALSE(bad_status.GetPayload(kUrl3));
bad_status.SetPayload(kUrl1, absl::Cord(kPayload3));
EXPECT_THAT(bad_status.GetPayload(kUrl1), Optional(Eq(kPayload3)));
bad_status.SetPayload(absl::StrCat(kUrl1, ".1"), absl::Cord(kPayload1));
EXPECT_THAT(bad_status.GetPayload(absl::StrCat(kUrl1, ".1")),
Optional(Eq(kPayload1)));
}
TEST(Status, TestErasePayload) {
absl::Status bad_status(absl::StatusCode::kInternal, "fail");
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status.SetPayload(kUrl3, absl::Cord(kPayload3));
EXPECT_FALSE(bad_status.ErasePayload(kUrl4));
EXPECT_TRUE(bad_status.GetPayload(kUrl2));
EXPECT_TRUE(bad_status.ErasePayload(kUrl2));
EXPECT_FALSE(bad_status.GetPayload(kUrl2));
EXPECT_FALSE(bad_status.ErasePayload(kUrl2));
EXPECT_TRUE(bad_status.ErasePayload(kUrl1));
EXPECT_TRUE(bad_status.ErasePayload(kUrl3));
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_TRUE(bad_status.ErasePayload(kUrl1));
}
TEST(Status, TestComparePayloads) {
absl::Status bad_status1(absl::StatusCode::kInternal, "fail");
bad_status1.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status1.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status1.SetPayload(kUrl3, absl::Cord(kPayload3));
absl::Status bad_status2(absl::StatusCode::kInternal, "fail");
bad_status2.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status2.SetPayload(kUrl3, absl::Cord(kPayload3));
bad_status2.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_EQ(bad_status1, bad_status2);
}
TEST(Status, TestComparePayloadsAfterErase) {
absl::Status payload_status(absl::StatusCode::kInternal, "");
payload_status.SetPayload(kUrl1, absl::Cord(kPayload1));
payload_status.SetPayload(kUrl2, absl::Cord(kPayload2));
absl::Status empty_status(absl::StatusCode::kInternal, "");
EXPECT_NE(payload_status, empty_status);
EXPECT_TRUE(payload_status.ErasePayload(kUrl1));
EXPECT_NE(payload_status, empty_status);
EXPECT_TRUE(payload_status.ErasePayload(kUrl2));
EXPECT_EQ(payload_status, empty_status);
}
PayloadsVec AllVisitedPayloads(const absl::Status& s) {
PayloadsVec result;
s.ForEachPayload([&](absl::string_view type_url, const absl::Cord& payload) {
result.push_back(std::make_pair(std::string(type_url), payload));
});
return result;
}
TEST(Status, TestForEachPayload) {
absl::Status bad_status(absl::StatusCode::kInternal, "fail");
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status.SetPayload(kUrl3, absl::Cord(kPayload3));
int count = 0;
bad_status.ForEachPayload(
[&count](absl::string_view, const absl::Cord&) { ++count; });
EXPECT_EQ(count, 3);
PayloadsVec expected_payloads = {{kUrl1, absl::Cord(kPayload1)},
{kUrl2, absl::Cord(kPayload2)},
{kUrl3, absl::Cord(kPayload3)}};
PayloadsVec visited_payloads = AllVisitedPayloads(bad_status);
EXPECT_THAT(visited_payloads, UnorderedElementsAreArray(expected_payloads));
std::vector<absl::Status> scratch;
while (true) {
scratch.emplace_back(absl::StatusCode::kInternal, "fail");
scratch.back().SetPayload(kUrl1, absl::Cord(kPayload1));
scratch.back().SetPayload(kUrl2, absl::Cord(kPayload2));
scratch.back().SetPayload(kUrl3, absl::Cord(kPayload3));
if (AllVisitedPayloads(scratch.back()) != visited_payloads) {
break;
}
}
}
TEST(Status, ToString) {
absl::Status status(absl::StatusCode::kInternal, "fail");
EXPECT_EQ("INTERNAL: fail", status.ToString());
status.SetPayload("foo", absl::Cord("bar"));
EXPECT_EQ("INTERNAL: fail [foo='bar']", status.ToString());
status.SetPayload("bar", absl::Cord("\377"));
EXPECT_THAT(status.ToString(),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
}
TEST(Status, ToStringMode) {
absl::Status status(absl::StatusCode::kInternal, "fail");
status.SetPayload("foo", absl::Cord("bar"));
status.SetPayload("bar", absl::Cord("\377"));
EXPECT_EQ("INTERNAL: fail",
status.ToString(absl::StatusToStringMode::kWithNoExtraData));
EXPECT_THAT(status.ToString(absl::StatusToStringMode::kWithPayload),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
EXPECT_THAT(status.ToString(absl::StatusToStringMode::kWithEverything),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
EXPECT_THAT(status.ToString(~absl::StatusToStringMode::kWithPayload),
AllOf(HasSubstr("INTERNAL: fail"), Not(HasSubstr("[foo='bar']")),
Not(HasSubstr("[bar='\\xff']"))));
}
TEST(Status, OstreamOperator) {
absl::Status status(absl::StatusCode::kInternal, "fail");
{ std::stringstream stream;
stream << status;
EXPECT_EQ("INTERNAL: fail", stream.str());
}
status.SetPayload("foo", absl::Cord("bar"));
{ std::stringstream stream;
stream << status;
EXPECT_EQ("INTERNAL: fail [foo='bar']", stream.str());
}
status.SetPayload("bar", absl::Cord("\377"));
{ std::stringstream stream;
stream << status;
EXPECT_THAT(stream.str(),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
}
}
TEST(Status, AbslStringify) {
absl::Status status(absl::StatusCode::kInternal, "fail");
EXPECT_EQ("INTERNAL: fail", absl::StrCat(status));
EXPECT_EQ("INTERNAL: fail", absl::StrFormat("%v", status));
status.SetPayload("foo", absl::Cord("bar"));
EXPECT_EQ("INTERNAL: fail [foo='bar']", absl::StrCat(status));
status.SetPayload("bar", absl::Cord("\377"));
EXPECT_THAT(absl::StrCat(status),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
}
TEST(Status, OstreamEqStringify) {
absl::Status status(absl::StatusCode::kUnknown, "fail");
status.SetPayload("foo", absl::Cord("bar"));
std::stringstream stream;
stream << status;
EXPECT_EQ(stream.str(), absl::StrCat(status));
}
absl::Status EraseAndReturn(const absl::Status& base) {
absl::Status copy = base;
EXPECT_TRUE(copy.ErasePayload(kUrl1));
return copy;
}
TEST(Status, CopyOnWriteForErasePayload) {
{
absl::Status base(absl::StatusCode::kInvalidArgument, "fail");
base.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_TRUE(base.GetPayload(kUrl1).has_value());
absl::Status copy = EraseAndReturn(base);
EXPECT_TRUE(base.GetPayload(kUrl1).has_value());
EXPECT_FALSE(copy.GetPayload(kUrl1).has_value());
}
{
absl::Status base(absl::StatusCode::kInvalidArgument, "fail");
base.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy = base;
EXPECT_TRUE(base.GetPayload(kUrl1).has_value());
EXPECT_TRUE(copy.GetPayload(kUrl1).has_value());
EXPECT_TRUE(base.ErasePayload(kUrl1));
EXPECT_FALSE(base.GetPayload(kUrl1).has_value());
EXPECT_TRUE(copy.GetPayload(kUrl1).has_value());
}
}
TEST(Status, CopyConstructor) {
{
absl::Status status;
absl::Status copy(status);
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
absl::Status copy(status);
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy(status);
EXPECT_EQ(copy, status);
}
}
TEST(Status, CopyAssignment) {
absl::Status assignee;
{
absl::Status status;
assignee = status;
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
assignee = status;
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
assignee = status;
EXPECT_EQ(assignee, status);
}
}
TEST(Status, CopyAssignmentIsNotRef) {
const absl::Status status_orig(absl::StatusCode::kInvalidArgument, "message");
absl::Status status_copy = status_orig;
EXPECT_EQ(status_orig, status_copy);
status_copy.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_NE(status_orig, status_copy);
}
TEST(Status, MoveConstructor) {
{
absl::Status status;
absl::Status copy(absl::Status{});
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
absl::Status copy(
absl::Status(absl::StatusCode::kInvalidArgument, "message"));
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy1(status);
absl::Status copy2(std::move(status));
EXPECT_EQ(copy1, copy2);
}
}
TEST(Status, MoveAssignment) {
absl::Status assignee;
{
absl::Status status;
assignee = absl::Status();
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
assignee = absl::Status(absl::StatusCode::kInvalidArgument, "message");
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy(status);
assignee = std::move(status);
EXPECT_EQ(assignee, copy);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
absl::Status copy(status);
assignee = static_cast<absl::Status&&>(status);
EXPECT_EQ(assignee, copy);
}
}
TEST(Status, Update) {
absl::Status s;
s.Update(absl::OkStatus());
EXPECT_TRUE(s.ok());
const absl::Status a(absl::StatusCode::kCancelled, "message");
s.Update(a);
EXPECT_EQ(s, a);
const absl::Status b(absl::StatusCode::kInternal, "other message");
s.Update(b);
EXPECT_EQ(s, a);
s.Update(absl::OkStatus());
EXPECT_EQ(s, a);
EXPECT_FALSE(s.ok());
}
TEST(Status, Equality) {
absl::Status ok;
absl::Status no_payload = absl::CancelledError("no payload");
absl::Status one_payload = absl::InvalidArgumentError("one payload");
one_payload.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status two_payloads = one_payload;
two_payloads.SetPayload(kUrl2, absl::Cord(kPayload2));
const std::array<absl::Status, 4> status_arr = {ok, no_payload, one_payload,
two_payloads};
for (int i = 0; i < status_arr.size(); i++) {
for (int j = 0; j < status_arr.size(); j++) {
if (i == j) {
EXPECT_TRUE(status_arr[i] == status_arr[j]);
EXPECT_FALSE(status_arr[i] != status_arr[j]);
} else {
EXPECT_TRUE(status_arr[i] != status_arr[j]);
EXPECT_FALSE(status_arr[i] == status_arr[j]);
}
}
}
}
TEST(Status, Swap) {
auto test_swap = [](const absl::Status& s1, const absl::Status& s2) {
absl::Status copy1 = s1, copy2 = s2;
swap(copy1, copy2);
EXPECT_EQ(copy1, s2);
EXPECT_EQ(copy2, s1);
};
const absl::Status ok;
const absl::Status no_payload(absl::StatusCode::kAlreadyExists, "no payload");
absl::Status with_payload(absl::StatusCode::kInternal, "with payload");
with_payload.SetPayload(kUrl1, absl::Cord(kPayload1));
test_swap(ok, no_payload);
test_swap(no_payload, ok);
test_swap(ok, with_payload);
test_swap(with_payload, ok);
test_swap(no_payload, with_payload);
test_swap(with_payload, no_payload);
}
TEST(StatusErrno, ErrnoToStatusCode) {
EXPECT_EQ(absl::ErrnoToStatusCode(0), absl::StatusCode::kOk);
EXPECT_EQ(absl::ErrnoToStatusCode(EINVAL),
absl::StatusCode::kInvalidArgument);
EXPECT_EQ(absl::ErrnoToStatusCode(ENOENT), absl::StatusCode::kNotFound);
EXPECT_EQ(absl::ErrnoToStatusCode(19980927), absl::StatusCode::kUnknown);
}
TEST(StatusErrno, ErrnoToStatus) {
absl::Status status = absl::ErrnoToStatus(ENOENT, "Cannot open 'path'");
EXPECT_EQ(status.code(), absl::StatusCode::kNotFound);
EXPECT_EQ(status.message(), "Cannot open 'path': No such file or directory");
}
} | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/status.cc | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/status_test.cc | 03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4 |
cc9e35f1-f6de-45a6-a527-4712b67254ca | cpp | google/arolla | expr_operator_signature | arolla/expr/expr_operator_signature.cc | arolla/expr/expr_operator_signature_test.cc | #include "arolla/expr/expr_operator_signature.h"
#include <algorithm>
#include <cstddef>
#include <optional>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_node.h"
#include "arolla/qtype/typed_value.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/string.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr {
namespace {
using Param = ExprOperatorSignature::Parameter;
absl::Status ValidateSignatureParameterNames(
const ExprOperatorSignature& signature) {
for (const auto& param : signature.parameters) {
if (!IsIdentifier(param.name)) {
return absl::InvalidArgumentError(absl::StrCat(
"illegal parameter name: '", absl::CEscape(param.name), "'"));
}
}
absl::flat_hash_set<absl::string_view> param_names;
param_names.reserve(signature.parameters.size());
for (const auto& param : signature.parameters) {
if (!param_names.insert(param.name).second) {
return absl::InvalidArgumentError(
absl::StrCat("non-unique parameter name: '", param.name, "'"));
}
}
return absl::OkStatus();
}
absl::Status ValidateSignatureParameterKinds(
const ExprOperatorSignature& signature) {
for (const auto& param : signature.parameters) {
if (param.kind != Param::Kind::kPositionalOrKeyword &&
param.kind != Param::Kind::kVariadicPositional) {
return absl::InvalidArgumentError(
absl::StrCat("parameter '", param.name,
"' has illegal kind: ", static_cast<int>(param.kind)));
}
}
return absl::OkStatus();
}
absl::Status ValidateSignaturePositionalOrKeywordParameters(
const ExprOperatorSignature& signature) {
bool had_default_value = false;
for (const auto& param : signature.parameters) {
if (param.kind != Param::Kind::kPositionalOrKeyword) {
break;
}
if (!param.default_value.has_value()) {
if (had_default_value) {
return absl::InvalidArgumentError(
"parameter without a default value goes after a parameter with "
"a default value");
}
} else {
had_default_value = true;
}
}
return absl::OkStatus();
}
absl::Status ValidateSignatureVariadicParameters(
const ExprOperatorSignature& signature) {
for (size_t i = 0; i + 1 < signature.parameters.size(); ++i) {
if (signature.parameters[i].kind == Param::Kind::kVariadicPositional) {
return absl::InvalidArgumentError("variadic parameter must be the last");
}
}
if (!signature.parameters.empty() &&
signature.parameters.back().kind == Param::Kind::kVariadicPositional &&
signature.parameters.back().default_value.has_value()) {
return absl::InvalidArgumentError(
"variadic parameter cannot have a default value");
}
return absl::OkStatus();
}
}
absl::Status ValidateSignature(const ExprOperatorSignature& signature) {
RETURN_IF_ERROR(ValidateSignatureParameterNames(signature));
RETURN_IF_ERROR(ValidateSignatureParameterKinds(signature));
RETURN_IF_ERROR(ValidateSignaturePositionalOrKeywordParameters(signature));
RETURN_IF_ERROR(ValidateSignatureVariadicParameters(signature));
return absl::OkStatus();
}
bool HasVariadicParameter(const ExprOperatorSignature& signature) {
return !signature.parameters.empty() &&
signature.parameters.back().kind == Param::Kind::kVariadicPositional;
}
namespace {
absl::Status MultipleValuesForArgumentError(absl::string_view name) {
return absl::InvalidArgumentError(
absl::StrCat("multiple values for argument: '", name, "'"));
}
absl::Status UnexpectedParameterKindError(Param::Kind kind) {
return absl::InternalError(
absl::StrCat("unexpected parameter kind: ", static_cast<int>(kind)));
}
absl::Status UnexpectedKeywordArgumentsError(
std::vector<absl::string_view> unexpected_keyword_arguments) {
if (unexpected_keyword_arguments.size() == 1) {
return absl::InvalidArgumentError(
absl::StrCat("unexpected keyword argument: '",
unexpected_keyword_arguments[0], "'"));
}
std::sort(unexpected_keyword_arguments.begin(),
unexpected_keyword_arguments.end());
return absl::InvalidArgumentError(
absl::StrCat("unexpected keyword arguments: '",
absl::StrJoin(unexpected_keyword_arguments, "', '"), "'"));
}
absl::Status MissingArgumentsError(
absl::Span<const absl::string_view> missing_arguments) {
if (missing_arguments.size() == 1) {
return absl::InvalidArgumentError(absl::StrCat(
"missing 1 required argument: '", missing_arguments[0], "'"));
}
return absl::InvalidArgumentError(absl::StrCat(
"missing ", missing_arguments.size(), " required arguments: '",
absl::StrJoin(missing_arguments, "', '"), "'"));
}
}
absl::Status ValidateDepsCount(const ExprOperatorSignature& signature,
size_t deps_count, absl::StatusCode error_code) {
const bool has_variadic_param = HasVariadicParameter(signature);
size_t count_required_params = has_variadic_param
? signature.parameters.size() - 1
: signature.parameters.size();
if (deps_count < count_required_params ||
(!has_variadic_param && deps_count > count_required_params)) {
return absl::Status(
error_code,
absl::StrFormat("incorrect number of dependencies passed to an "
"operator node: expected %d but got %d",
count_required_params, deps_count));
}
return absl::OkStatus();
}
absl::StatusOr<std::vector<ExprNodePtr>> BindArguments(
const ExprOperatorSignature& signature, absl::Span<const ExprNodePtr> args,
const absl::flat_hash_map<std::string, ExprNodePtr>& kwargs) {
DCHECK_OK(ValidateSignature(signature));
std::vector<ExprNodePtr> result;
result.reserve(args.size() + kwargs.size());
size_t paramIdx = 0;
size_t argIdx = 0;
for (; paramIdx < signature.parameters.size() && argIdx < args.size();
++paramIdx) {
const auto& param = signature.parameters[paramIdx];
if (param.kind == Param::Kind::kPositionalOrKeyword) {
if (kwargs.count(param.name) != 0) {
return MultipleValuesForArgumentError(param.name);
}
result.push_back(args[argIdx++]);
} else if (param.kind == Param::Kind::kVariadicPositional) {
result.insert(result.end(), args.begin() + argIdx, args.end());
argIdx = args.size();
} else {
return UnexpectedParameterKindError(param.kind);
}
}
if (argIdx < args.size()) {
return absl::InvalidArgumentError(absl::StrCat(
"too many positional arguments passed: expected maximumum is ",
result.size(), " but got ", args.size()));
}
std::vector<absl::string_view> missing_arguments;
absl::flat_hash_set<absl::string_view> used_kwargs;
used_kwargs.reserve(args.size() + kwargs.size());
for (; paramIdx < signature.parameters.size(); ++paramIdx) {
const auto& param = signature.parameters[paramIdx];
if (param.kind == Param::Kind::kPositionalOrKeyword) {
if (const auto it = kwargs.find(param.name); it != kwargs.end()) {
used_kwargs.insert(param.name);
result.push_back(it->second);
} else if (param.default_value.has_value()) {
result.push_back(Literal(*param.default_value));
} else {
missing_arguments.push_back(param.name);
}
} else if (param.kind != Param::Kind::kVariadicPositional) {
return UnexpectedParameterKindError(param.kind);
}
}
std::vector<absl::string_view> unexpected_keyword_arguments;
for (const auto& kv : kwargs) {
if (!used_kwargs.contains(kv.first)) {
unexpected_keyword_arguments.push_back(kv.first);
}
}
if (!unexpected_keyword_arguments.empty()) {
return UnexpectedKeywordArgumentsError(
std::move(unexpected_keyword_arguments));
}
if (!missing_arguments.empty()) {
return MissingArgumentsError(missing_arguments);
}
return result;
}
ExprOperatorSignature ExprOperatorSignature::MakeArgsN(size_t n) {
ExprOperatorSignature result;
if (n == 1) {
result.parameters.push_back({absl::StrCat("arg")});
} else {
for (size_t i = 0; i < n; ++i) {
result.parameters.push_back({absl::StrCat("arg", i + 1)});
}
}
return result;
}
ExprOperatorSignature ExprOperatorSignature::MakeVariadicArgs() {
return ExprOperatorSignature{
{"args", std::nullopt,
ExprOperatorSignature::Parameter::Kind::kVariadicPositional}};
}
absl::StatusOr<ExprOperatorSignature> ExprOperatorSignature::Make(
absl::string_view signature_spec,
absl::Span<const TypedValue> default_values) {
ExprOperatorSignature result;
signature_spec = absl::StripAsciiWhitespace(signature_spec);
if (auto pos = signature_spec.rfind('|'); pos < signature_spec.size()) {
result.aux_policy =
std::string(absl::StripAsciiWhitespace(signature_spec.substr(pos + 1)));
signature_spec = absl::StripAsciiWhitespace(signature_spec.substr(0, pos));
}
std::vector<absl::string_view> param_defs;
if (!signature_spec.empty()) {
param_defs = absl::StrSplit(signature_spec, ',');
}
size_t i = 0;
for (auto param_def : param_defs) {
Param param;
param_def = absl::StripAsciiWhitespace(param_def);
if (absl::StartsWith(param_def, "*")) {
param_def = absl::StripLeadingAsciiWhitespace(param_def.substr(1));
param.kind = Param::Kind::kVariadicPositional;
} else {
param.kind = Param::Kind::kPositionalOrKeyword;
}
if (absl::EndsWith(param_def, "=")) {
param_def = absl::StripTrailingAsciiWhitespace(
param_def.substr(0, param_def.size() - 1));
if (i >= default_values.size()) {
return absl::InvalidArgumentError(absl::StrCat(
"default value expected, but not provided for parameter: '",
param_def, "'"));
}
param.default_value = default_values[i];
i += 1;
}
param.name = std::string(param_def);
result.parameters.push_back(std::move(param));
}
if (i != default_values.size()) {
return absl::InvalidArgumentError(
"some of the provided default values left unused");
}
RETURN_IF_ERROR(ValidateSignature(result));
return result;
}
std::string GetExprOperatorSignatureSpec(
const ExprOperatorSignature& signature) {
std::ostringstream result;
bool first = true;
for (const auto& param : signature.parameters) {
result << NonFirstComma(first);
switch (param.kind) {
case Param::Kind::kPositionalOrKeyword:
break;
case Param::Kind::kVariadicPositional:
result << '*';
}
result << param.name;
if (param.default_value.has_value()) {
result << '=';
}
}
if (!signature.aux_policy.empty()) {
result << "|" << signature.aux_policy;
}
return std::move(result).str();
}
}
namespace arolla {
void FingerprintHasherTraits<expr::ExprOperatorSignature>::operator()(
FingerprintHasher* hasher,
const expr::ExprOperatorSignature& signature) const {
hasher->Combine(signature.parameters.size());
for (const auto& param : signature.parameters) {
hasher->Combine(param.name, param.kind);
hasher->Combine(param.default_value ? param.default_value->GetFingerprint()
: Fingerprint{});
}
hasher->Combine(signature.aux_policy);
}
} | #include "arolla/expr/expr_operator_signature.h"
#include <cstddef>
#include <optional>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_debug_string.h"
#include "arolla/expr/expr_node.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/testing/qtype.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/unit.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr {
namespace {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::arolla::testing::TypedValueWith;
using ::testing::HasSubstr;
using ::testing::Optional;
TEST(ExprOperatorSignature, HasVariadicParameter) {
ExprOperatorSignature sig;
EXPECT_FALSE(HasVariadicParameter(sig));
sig.parameters.push_back({"arg"});
EXPECT_FALSE(HasVariadicParameter(sig));
sig.parameters.push_back(
{"*args", std::nullopt,
ExprOperatorSignature::Parameter::Kind::kVariadicPositional});
EXPECT_TRUE(HasVariadicParameter(sig));
}
TEST(ExprOperatorSignature, ExprOperatorSignature_MakeArgsN) {
using Kind = ExprOperatorSignature::Parameter::Kind;
{
const auto sig = ExprOperatorSignature::MakeArgsN(0);
EXPECT_TRUE(sig.parameters.empty());
EXPECT_TRUE(sig.aux_policy.empty());
}
{
const auto sig = ExprOperatorSignature::MakeArgsN(1);
EXPECT_EQ(sig.parameters.size(), 1);
EXPECT_EQ(sig.parameters[0].name, "arg");
EXPECT_EQ(sig.parameters[0].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword);
EXPECT_TRUE(sig.aux_policy.empty());
}
{
const auto sig = ExprOperatorSignature::MakeArgsN(3);
EXPECT_EQ(sig.parameters.size(), 3);
EXPECT_EQ(sig.parameters[0].name, "arg1");
EXPECT_EQ(sig.parameters[0].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword);
EXPECT_EQ(sig.parameters[1].name, "arg2");
EXPECT_EQ(sig.parameters[1].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[1].kind, Kind::kPositionalOrKeyword);
EXPECT_EQ(sig.parameters[2].name, "arg3");
EXPECT_EQ(sig.parameters[2].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[2].kind, Kind::kPositionalOrKeyword);
EXPECT_TRUE(sig.aux_policy.empty());
}
}
TEST(ExprOperatorSignature, ExprOperatorSignature_MakeVariadicArgs) {
using Kind = ExprOperatorSignature::Parameter::Kind;
const auto sig = ExprOperatorSignature::MakeVariadicArgs();
EXPECT_EQ(sig.parameters.size(), 1);
EXPECT_EQ(sig.parameters[0].name, "args");
EXPECT_EQ(sig.parameters[0].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[0].kind, Kind::kVariadicPositional);
EXPECT_TRUE(sig.aux_policy.empty());
}
TEST(ExprOperatorSignature, ExprOperatorSignature_Make) {
using Sig = ExprOperatorSignature;
using Kind = ExprOperatorSignature::Parameter::Kind;
{
ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make(""));
EXPECT_TRUE(sig.parameters.empty());
EXPECT_TRUE(sig.aux_policy.empty());
}
{
ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("arg"));
EXPECT_EQ(sig.parameters.size(), 1);
EXPECT_EQ(sig.parameters[0].name, "arg");
EXPECT_EQ(sig.parameters[0].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword);
EXPECT_TRUE(sig.aux_policy.empty());
}
{
ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("arg=", kUnit));
EXPECT_EQ(sig.parameters.size(), 1);
EXPECT_EQ(sig.parameters[0].name, "arg");
EXPECT_THAT(*sig.parameters[0].default_value, TypedValueWith<Unit>(kUnit));
EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword);
EXPECT_TRUE(sig.aux_policy.empty());
}
{
ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("*args"));
EXPECT_EQ(sig.parameters.size(), 1);
EXPECT_EQ(sig.parameters[0].name, "args");
EXPECT_EQ(sig.parameters[0].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[0].kind, Kind::kVariadicPositional);
EXPECT_TRUE(sig.aux_policy.empty());
}
{
ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make(
"arg1, arg2=, *args", kUnit));
EXPECT_EQ(sig.parameters.size(), 3);
EXPECT_EQ(sig.parameters[0].name, "arg1");
EXPECT_EQ(sig.parameters[0].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword);
EXPECT_EQ(sig.parameters[1].name, "arg2");
EXPECT_THAT(sig.parameters[1].default_value,
Optional(TypedValueWith<Unit>(kUnit)));
EXPECT_EQ(sig.parameters[1].kind, Kind::kPositionalOrKeyword);
EXPECT_EQ(sig.parameters[2].name, "args");
EXPECT_EQ(sig.parameters[2].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[2].kind, Kind::kVariadicPositional);
EXPECT_TRUE(sig.aux_policy.empty());
}
{
ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("|"));
EXPECT_TRUE(sig.parameters.empty());
EXPECT_TRUE(sig.aux_policy.empty());
}
{
ASSERT_OK_AND_ASSIGN(const auto sig,
ExprOperatorSignature::Make("|policy"));
EXPECT_TRUE(sig.parameters.empty());
EXPECT_EQ(sig.aux_policy, "policy");
}
{
ASSERT_OK_AND_ASSIGN(
const auto sig,
ExprOperatorSignature::Make("arg1, arg2=, *args|policy", kUnit));
EXPECT_EQ(sig.parameters.size(), 3);
EXPECT_EQ(sig.parameters[0].name, "arg1");
EXPECT_EQ(sig.parameters[0].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword);
EXPECT_EQ(sig.parameters[1].name, "arg2");
EXPECT_THAT(sig.parameters[1].default_value,
Optional(TypedValueWith<Unit>(kUnit)));
EXPECT_EQ(sig.parameters[1].kind, Kind::kPositionalOrKeyword);
EXPECT_EQ(sig.parameters[2].name, "args");
EXPECT_EQ(sig.parameters[2].default_value, std::nullopt);
EXPECT_EQ(sig.parameters[2].kind, Kind::kVariadicPositional);
EXPECT_EQ(sig.aux_policy, "policy");
}
EXPECT_THAT(
ExprOperatorSignature::Make("arg1, arg2="),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("'arg2'")));
EXPECT_THAT(
ExprOperatorSignature::Make("arg1, arg2=", kUnit, kUnit),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unused")));
{
ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("|policy"));
EXPECT_TRUE(sig.parameters.empty());
EXPECT_EQ(sig.aux_policy, "policy");
}
}
TEST(ExprOperatorSignature, ValidateSignature_IsValidParamName) {
constexpr auto validate_param_name = [](absl::string_view name) {
return ValidateSignature(ExprOperatorSignature{{std::string(name)}});
};
EXPECT_THAT(validate_param_name(""),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_OK(validate_param_name("_"));
EXPECT_OK(validate_param_name("A"));
EXPECT_OK(validate_param_name("Z"));
EXPECT_OK(validate_param_name("a"));
EXPECT_OK(validate_param_name("z"));
EXPECT_THAT(validate_param_name("0"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_param_name("$"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_param_name("/"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_param_name("*"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_OK(validate_param_name("_AZaz_09"));
EXPECT_THAT(validate_param_name("_$"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_param_name("_/"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_param_name("_*"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_param_name("*_"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_param_name("**_"),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(ExprOperatorSignature, Make_ValidateSignature) {
constexpr auto validate_signature = [](absl::string_view signature,
auto&&... defaultValues) {
return ExprOperatorSignature::Make(signature, defaultValues...);
};
EXPECT_OK(validate_signature(""));
EXPECT_OK(validate_signature("arg"));
EXPECT_OK(validate_signature("arg=", kUnit));
EXPECT_OK(validate_signature("arg0, arg1=", kUnit));
EXPECT_OK(validate_signature("arg0=, arg1=", kUnit, kUnit));
EXPECT_OK(validate_signature("*args"));
EXPECT_OK(validate_signature("arg, *args"));
EXPECT_OK(validate_signature("arg=, *args", kUnit));
EXPECT_OK(validate_signature("arg0, arg1=, *args", kUnit));
EXPECT_OK(validate_signature("arg0=, arg1=, *args", kUnit, kUnit));
EXPECT_OK(validate_signature("|policy"));
EXPECT_OK(validate_signature("arg0=, arg1=, *args|policy", kUnit, kUnit));
EXPECT_THAT(validate_signature("arg0=, arg1", kUnit),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_signature("*args=", kUnit),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_signature("arg, arg"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_signature("arg, *arg"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_signature("*args, arg"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(validate_signature("*args0, *args1"),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(ExprOperatorSignature, ValidateSignature_FormattedErrorMessages) {
EXPECT_THAT(ExprOperatorSignature::Make("$"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("illegal parameter name: '$'")));
EXPECT_THAT(ExprOperatorSignature::Make("x, x"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("non-unique parameter name: 'x'")));
}
TEST(ExprOperatorSignature, BindArguments) {
constexpr auto bind_arguments =
[](const ExprOperatorSignature& signature,
absl::string_view args_def) -> absl::StatusOr<std::string> {
std::vector<ExprNodePtr> args;
absl::flat_hash_map<std::string, ExprNodePtr> kwargs;
for (absl::string_view arg :
absl::StrSplit(args_def, ' ', absl::SkipEmpty())) {
if (size_t pos = arg.find('='); pos == absl::string_view::npos) {
args.push_back(Leaf(arg));
} else {
std::string kw(arg.substr(0, pos));
kwargs[kw] = Leaf(arg.substr(pos + 1));
}
}
ASSIGN_OR_RETURN(auto bound_args, BindArguments(signature, args, kwargs));
std::vector<std::string> result;
result.reserve(bound_args.size());
for (const auto& node : bound_args) {
if (node->is_leaf()) {
result.push_back(node->leaf_key());
} else {
result.push_back(ToDebugString(node));
}
}
return absl::StrJoin(result, " ");
};
const auto x = Leaf("x");
{
ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make(
"arg0, arg1=, *args", kUnit));
EXPECT_THAT(bind_arguments(sig, ""),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u unit"));
EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v"));
EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w"));
EXPECT_THAT(bind_arguments(sig, "u v w y"), IsOkAndHolds("u v w y"));
}
{
ASSERT_OK_AND_ASSIGN(const auto sig,
ExprOperatorSignature::Make("arg=, *args", kUnit));
EXPECT_THAT(bind_arguments(sig, ""), IsOkAndHolds("unit"));
EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u"));
EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v"));
EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w"));
}
{
ASSERT_OK_AND_ASSIGN(const auto sig,
ExprOperatorSignature::Make("arg, *args"));
EXPECT_THAT(bind_arguments(sig, ""),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u"));
EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v"));
EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w"));
}
{
ASSERT_OK_AND_ASSIGN(const auto sig,
ExprOperatorSignature::Make("arg0, arg1=", kUnit));
EXPECT_THAT(bind_arguments(sig, ""),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u unit"));
EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v"));
EXPECT_THAT(bind_arguments(sig, "u v w"),
StatusIs(absl::StatusCode::kInvalidArgument));
}
{
ASSERT_OK_AND_ASSIGN(
const auto sig,
ExprOperatorSignature::Make("arg0, arg1=, arg2=", kUnit, kUnit));
EXPECT_THAT(bind_arguments(sig, ""),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u unit unit"));
EXPECT_THAT(bind_arguments(sig, "arg0=u"), IsOkAndHolds("u unit unit"));
EXPECT_THAT(bind_arguments(sig, "arg1=v"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "arg2=w"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v unit"));
EXPECT_THAT(bind_arguments(sig, "v arg0=u"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u arg1=v"), IsOkAndHolds("u v unit"));
EXPECT_THAT(bind_arguments(sig, "u arg2=w"), IsOkAndHolds("u unit w"));
EXPECT_THAT(bind_arguments(sig, "arg0=u arg1=v"), IsOkAndHolds("u v unit"));
EXPECT_THAT(bind_arguments(sig, "arg0=u arg2=w"), IsOkAndHolds("u unit w"));
EXPECT_THAT(bind_arguments(sig, "arg1=v arg2=w"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w"));
EXPECT_THAT(bind_arguments(sig, "v w arg0=u"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u w arg1=v"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u v arg2=w"), IsOkAndHolds("u v w"));
EXPECT_THAT(bind_arguments(sig, "w arg0=u arg1=v"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "v arg0=u arg2=w"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "u arg1=v arg2=w"), IsOkAndHolds("u v w"));
EXPECT_THAT(bind_arguments(sig, "arg0=u arg1=v arg2=w"),
IsOkAndHolds("u v w"));
}
{
ASSERT_OK_AND_ASSIGN(const auto sig,
ExprOperatorSignature::Make("arg0, *args"));
EXPECT_THAT(bind_arguments(sig, "arg0=u"), IsOkAndHolds("u"));
EXPECT_THAT(bind_arguments(sig, "arg0=u, args=v"),
StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(bind_arguments(sig, "v arg0=u"),
StatusIs(absl::StatusCode::kInvalidArgument));
}
}
TEST(ExprOperatorSignature, BindArguments_FormattedErrorMessages) {
const auto x = Leaf("x");
{
ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make(
"arg0, arg1, arg2, arg3=", kUnit));
EXPECT_THAT(BindArguments(sig, {}, {}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("missing 3 required arguments: "
"'arg0', 'arg1', 'arg2'")));
EXPECT_THAT(
BindArguments(sig, {x}, {}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("missing 2 required arguments: 'arg1', 'arg2'")));
EXPECT_THAT(BindArguments(sig, {x, x}, {}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("missing 1 required argument: 'arg2'")));
EXPECT_THAT(BindArguments(sig, {x, x, x, x, x}, {}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("too many positional arguments passed: "
"expected maximumum is 4 but got 5")));
}
{
ASSERT_OK_AND_ASSIGN(const auto sig,
ExprOperatorSignature::Make("arg0, *args"));
EXPECT_THAT(BindArguments(sig, {x}, {{"arg0", x}}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("multiple values for argument: 'arg0'")));
EXPECT_THAT(BindArguments(sig, {x}, {{"args", x}}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("unexpected keyword argument: 'args'")));
EXPECT_THAT(
BindArguments(sig, {x}, {{"args", x}, {"arg1", x}}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("unexpected keyword arguments: 'arg1', 'args'")));
}
}
TEST(ExprOperatorSignature, GetExprOperatorSignatureSpec) {
EXPECT_EQ(GetExprOperatorSignatureSpec(ExprOperatorSignature{}), "");
{
ASSERT_OK_AND_ASSIGN(
const auto sig,
ExprOperatorSignature::Make("arg0, arg1=, *args|policy", kUnit));
EXPECT_EQ(GetExprOperatorSignatureSpec(sig), "arg0, arg1=, *args|policy");
}
}
TEST(ExprOperatorSignature, Fingerprint) {
constexpr auto fgpt =
[](absl::StatusOr<ExprOperatorSignature> sig) -> Fingerprint {
return FingerprintHasher("dummy-salt").Combine(*sig).Finish();
};
const auto signatures = {
ExprOperatorSignature::Make(""),
ExprOperatorSignature::Make("x"),
ExprOperatorSignature::Make("*x"),
ExprOperatorSignature::Make("x|policy"),
ExprOperatorSignature::Make("y"),
ExprOperatorSignature::Make("x, y"),
ExprOperatorSignature::Make("x=", kUnit),
ExprOperatorSignature::Make("x=", GetQTypeQType()),
};
for (auto& sig1 : signatures) {
for (auto& sig2 : signatures) {
if (&sig1 == &sig2) {
EXPECT_EQ(fgpt(sig1), fgpt(sig2));
} else {
EXPECT_NE(fgpt(sig1), fgpt(sig2));
}
}
}
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/expr_operator_signature.cc | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/expr_operator_signature_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
d46120d8-760a-4260-9f54-29cb14e1086c | cpp | tensorflow/tensorflow | copy_thunk | third_party/xla/xla/service/gpu/runtime/copy_thunk.cc | third_party/xla/xla/backends/cpu/runtime/copy_thunk_test.cc | #include "xla/service/gpu/runtime/copy_thunk.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/synchronization/mutex.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/gpu/runtime/thunk.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/event.h"
#include "xla/stream_executor/stream_executor.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
DeviceToDeviceCopyThunk::DeviceToDeviceCopyThunk(
ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer, uint64_t mem_size)
: Thunk(Kind::kCopy, std::move(thunk_info)),
source_buffer_(source_buffer),
destination_buffer_(destination_buffer),
mem_size_(mem_size) {}
absl::Status DeviceToDeviceCopyThunk::ExecuteOnStream(
const ExecuteParams& params) {
se::DeviceMemoryBase destination_data =
params.buffer_allocations->GetDeviceAddress(destination_buffer_);
se::DeviceMemoryBase source_data =
params.buffer_allocations->GetDeviceAddress(source_buffer_);
VLOG(3) << "Memcpy D2D of size " << mem_size_ << " from "
<< source_data.opaque() << " to " << destination_data.opaque();
return params.stream->Memcpy(&destination_data, source_data, mem_size_);
}
CopyThunk::CopyThunk(ThunkInfo thunk_info,
const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer,
uint64_t mem_size)
: Thunk(Kind::kCopy, std::move(thunk_info)),
source_buffer_(source_buffer),
destination_buffer_(destination_buffer),
mem_size_(mem_size) {}
absl::Status CopyThunk::ExecuteOnStream(const ExecuteParams& params) {
return absl::OkStatus();
}
absl::Status CopyThunk::AsyncEvents::Emplace(se::StreamExecutor* executor,
const HloInstruction* instr,
std::unique_ptr<se::Event> event) {
Key key = {executor, instr};
absl::MutexLock lock(&mutex_);
VLOG(3) << "Emplace event " << event.get();
if (auto [it, inserted] = events_.try_emplace(key, std::move(event));
inserted) {
return absl::OkStatus();
}
return absl::InternalError("Async copy event already exists!");
}
absl::StatusOr<std::unique_ptr<se::Event>> CopyThunk::AsyncEvents::Extract(
se::StreamExecutor* executor, const HloInstruction* instr) {
Key key = {executor, instr};
absl::MutexLock lock(&mutex_);
if (auto event = events_.extract(key)) {
VLOG(3) << "Extract event " << event.mapped().get();
return std::move(event.mapped());
}
return absl::InternalError("Async copy event was not found!");
}
DeviceToHostCopyThunk::DeviceToHostCopyThunk(
ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer, uint64_t mem_size,
std::shared_ptr<CopyThunk::AsyncEvents> async_events,
const HloInstruction* instr)
: CopyThunk(std::move(thunk_info), source_buffer, destination_buffer,
mem_size),
async_events_(std::move(async_events)),
instr_(instr) {}
absl::Status DeviceToHostCopyThunk::ExecuteOnStream(
const ExecuteParams& params) {
se::DeviceMemoryBase destination_data =
params.buffer_allocations->GetDeviceAddress(destination());
se::DeviceMemoryBase source_data =
params.buffer_allocations->GetDeviceAddress(source());
void* cpu_dst = destination_data.opaque();
TF_ASSIGN_OR_RETURN(
se::Stream * stream,
GetStreamForExecution(Thunk::execution_stream_id(), params));
TF_RETURN_IF_ERROR(stream->Memcpy(cpu_dst, source_data, size_bytes()));
if (stream == params.stream) {
VLOG(2) << "Memcpy D2H from the main stream";
return absl::OkStatus();
}
VLOG(2) << "Memcpy D2H from the other stream";
se::StreamExecutor* executor = params.stream->parent();
TF_ASSIGN_OR_RETURN(auto event, executor->CreateEvent());
TF_RETURN_IF_ERROR(stream->RecordEvent(event.get()));
VLOG(3) << "Emplace events: " << event.get()
<< " for instr: " << instr_->ToString();
return async_events_->Emplace(executor, instr_, std::move(event));
}
HostToDeviceCopyThunk::HostToDeviceCopyThunk(
ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer, uint64_t mem_size,
std::shared_ptr<CopyThunk::AsyncEvents> async_events,
const HloInstruction* instr)
: CopyThunk(std::move(thunk_info), source_buffer, destination_buffer,
mem_size),
async_events_(std::move(async_events)),
instr_(instr) {}
absl::Status HostToDeviceCopyThunk::ExecuteOnStream(
const ExecuteParams& params) {
se::DeviceMemoryBase destination_data =
params.buffer_allocations->GetDeviceAddress(destination());
se::DeviceMemoryBase source_data =
params.buffer_allocations->GetDeviceAddress(source());
void* cpu_src = source_data.opaque();
TF_ASSIGN_OR_RETURN(
se::Stream * stream,
GetStreamForExecution(Thunk::execution_stream_id(), params));
TF_RETURN_IF_ERROR(stream->Memcpy(&destination_data, cpu_src, size_bytes()));
if (stream == params.stream) {
VLOG(2) << "Memcpy H2D from the main stream";
return absl::OkStatus();
}
VLOG(2) << "Memcpy H2D from the other stream";
se::StreamExecutor* executor = params.stream->parent();
TF_ASSIGN_OR_RETURN(auto event, executor->CreateEvent());
TF_RETURN_IF_ERROR(stream->RecordEvent(event.get()));
VLOG(3) << "Emplace events: " << event.get()
<< " for instr: " << instr_->ToString();
return async_events_->Emplace(executor, instr_, std::move(event));
}
CopyDoneThunk::CopyDoneThunk(
Thunk::Kind kind, ThunkInfo thunk_info,
std::shared_ptr<CopyThunk::AsyncEvents> async_events,
const HloInstruction* copy_start_instr)
: Thunk(kind, std::move(thunk_info)),
async_events_(std::move(async_events)),
copy_start_instr_(copy_start_instr) {}
absl::Status CopyDoneThunk::ExecuteOnStream(const ExecuteParams& params) {
VLOG(3) << "CopyDone thunk between a host and a device for: "
<< copy_start_instr_->ToString();
se::StreamExecutor* executor = params.stream->parent();
TF_ASSIGN_OR_RETURN(std::unique_ptr<se::Event> event,
async_events_->Extract(executor, copy_start_instr_));
return params.stream->WaitFor(event.get());
}
}
} | #include "xla/backends/cpu/runtime/copy_thunk.h"
#include <cstddef>
#include <vector>
#include "xla/backends/cpu/runtime/buffer_allocations.h"
#include "xla/backends/cpu/runtime/thunk.h"
#include "xla/layout_util.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/maybe_owning_device_memory.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace xla::cpu {
namespace {
TEST(CopyThunkTest, CopyEmptyShape) {
std::vector<MaybeOwningDeviceMemory> buffers;
buffers.emplace_back(se::DeviceMemoryBase(nullptr, 0));
buffers.emplace_back(se::DeviceMemoryBase(nullptr, 0));
BufferAllocations allocations(buffers);
BufferAllocation src_alloc(0, 100, 0);
BufferAllocation dst_alloc(1, 100, 0);
BufferAllocation::Slice src_slice(&src_alloc, 0, 0);
BufferAllocation::Slice dst_slice(&dst_alloc, 0, 0);
Shape shape = ShapeUtil::MakeShape(F32, {0, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto thunk,
CopyThunk::Create({"copy"}, src_slice, shape, dst_slice, shape));
Thunk::ExecuteParams params = {nullptr, &allocations};
auto execute_event = thunk->Execute(params);
tsl::BlockUntilReady(execute_event);
ASSERT_FALSE(execute_event.IsError());
}
TEST(CopyThunkTest, CopySameShape) {
std::vector<MaybeOwningDeviceMemory> buffers;
std::vector<float> src = {1.0, 2.0, 3.0, 4.0};
std::vector<float> dst(4, 0.0);
size_t size_in_bytes = src.size() * sizeof(float);
buffers.emplace_back(se::DeviceMemoryBase(src.data(), size_in_bytes));
buffers.emplace_back(se::DeviceMemoryBase(dst.data(), size_in_bytes));
BufferAllocations allocations(buffers);
BufferAllocation src_alloc(0, size_in_bytes, 0);
BufferAllocation dst_alloc(1, size_in_bytes, 0);
BufferAllocation::Slice src_slice(&src_alloc, 0, size_in_bytes);
BufferAllocation::Slice dst_slice(&dst_alloc, 0, size_in_bytes);
Shape shape = ShapeUtil::MakeShape(F32, {2, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto thunk,
CopyThunk::Create({"copy"}, src_slice, shape, dst_slice, shape));
Thunk::ExecuteParams params = {nullptr, &allocations};
auto execute_event = thunk->Execute(params);
tsl::BlockUntilReady(execute_event);
ASSERT_FALSE(execute_event.IsError());
EXPECT_EQ(src, dst);
}
TEST(CopyThunkTest, CopyTransposed) {
std::vector<MaybeOwningDeviceMemory> buffers;
std::vector<float> src = {1.0, 2.0, 3.0, 4.0};
std::vector<float> dst(4, 0.0);
size_t size_in_bytes = src.size() * sizeof(float);
buffers.emplace_back(se::DeviceMemoryBase(src.data(), size_in_bytes));
buffers.emplace_back(se::DeviceMemoryBase(dst.data(), size_in_bytes));
BufferAllocations allocations(buffers);
BufferAllocation src_alloc(0, size_in_bytes, 0);
BufferAllocation dst_alloc(1, size_in_bytes, 0);
BufferAllocation::Slice src_slice(&src_alloc, 0, size_in_bytes);
BufferAllocation::Slice dst_slice(&dst_alloc, 0, size_in_bytes);
Shape src_shape = ShapeUtil::MakeShape(F32, {2, 2});
*src_shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1});
Shape dst_shape = ShapeUtil::MakeShape(F32, {2, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto thunk,
CopyThunk::Create({"copy"}, src_slice, src_shape, dst_slice, dst_shape));
Thunk::ExecuteParams params = {nullptr, &allocations};
auto execute_event = thunk->Execute(params);
tsl::BlockUntilReady(execute_event);
ASSERT_FALSE(execute_event.IsError());
std::vector<float> expected = {1.0, 3.0, 2.0, 4.0};
EXPECT_EQ(expected, dst);
}
TEST(CopyThunkTest, CopyTransposedEmptyShape) {
std::vector<MaybeOwningDeviceMemory> buffers;
buffers.emplace_back(se::DeviceMemoryBase(nullptr, 0));
buffers.emplace_back(se::DeviceMemoryBase(nullptr, 0));
BufferAllocations allocations(buffers);
BufferAllocation src_alloc(0, 100, 0);
BufferAllocation dst_alloc(1, 100, 0);
BufferAllocation::Slice src_slice(&src_alloc, 0, 0);
BufferAllocation::Slice dst_slice(&dst_alloc, 0, 0);
Shape src_shape = ShapeUtil::MakeShape(F32, {0, 2});
*src_shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1});
Shape dst_shape = ShapeUtil::MakeShape(F32, {0, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto thunk,
CopyThunk::Create({"copy"}, src_slice, src_shape, dst_slice, dst_shape));
Thunk::ExecuteParams params = {nullptr, &allocations};
auto execute_event = thunk->Execute(params);
tsl::BlockUntilReady(execute_event);
ASSERT_FALSE(execute_event.IsError());
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/runtime/copy_thunk.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/backends/cpu/runtime/copy_thunk_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
da86d2eb-96f5-4b19-ab4a-2a58a81896a6 | cpp | google/quiche | bandwidth_sampler | quiche/quic/core/congestion_control/bandwidth_sampler.cc | quiche/quic/core/congestion_control/bandwidth_sampler_test.cc | #include "quiche/quic/core/congestion_control/bandwidth_sampler.h"
#include <algorithm>
#include <ostream>
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
#include "quiche/quic/platform/api/quic_flag_utils.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
std::ostream& operator<<(std::ostream& os, const SendTimeState& s) {
os << "{valid:" << s.is_valid << ", app_limited:" << s.is_app_limited
<< ", total_sent:" << s.total_bytes_sent
<< ", total_acked:" << s.total_bytes_acked
<< ", total_lost:" << s.total_bytes_lost
<< ", inflight:" << s.bytes_in_flight << "}";
return os;
}
QuicByteCount MaxAckHeightTracker::Update(
QuicBandwidth bandwidth_estimate, bool is_new_max_bandwidth,
QuicRoundTripCount round_trip_count,
QuicPacketNumber last_sent_packet_number,
QuicPacketNumber last_acked_packet_number, QuicTime ack_time,
QuicByteCount bytes_acked) {
bool force_new_epoch = false;
if (reduce_extra_acked_on_bandwidth_increase_ && is_new_max_bandwidth) {
ExtraAckedEvent best = max_ack_height_filter_.GetBest();
ExtraAckedEvent second_best = max_ack_height_filter_.GetSecondBest();
ExtraAckedEvent third_best = max_ack_height_filter_.GetThirdBest();
max_ack_height_filter_.Clear();
QuicByteCount expected_bytes_acked = bandwidth_estimate * best.time_delta;
if (expected_bytes_acked < best.bytes_acked) {
best.extra_acked = best.bytes_acked - expected_bytes_acked;
max_ack_height_filter_.Update(best, best.round);
}
expected_bytes_acked = bandwidth_estimate * second_best.time_delta;
if (expected_bytes_acked < second_best.bytes_acked) {
QUICHE_DCHECK_LE(best.round, second_best.round);
second_best.extra_acked = second_best.bytes_acked - expected_bytes_acked;
max_ack_height_filter_.Update(second_best, second_best.round);
}
expected_bytes_acked = bandwidth_estimate * third_best.time_delta;
if (expected_bytes_acked < third_best.bytes_acked) {
QUICHE_DCHECK_LE(second_best.round, third_best.round);
third_best.extra_acked = third_best.bytes_acked - expected_bytes_acked;
max_ack_height_filter_.Update(third_best, third_best.round);
}
}
if (start_new_aggregation_epoch_after_full_round_ &&
last_sent_packet_number_before_epoch_.IsInitialized() &&
last_acked_packet_number.IsInitialized() &&
last_acked_packet_number > last_sent_packet_number_before_epoch_) {
QUIC_DVLOG(3) << "Force starting a new aggregation epoch. "
"last_sent_packet_number_before_epoch_:"
<< last_sent_packet_number_before_epoch_
<< ", last_acked_packet_number:" << last_acked_packet_number;
if (reduce_extra_acked_on_bandwidth_increase_) {
QUIC_BUG(quic_bwsampler_46)
<< "A full round of aggregation should never "
<< "pass with startup_include_extra_acked(B204) enabled.";
}
force_new_epoch = true;
}
if (aggregation_epoch_start_time_ == QuicTime::Zero() || force_new_epoch) {
aggregation_epoch_bytes_ = bytes_acked;
aggregation_epoch_start_time_ = ack_time;
last_sent_packet_number_before_epoch_ = last_sent_packet_number;
++num_ack_aggregation_epochs_;
return 0;
}
QuicTime::Delta aggregation_delta = ack_time - aggregation_epoch_start_time_;
QuicByteCount expected_bytes_acked = bandwidth_estimate * aggregation_delta;
if (aggregation_epoch_bytes_ <=
ack_aggregation_bandwidth_threshold_ * expected_bytes_acked) {
QUIC_DVLOG(3) << "Starting a new aggregation epoch because "
"aggregation_epoch_bytes_ "
<< aggregation_epoch_bytes_
<< " is smaller than expected. "
"ack_aggregation_bandwidth_threshold_:"
<< ack_aggregation_bandwidth_threshold_
<< ", expected_bytes_acked:" << expected_bytes_acked
<< ", bandwidth_estimate:" << bandwidth_estimate
<< ", aggregation_duration:" << aggregation_delta
<< ", new_aggregation_epoch:" << ack_time
<< ", new_aggregation_bytes_acked:" << bytes_acked;
aggregation_epoch_bytes_ = bytes_acked;
aggregation_epoch_start_time_ = ack_time;
last_sent_packet_number_before_epoch_ = last_sent_packet_number;
++num_ack_aggregation_epochs_;
return 0;
}
aggregation_epoch_bytes_ += bytes_acked;
QuicByteCount extra_bytes_acked =
aggregation_epoch_bytes_ - expected_bytes_acked;
QUIC_DVLOG(3) << "Updating MaxAckHeight. ack_time:" << ack_time
<< ", last sent packet:" << last_sent_packet_number
<< ", bandwidth_estimate:" << bandwidth_estimate
<< ", bytes_acked:" << bytes_acked
<< ", expected_bytes_acked:" << expected_bytes_acked
<< ", aggregation_epoch_bytes_:" << aggregation_epoch_bytes_
<< ", extra_bytes_acked:" << extra_bytes_acked;
ExtraAckedEvent new_event;
new_event.extra_acked = extra_bytes_acked;
new_event.bytes_acked = aggregation_epoch_bytes_;
new_event.time_delta = aggregation_delta;
max_ack_height_filter_.Update(new_event, round_trip_count);
return extra_bytes_acked;
}
BandwidthSampler::BandwidthSampler(
const QuicUnackedPacketMap* unacked_packet_map,
QuicRoundTripCount max_height_tracker_window_length)
: total_bytes_sent_(0),
total_bytes_acked_(0),
total_bytes_lost_(0),
total_bytes_neutered_(0),
total_bytes_sent_at_last_acked_packet_(0),
last_acked_packet_sent_time_(QuicTime::Zero()),
last_acked_packet_ack_time_(QuicTime::Zero()),
is_app_limited_(true),
connection_state_map_(),
max_tracked_packets_(GetQuicFlag(quic_max_tracked_packet_count)),
unacked_packet_map_(unacked_packet_map),
max_ack_height_tracker_(max_height_tracker_window_length),
total_bytes_acked_after_last_ack_event_(0),
overestimate_avoidance_(false),
limit_max_ack_height_tracker_by_send_rate_(false) {}
BandwidthSampler::BandwidthSampler(const BandwidthSampler& other)
: total_bytes_sent_(other.total_bytes_sent_),
total_bytes_acked_(other.total_bytes_acked_),
total_bytes_lost_(other.total_bytes_lost_),
total_bytes_neutered_(other.total_bytes_neutered_),
total_bytes_sent_at_last_acked_packet_(
other.total_bytes_sent_at_last_acked_packet_),
last_acked_packet_sent_time_(other.last_acked_packet_sent_time_),
last_acked_packet_ack_time_(other.last_acked_packet_ack_time_),
last_sent_packet_(other.last_sent_packet_),
last_acked_packet_(other.last_acked_packet_),
is_app_limited_(other.is_app_limited_),
end_of_app_limited_phase_(other.end_of_app_limited_phase_),
connection_state_map_(other.connection_state_map_),
recent_ack_points_(other.recent_ack_points_),
a0_candidates_(other.a0_candidates_),
max_tracked_packets_(other.max_tracked_packets_),
unacked_packet_map_(other.unacked_packet_map_),
max_ack_height_tracker_(other.max_ack_height_tracker_),
total_bytes_acked_after_last_ack_event_(
other.total_bytes_acked_after_last_ack_event_),
overestimate_avoidance_(other.overestimate_avoidance_),
limit_max_ack_height_tracker_by_send_rate_(
other.limit_max_ack_height_tracker_by_send_rate_) {}
void BandwidthSampler::EnableOverestimateAvoidance() {
if (overestimate_avoidance_) {
return;
}
overestimate_avoidance_ = true;
max_ack_height_tracker_.SetAckAggregationBandwidthThreshold(2.0);
}
BandwidthSampler::~BandwidthSampler() {}
void BandwidthSampler::OnPacketSent(
QuicTime sent_time, QuicPacketNumber packet_number, QuicByteCount bytes,
QuicByteCount bytes_in_flight,
HasRetransmittableData has_retransmittable_data) {
last_sent_packet_ = packet_number;
if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) {
return;
}
total_bytes_sent_ += bytes;
if (bytes_in_flight == 0) {
last_acked_packet_ack_time_ = sent_time;
if (overestimate_avoidance_) {
recent_ack_points_.Clear();
recent_ack_points_.Update(sent_time, total_bytes_acked_);
a0_candidates_.clear();
a0_candidates_.push_back(recent_ack_points_.MostRecentPoint());
}
total_bytes_sent_at_last_acked_packet_ = total_bytes_sent_;
last_acked_packet_sent_time_ = sent_time;
}
if (!connection_state_map_.IsEmpty() &&
packet_number >
connection_state_map_.last_packet() + max_tracked_packets_) {
if (unacked_packet_map_ != nullptr && !unacked_packet_map_->empty()) {
QuicPacketNumber maybe_least_unacked =
unacked_packet_map_->GetLeastUnacked();
QUIC_BUG(quic_bug_10437_1)
<< "BandwidthSampler in-flight packet map has exceeded maximum "
"number of tracked packets("
<< max_tracked_packets_
<< "). First tracked: " << connection_state_map_.first_packet()
<< "; last tracked: " << connection_state_map_.last_packet()
<< "; entry_slots_used: " << connection_state_map_.entry_slots_used()
<< "; number_of_present_entries: "
<< connection_state_map_.number_of_present_entries()
<< "; packet number: " << packet_number
<< "; unacked_map: " << unacked_packet_map_->DebugString()
<< "; total_bytes_sent: " << total_bytes_sent_
<< "; total_bytes_acked: " << total_bytes_acked_
<< "; total_bytes_lost: " << total_bytes_lost_
<< "; total_bytes_neutered: " << total_bytes_neutered_
<< "; last_acked_packet_sent_time: " << last_acked_packet_sent_time_
<< "; total_bytes_sent_at_last_acked_packet: "
<< total_bytes_sent_at_last_acked_packet_
<< "; least_unacked_packet_info: "
<< (unacked_packet_map_->IsUnacked(maybe_least_unacked)
? unacked_packet_map_
->GetTransmissionInfo(maybe_least_unacked)
.DebugString()
: "n/a");
} else {
QUIC_BUG(quic_bug_10437_2)
<< "BandwidthSampler in-flight packet map has exceeded maximum "
"number of tracked packets.";
}
}
bool success = connection_state_map_.Emplace(packet_number, sent_time, bytes,
bytes_in_flight + bytes, *this);
QUIC_BUG_IF(quic_bug_10437_3, !success)
<< "BandwidthSampler failed to insert the packet "
"into the map, most likely because it's already "
"in it.";
}
void BandwidthSampler::OnPacketNeutered(QuicPacketNumber packet_number) {
connection_state_map_.Remove(
packet_number, [&](const ConnectionStateOnSentPacket& sent_packet) {
QUIC_CODE_COUNT(quic_bandwidth_sampler_packet_neutered);
total_bytes_neutered_ += sent_packet.size();
});
}
BandwidthSamplerInterface::CongestionEventSample
BandwidthSampler::OnCongestionEvent(QuicTime ack_time,
const AckedPacketVector& acked_packets,
const LostPacketVector& lost_packets,
QuicBandwidth max_bandwidth,
QuicBandwidth est_bandwidth_upper_bound,
QuicRoundTripCount round_trip_count) {
CongestionEventSample event_sample;
SendTimeState last_lost_packet_send_state;
for (const LostPacket& packet : lost_packets) {
SendTimeState send_state =
OnPacketLost(packet.packet_number, packet.bytes_lost);
if (send_state.is_valid) {
last_lost_packet_send_state = send_state;
}
}
if (acked_packets.empty()) {
event_sample.last_packet_send_state = last_lost_packet_send_state;
return event_sample;
}
SendTimeState last_acked_packet_send_state;
QuicBandwidth max_send_rate = QuicBandwidth::Zero();
for (const auto& packet : acked_packets) {
if (packet.spurious_loss) {
QUICHE_DCHECK_EQ(packet.bytes_acked, 0);
continue;
}
BandwidthSample sample =
OnPacketAcknowledged(ack_time, packet.packet_number);
if (!sample.state_at_send.is_valid) {
continue;
}
last_acked_packet_send_state = sample.state_at_send;
if (!sample.rtt.IsZero()) {
event_sample.sample_rtt = std::min(event_sample.sample_rtt, sample.rtt);
}
if (sample.bandwidth > event_sample.sample_max_bandwidth) {
event_sample.sample_max_bandwidth = sample.bandwidth;
event_sample.sample_is_app_limited = sample.state_at_send.is_app_limited;
}
if (!sample.send_rate.IsInfinite()) {
max_send_rate = std::max(max_send_rate, sample.send_rate);
}
const QuicByteCount inflight_sample =
total_bytes_acked() - last_acked_packet_send_state.total_bytes_acked;
if (inflight_sample > event_sample.sample_max_inflight) {
event_sample.sample_max_inflight = inflight_sample;
}
}
if (!last_lost_packet_send_state.is_valid) {
event_sample.last_packet_send_state = last_acked_packet_send_state;
} else if (!last_acked_packet_send_state.is_valid) {
event_sample.last_packet_send_state = last_lost_packet_send_state;
} else {
event_sample.last_packet_send_state =
lost_packets.back().packet_number > acked_packets.back().packet_number
? last_lost_packet_send_state
: last_acked_packet_send_state;
}
bool is_new_max_bandwidth = event_sample.sample_max_bandwidth > max_bandwidth;
max_bandwidth = std::max(max_bandwidth, event_sample.sample_max_bandwidth);
if (limit_max_ack_height_tracker_by_send_rate_) {
max_bandwidth = std::max(max_bandwidth, max_send_rate);
}
event_sample.extra_acked =
OnAckEventEnd(std::min(est_bandwidth_upper_bound, max_bandwidth),
is_new_max_bandwidth, round_trip_count);
return event_sample;
}
QuicByteCount BandwidthSampler::OnAckEventEnd(
QuicBandwidth bandwidth_estimate, bool is_new_max_bandwidth,
QuicRoundTripCount round_trip_count) {
const QuicByteCount newly_acked_bytes =
total_bytes_acked_ - total_bytes_acked_after_last_ack_event_;
if (newly_acked_bytes == 0) {
return 0;
}
total_bytes_acked_after_last_ack_event_ = total_bytes_acked_;
QuicByteCount extra_acked = max_ack_height_tracker_.Update(
bandwidth_estimate, is_new_max_bandwidth, round_trip_count,
last_sent_packet_, last_acked_packet_, last_acked_packet_ack_time_,
newly_acked_bytes);
if (overestimate_avoidance_ && extra_acked == 0) {
a0_candidates_.push_back(recent_ack_points_.LessRecentPoint());
QUIC_DVLOG(1) << "New a0_candidate:" << a0_candidates_.back();
}
return extra_acked;
}
BandwidthSample BandwidthSampler::OnPacketAcknowledged(
QuicTime ack_time, QuicPacketNumber packet_number) {
last_acked_packet_ = packet_number;
ConnectionStateOnSentPacket* sent_packet_pointer =
connection_state_map_.GetEntry(packet_number);
if (sent_packet_pointer == nullptr) {
return BandwidthSample();
}
BandwidthSample sample =
OnPacketAcknowledgedInner(ack_time, packet_number, *sent_packet_pointer);
return sample;
}
BandwidthSample BandwidthSampler::OnPacketAcknowledgedInner(
QuicTime ack_time, QuicPacketNumber packet_number,
const ConnectionStateOnSentPacket& sent_packet) {
total_bytes_acked_ += sent_packet.size();
total_bytes_sent_at_last_acked_packet_ =
sent_packet.send_time_state().total_bytes_sent;
last_acked_packet_sent_time_ = sent_packet.sent_time();
last_acked_packet_ack_time_ = ack_time;
if (overestimate_avoidance_) {
recent_ack_points_.Update(ack_time, total_bytes_acked_);
}
if (is_app_limited_) {
if (!end_of_app_limited_phase_.IsInitialized() ||
packet_number > end_of_app_limited_phase_) {
is_app_limited_ = false;
}
}
if (sent_packet.last_acked_packet_sent_time() == QuicTime::Zero()) {
QUIC_BUG(quic_bug_10437_4)
<< "sent_packet.last_acked_packet_sent_time is zero";
return BandwidthSample();
}
QuicBandwidth send_rate = QuicBandwidth::Infinite();
if (sent_packet.sent_time() > sent_packet.last_acked_packet_sent_time()) {
send_rate = QuicBandwidth::FromBytesAndTimeDelta(
sent_packet.send_time_state().total_bytes_sent -
sent_packet.total_bytes_sent_at_last_acked_packet(),
sent_packet.sent_time() - sent_packet.last_acked_packet_sent_time());
}
AckPoint a0;
if (overestimate_avoidance_ &&
ChooseA0Point(sent_packet.send_time_state().total_bytes_acked, &a0)) {
QUIC_DVLOG(2) << "Using a0 point: " << a0;
} else {
a0.ack_time = sent_packet.last_acked_packet_ack_time(),
a0.total_bytes_acked = sent_packet.send_time_state().total_bytes_acked;
}
if (ack_time <= a0.ack_time) {
if (a0.ack_time == sent_packet.sent_time()) {
QUIC_CODE_COUNT_N(quic_prev_ack_time_larger_than_current_ack_time, 1, 2);
} else {
QUIC_CODE_COUNT_N(quic_prev_ack_time_larger_than_current_ack_time, 2, 2);
}
QUIC_LOG_EVERY_N_SEC(ERROR, 60)
<< "Time of the previously acked packet:"
<< a0.ack_time.ToDebuggingValue()
<< " is larger than the ack time of the current packet:"
<< ack_time.ToDebuggingValue()
<< ". acked packet number:" << packet_number
<< ", total_bytes_acked_:" << total_bytes_acked_
<< ", overestimate_avoidance_:" << overestimate_avoidance_
<< ", sent_packet:" << sent_packet;
return BandwidthSample();
}
QuicBandwidth ack_rate = QuicBandwidth::FromBytesAndTimeDelta(
total_bytes_acked_ - a0.total_bytes_acked, ack_time - a0.ack_time);
BandwidthSample sample;
sample.bandwidth = std::min(send_rate, ack_rate);
sample.rtt = ack_time - sent_packet.sent_time();
sample.send_rate = send_rate;
SentPacketToSendTimeState(sent_packet, &sample.state_at_send);
if (sample.bandwidth.IsZero()) {
QUIC_LOG_EVERY_N_SEC(ERROR, 60)
<< "ack_rate: " << ack_rate << ", send_rate: " << send_rate
<< ". acked packet number:" << packet_number
<< ", overestimate_avoidance_:" << overestimate_avoidance_ << "a1:{"
<< total_bytes_acked_ << "@" << ack_time << "}, a0:{"
<< a0.total_bytes_acked << "@" << a0.ack_time
<< "}, sent_packet:" << sent_packet;
}
return sample;
}
bool BandwidthSampler::ChooseA0Point(QuicByteCount total_bytes_acked,
AckPoint* a0) {
if (a0_candidates_.empty()) {
QUIC_BUG(quic_bug_10437_5)
<< "No A0 point candicates. total_bytes_acked:" << total_bytes_acked;
return false;
}
if (a0_candidates_.size() == 1) {
*a0 = a0_candidates_.front();
return true;
}
for (size_t i = 1; i < a0_candidates_.size(); ++i) {
if (a0_candidates_[i].total_bytes_acked > total_bytes_acked) {
*a0 = a0_candidates_[i - 1];
if (i > 1) {
a0_candidates_.pop_front_n(i - 1);
}
return true;
}
}
*a0 = a0_candidates_.back();
a0_candidates_.pop_front_n(a0_candidates_.size() - 1);
return true;
}
SendTimeState BandwidthSampler::OnPacketLost(QuicPacketNumber packet_number,
QuicPacketLength bytes_lost) {
SendTimeState send_time_state;
total_bytes_lost_ += bytes_lost;
ConnectionStateOnSentPacket* sent_packet_pointer =
connection_state_map_.GetEntry(packet_number);
if (sent_packet_pointer != nullptr) {
SentPacketToSendTimeState(*sent_packet_pointer, &send_time_state);
}
return send_time_state;
}
void BandwidthSampler::SentPacketToSendTimeState(
const ConnectionStateOnSentPacket& sent_packet,
SendTimeState* send_time_state) const {
*send_time_state = sent_packet.send_time_state();
send_time_state->is_valid = true;
}
void BandwidthSampler::OnAppLimited() {
is_app_limited_ = true;
end_of_app_limited_phase_ = last_sent_packet_;
}
void BandwidthSampler::RemoveObsoletePackets(QuicPacketNumber least_unacked) {
connection_state_map_.RemoveUpTo(least_unacked);
}
QuicByteCount BandwidthSampler::total_bytes_sent() const {
return total_bytes_sent_;
}
QuicByteCount BandwidthSampler::total_bytes_acked() const {
return total_bytes_acked_;
}
QuicByteCount BandwidthSampler::total_bytes_lost() const {
return total_bytes_lost_;
}
QuicByteCount BandwidthSampler::total_bytes_neutered() const {
return total_bytes_neutered_;
}
bool BandwidthSampler::is_app_limited() const { return is_app_limited_; }
QuicPacketNumber BandwidthSampler::end_of_app_limited_phase() const {
return end_of_app_limited_phase_;
}
} | #include "quiche/quic/core/congestion_control/bandwidth_sampler.h"
#include <algorithm>
#include <cstdint>
#include <set>
#include <string>
#include "quiche/quic/core/quic_bandwidth.h"
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_logging.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/mock_clock.h"
namespace quic {
namespace test {
class BandwidthSamplerPeer {
public:
static size_t GetNumberOfTrackedPackets(const BandwidthSampler& sampler) {
return sampler.connection_state_map_.number_of_present_entries();
}
static QuicByteCount GetPacketSize(const BandwidthSampler& sampler,
QuicPacketNumber packet_number) {
return sampler.connection_state_map_.GetEntry(packet_number)->size();
}
};
const QuicByteCount kRegularPacketSize = 1280;
static_assert((kRegularPacketSize & 31) == 0,
"kRegularPacketSize has to be five times divisible by 2");
struct TestParameters {
bool overestimate_avoidance;
};
std::string PrintToString(const TestParameters& p) {
return p.overestimate_avoidance ? "enable_overestimate_avoidance"
: "no_enable_overestimate_avoidance";
}
class BandwidthSamplerTest : public QuicTestWithParam<TestParameters> {
protected:
BandwidthSamplerTest()
: sampler_(nullptr, 0),
sampler_app_limited_at_start_(sampler_.is_app_limited()),
bytes_in_flight_(0),
max_bandwidth_(QuicBandwidth::Zero()),
est_bandwidth_upper_bound_(QuicBandwidth::Infinite()),
round_trip_count_(0) {
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
if (GetParam().overestimate_avoidance) {
sampler_.EnableOverestimateAvoidance();
}
}
MockClock clock_;
BandwidthSampler sampler_;
bool sampler_app_limited_at_start_;
QuicByteCount bytes_in_flight_;
QuicBandwidth max_bandwidth_;
QuicBandwidth est_bandwidth_upper_bound_;
QuicRoundTripCount round_trip_count_;
QuicByteCount PacketsToBytes(QuicPacketCount packet_count) {
return packet_count * kRegularPacketSize;
}
void SendPacketInner(uint64_t packet_number, QuicByteCount bytes,
HasRetransmittableData has_retransmittable_data) {
sampler_.OnPacketSent(clock_.Now(), QuicPacketNumber(packet_number), bytes,
bytes_in_flight_, has_retransmittable_data);
if (has_retransmittable_data == HAS_RETRANSMITTABLE_DATA) {
bytes_in_flight_ += bytes;
}
}
void SendPacket(uint64_t packet_number) {
SendPacketInner(packet_number, kRegularPacketSize,
HAS_RETRANSMITTABLE_DATA);
}
BandwidthSample AckPacketInner(uint64_t packet_number) {
QuicByteCount size = BandwidthSamplerPeer::GetPacketSize(
sampler_, QuicPacketNumber(packet_number));
bytes_in_flight_ -= size;
BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent(
clock_.Now(), {MakeAckedPacket(packet_number)}, {}, max_bandwidth_,
est_bandwidth_upper_bound_, round_trip_count_);
max_bandwidth_ = std::max(max_bandwidth_, sample.sample_max_bandwidth);
BandwidthSample bandwidth_sample;
bandwidth_sample.bandwidth = sample.sample_max_bandwidth;
bandwidth_sample.rtt = sample.sample_rtt;
bandwidth_sample.state_at_send = sample.last_packet_send_state;
EXPECT_TRUE(bandwidth_sample.state_at_send.is_valid);
return bandwidth_sample;
}
AckedPacket MakeAckedPacket(uint64_t packet_number) const {
QuicByteCount size = BandwidthSamplerPeer::GetPacketSize(
sampler_, QuicPacketNumber(packet_number));
return AckedPacket(QuicPacketNumber(packet_number), size, clock_.Now());
}
LostPacket MakeLostPacket(uint64_t packet_number) const {
return LostPacket(QuicPacketNumber(packet_number),
BandwidthSamplerPeer::GetPacketSize(
sampler_, QuicPacketNumber(packet_number)));
}
QuicBandwidth AckPacket(uint64_t packet_number) {
BandwidthSample sample = AckPacketInner(packet_number);
return sample.bandwidth;
}
BandwidthSampler::CongestionEventSample OnCongestionEvent(
std::set<uint64_t> acked_packet_numbers,
std::set<uint64_t> lost_packet_numbers) {
AckedPacketVector acked_packets;
for (auto it = acked_packet_numbers.begin();
it != acked_packet_numbers.end(); ++it) {
acked_packets.push_back(MakeAckedPacket(*it));
bytes_in_flight_ -= acked_packets.back().bytes_acked;
}
LostPacketVector lost_packets;
for (auto it = lost_packet_numbers.begin(); it != lost_packet_numbers.end();
++it) {
lost_packets.push_back(MakeLostPacket(*it));
bytes_in_flight_ -= lost_packets.back().bytes_lost;
}
BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent(
clock_.Now(), acked_packets, lost_packets, max_bandwidth_,
est_bandwidth_upper_bound_, round_trip_count_);
max_bandwidth_ = std::max(max_bandwidth_, sample.sample_max_bandwidth);
return sample;
}
SendTimeState LosePacket(uint64_t packet_number) {
QuicByteCount size = BandwidthSamplerPeer::GetPacketSize(
sampler_, QuicPacketNumber(packet_number));
bytes_in_flight_ -= size;
LostPacket lost_packet(QuicPacketNumber(packet_number), size);
BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent(
clock_.Now(), {}, {lost_packet}, max_bandwidth_,
est_bandwidth_upper_bound_, round_trip_count_);
EXPECT_TRUE(sample.last_packet_send_state.is_valid);
EXPECT_EQ(sample.sample_max_bandwidth, QuicBandwidth::Zero());
EXPECT_EQ(sample.sample_rtt, QuicTime::Delta::Infinite());
return sample.last_packet_send_state;
}
void Send40PacketsAndAckFirst20(QuicTime::Delta time_between_packets) {
for (int i = 1; i <= 20; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
}
for (int i = 1; i <= 20; i++) {
AckPacket(i);
SendPacket(i + 20);
clock_.AdvanceTime(time_between_packets);
}
}
};
INSTANTIATE_TEST_SUITE_P(
BandwidthSamplerTests, BandwidthSamplerTest,
testing::Values(TestParameters{false},
TestParameters{true}),
testing::PrintToStringParamName());
TEST_P(BandwidthSamplerTest, SendAndWait) {
QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10);
QuicBandwidth expected_bandwidth =
QuicBandwidth::FromBytesPerSecond(kRegularPacketSize * 100);
for (int i = 1; i < 20; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
QuicBandwidth current_sample = AckPacket(i);
EXPECT_EQ(expected_bandwidth, current_sample);
}
for (int i = 20; i < 25; i++) {
time_between_packets = time_between_packets * 2;
expected_bandwidth = expected_bandwidth * 0.5;
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
QuicBandwidth current_sample = AckPacket(i);
EXPECT_EQ(expected_bandwidth, current_sample);
}
sampler_.RemoveObsoletePackets(QuicPacketNumber(25));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
EXPECT_EQ(0u, bytes_in_flight_);
}
TEST_P(BandwidthSamplerTest, SendTimeState) {
QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10);
for (int i = 1; i <= 5; i++) {
SendPacket(i);
EXPECT_EQ(PacketsToBytes(i), sampler_.total_bytes_sent());
clock_.AdvanceTime(time_between_packets);
}
SendTimeState send_time_state = AckPacketInner(1).state_at_send;
EXPECT_EQ(PacketsToBytes(1), send_time_state.total_bytes_sent);
EXPECT_EQ(0u, send_time_state.total_bytes_acked);
EXPECT_EQ(0u, send_time_state.total_bytes_lost);
EXPECT_EQ(PacketsToBytes(1), sampler_.total_bytes_acked());
send_time_state = LosePacket(2);
EXPECT_EQ(PacketsToBytes(2), send_time_state.total_bytes_sent);
EXPECT_EQ(0u, send_time_state.total_bytes_acked);
EXPECT_EQ(0u, send_time_state.total_bytes_lost);
EXPECT_EQ(PacketsToBytes(1), sampler_.total_bytes_lost());
send_time_state = LosePacket(3);
EXPECT_EQ(PacketsToBytes(3), send_time_state.total_bytes_sent);
EXPECT_EQ(0u, send_time_state.total_bytes_acked);
EXPECT_EQ(0u, send_time_state.total_bytes_lost);
EXPECT_EQ(PacketsToBytes(2), sampler_.total_bytes_lost());
for (int i = 6; i <= 10; i++) {
SendPacket(i);
EXPECT_EQ(PacketsToBytes(i), sampler_.total_bytes_sent());
clock_.AdvanceTime(time_between_packets);
}
QuicPacketCount acked_packet_count = 1;
EXPECT_EQ(PacketsToBytes(acked_packet_count), sampler_.total_bytes_acked());
for (int i = 4; i <= 10; i++) {
send_time_state = AckPacketInner(i).state_at_send;
++acked_packet_count;
EXPECT_EQ(PacketsToBytes(acked_packet_count), sampler_.total_bytes_acked());
EXPECT_EQ(PacketsToBytes(i), send_time_state.total_bytes_sent);
if (i <= 5) {
EXPECT_EQ(0u, send_time_state.total_bytes_acked);
EXPECT_EQ(0u, send_time_state.total_bytes_lost);
} else {
EXPECT_EQ(PacketsToBytes(1), send_time_state.total_bytes_acked);
EXPECT_EQ(PacketsToBytes(2), send_time_state.total_bytes_lost);
}
EXPECT_EQ(send_time_state.total_bytes_sent -
send_time_state.total_bytes_acked -
send_time_state.total_bytes_lost,
send_time_state.bytes_in_flight);
clock_.AdvanceTime(time_between_packets);
}
}
TEST_P(BandwidthSamplerTest, SendPaced) {
const QuicTime::Delta time_between_packets =
QuicTime::Delta::FromMilliseconds(1);
QuicBandwidth expected_bandwidth =
QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize);
Send40PacketsAndAckFirst20(time_between_packets);
QuicBandwidth last_bandwidth = QuicBandwidth::Zero();
for (int i = 21; i <= 40; i++) {
last_bandwidth = AckPacket(i);
EXPECT_EQ(expected_bandwidth, last_bandwidth) << "i is " << i;
clock_.AdvanceTime(time_between_packets);
}
sampler_.RemoveObsoletePackets(QuicPacketNumber(41));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
EXPECT_EQ(0u, bytes_in_flight_);
}
TEST_P(BandwidthSamplerTest, SendWithLosses) {
const QuicTime::Delta time_between_packets =
QuicTime::Delta::FromMilliseconds(1);
QuicBandwidth expected_bandwidth =
QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize) * 0.5;
for (int i = 1; i <= 20; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
}
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
AckPacket(i);
} else {
LosePacket(i);
}
SendPacket(i + 20);
clock_.AdvanceTime(time_between_packets);
}
QuicBandwidth last_bandwidth = QuicBandwidth::Zero();
for (int i = 21; i <= 40; i++) {
if (i % 2 == 0) {
last_bandwidth = AckPacket(i);
EXPECT_EQ(expected_bandwidth, last_bandwidth);
} else {
LosePacket(i);
}
clock_.AdvanceTime(time_between_packets);
}
sampler_.RemoveObsoletePackets(QuicPacketNumber(41));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
EXPECT_EQ(0u, bytes_in_flight_);
}
TEST_P(BandwidthSamplerTest, NotCongestionControlled) {
const QuicTime::Delta time_between_packets =
QuicTime::Delta::FromMilliseconds(1);
QuicBandwidth expected_bandwidth =
QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize) * 0.5;
for (int i = 1; i <= 20; i++) {
SendPacketInner(
i, kRegularPacketSize,
i % 2 == 0 ? HAS_RETRANSMITTABLE_DATA : NO_RETRANSMITTABLE_DATA);
clock_.AdvanceTime(time_between_packets);
}
EXPECT_EQ(10u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
AckPacket(i);
}
SendPacketInner(
i + 20, kRegularPacketSize,
i % 2 == 0 ? HAS_RETRANSMITTABLE_DATA : NO_RETRANSMITTABLE_DATA);
clock_.AdvanceTime(time_between_packets);
}
QuicBandwidth last_bandwidth = QuicBandwidth::Zero();
for (int i = 21; i <= 40; i++) {
if (i % 2 == 0) {
last_bandwidth = AckPacket(i);
EXPECT_EQ(expected_bandwidth, last_bandwidth);
}
clock_.AdvanceTime(time_between_packets);
}
sampler_.RemoveObsoletePackets(QuicPacketNumber(41));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
EXPECT_EQ(0u, bytes_in_flight_);
}
TEST_P(BandwidthSamplerTest, CompressedAck) {
const QuicTime::Delta time_between_packets =
QuicTime::Delta::FromMilliseconds(1);
QuicBandwidth expected_bandwidth =
QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize);
Send40PacketsAndAckFirst20(time_between_packets);
clock_.AdvanceTime(time_between_packets * 15);
QuicBandwidth last_bandwidth = QuicBandwidth::Zero();
QuicTime::Delta ridiculously_small_time_delta =
QuicTime::Delta::FromMicroseconds(20);
for (int i = 21; i <= 40; i++) {
last_bandwidth = AckPacket(i);
clock_.AdvanceTime(ridiculously_small_time_delta);
}
EXPECT_EQ(expected_bandwidth, last_bandwidth);
sampler_.RemoveObsoletePackets(QuicPacketNumber(41));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
EXPECT_EQ(0u, bytes_in_flight_);
}
TEST_P(BandwidthSamplerTest, ReorderedAck) {
const QuicTime::Delta time_between_packets =
QuicTime::Delta::FromMilliseconds(1);
QuicBandwidth expected_bandwidth =
QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize);
Send40PacketsAndAckFirst20(time_between_packets);
QuicBandwidth last_bandwidth = QuicBandwidth::Zero();
for (int i = 0; i < 20; i++) {
last_bandwidth = AckPacket(40 - i);
EXPECT_EQ(expected_bandwidth, last_bandwidth);
SendPacket(41 + i);
clock_.AdvanceTime(time_between_packets);
}
for (int i = 41; i <= 60; i++) {
last_bandwidth = AckPacket(i);
EXPECT_EQ(expected_bandwidth, last_bandwidth);
clock_.AdvanceTime(time_between_packets);
}
sampler_.RemoveObsoletePackets(QuicPacketNumber(61));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
EXPECT_EQ(0u, bytes_in_flight_);
}
TEST_P(BandwidthSamplerTest, AppLimited) {
const QuicTime::Delta time_between_packets =
QuicTime::Delta::FromMilliseconds(1);
QuicBandwidth expected_bandwidth =
QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize);
for (int i = 1; i <= 20; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
}
for (int i = 1; i <= 20; i++) {
BandwidthSample sample = AckPacketInner(i);
EXPECT_EQ(sample.state_at_send.is_app_limited,
sampler_app_limited_at_start_);
SendPacket(i + 20);
clock_.AdvanceTime(time_between_packets);
}
sampler_.OnAppLimited();
for (int i = 21; i <= 40; i++) {
BandwidthSample sample = AckPacketInner(i);
EXPECT_FALSE(sample.state_at_send.is_app_limited);
EXPECT_EQ(expected_bandwidth, sample.bandwidth);
clock_.AdvanceTime(time_between_packets);
}
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
for (int i = 41; i <= 60; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
}
for (int i = 41; i <= 60; i++) {
BandwidthSample sample = AckPacketInner(i);
EXPECT_TRUE(sample.state_at_send.is_app_limited);
EXPECT_LT(sample.bandwidth, 0.7f * expected_bandwidth);
SendPacket(i + 20);
clock_.AdvanceTime(time_between_packets);
}
for (int i = 61; i <= 80; i++) {
BandwidthSample sample = AckPacketInner(i);
EXPECT_FALSE(sample.state_at_send.is_app_limited);
EXPECT_EQ(sample.bandwidth, expected_bandwidth);
clock_.AdvanceTime(time_between_packets);
}
sampler_.RemoveObsoletePackets(QuicPacketNumber(81));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
EXPECT_EQ(0u, bytes_in_flight_);
}
TEST_P(BandwidthSamplerTest, FirstRoundTrip) {
const QuicTime::Delta time_between_packets =
QuicTime::Delta::FromMilliseconds(1);
const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(800);
const int num_packets = 10;
const QuicByteCount num_bytes = kRegularPacketSize * num_packets;
const QuicBandwidth real_bandwidth =
QuicBandwidth::FromBytesAndTimeDelta(num_bytes, rtt);
for (int i = 1; i <= 10; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
}
clock_.AdvanceTime(rtt - num_packets * time_between_packets);
QuicBandwidth last_sample = QuicBandwidth::Zero();
for (int i = 1; i <= 10; i++) {
QuicBandwidth sample = AckPacket(i);
EXPECT_GT(sample, last_sample);
last_sample = sample;
clock_.AdvanceTime(time_between_packets);
}
EXPECT_LT(last_sample, real_bandwidth);
EXPECT_GT(last_sample, 0.9f * real_bandwidth);
}
TEST_P(BandwidthSamplerTest, RemoveObsoletePackets) {
SendPacket(1);
SendPacket(2);
SendPacket(3);
SendPacket(4);
SendPacket(5);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
EXPECT_EQ(5u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
sampler_.RemoveObsoletePackets(QuicPacketNumber(4));
EXPECT_EQ(2u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
LosePacket(4);
sampler_.RemoveObsoletePackets(QuicPacketNumber(5));
EXPECT_EQ(1u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
AckPacket(5);
sampler_.RemoveObsoletePackets(QuicPacketNumber(6));
EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_));
}
TEST_P(BandwidthSamplerTest, NeuterPacket) {
SendPacket(1);
EXPECT_EQ(0u, sampler_.total_bytes_neutered());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
sampler_.OnPacketNeutered(QuicPacketNumber(1));
EXPECT_LT(0u, sampler_.total_bytes_neutered());
EXPECT_EQ(0u, sampler_.total_bytes_acked());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent(
clock_.Now(),
{AckedPacket(QuicPacketNumber(1), kRegularPacketSize, clock_.Now())}, {},
max_bandwidth_, est_bandwidth_upper_bound_, round_trip_count_);
EXPECT_EQ(0u, sampler_.total_bytes_acked());
EXPECT_EQ(QuicBandwidth::Zero(), sample.sample_max_bandwidth);
EXPECT_FALSE(sample.sample_is_app_limited);
EXPECT_EQ(QuicTime::Delta::Infinite(), sample.sample_rtt);
EXPECT_EQ(0u, sample.sample_max_inflight);
EXPECT_EQ(0u, sample.extra_acked);
}
TEST_P(BandwidthSamplerTest, CongestionEventSampleDefaultValues) {
BandwidthSampler::CongestionEventSample sample;
EXPECT_EQ(QuicBandwidth::Zero(), sample.sample_max_bandwidth);
EXPECT_FALSE(sample.sample_is_app_limited);
EXPECT_EQ(QuicTime::Delta::Infinite(), sample.sample_rtt);
EXPECT_EQ(0u, sample.sample_max_inflight);
EXPECT_EQ(0u, sample.extra_acked);
}
TEST_P(BandwidthSamplerTest, TwoAckedPacketsPerEvent) {
QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10);
QuicBandwidth sending_rate = QuicBandwidth::FromBytesAndTimeDelta(
kRegularPacketSize, time_between_packets);
for (uint64_t i = 1; i < 21; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
if (i % 2 != 0) {
continue;
}
BandwidthSampler::CongestionEventSample sample =
OnCongestionEvent({i - 1, i}, {});
EXPECT_EQ(sending_rate, sample.sample_max_bandwidth);
EXPECT_EQ(time_between_packets, sample.sample_rtt);
EXPECT_EQ(2 * kRegularPacketSize, sample.sample_max_inflight);
EXPECT_TRUE(sample.last_packet_send_state.is_valid);
EXPECT_EQ(2 * kRegularPacketSize,
sample.last_packet_send_state.bytes_in_flight);
EXPECT_EQ(i * kRegularPacketSize,
sample.last_packet_send_state.total_bytes_sent);
EXPECT_EQ((i - 2) * kRegularPacketSize,
sample.last_packet_send_state.total_bytes_acked);
EXPECT_EQ(0u, sample.last_packet_send_state.total_bytes_lost);
sampler_.RemoveObsoletePackets(QuicPacketNumber(i - 2));
}
}
TEST_P(BandwidthSamplerTest, LoseEveryOtherPacket) {
QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10);
QuicBandwidth sending_rate = QuicBandwidth::FromBytesAndTimeDelta(
kRegularPacketSize, time_between_packets);
for (uint64_t i = 1; i < 21; i++) {
SendPacket(i);
clock_.AdvanceTime(time_between_packets);
if (i % 2 != 0) {
continue;
}
BandwidthSampler::CongestionEventSample sample =
OnCongestionEvent({i}, {i - 1});
EXPECT_EQ(sending_rate, sample.sample_max_bandwidth * 2);
EXPECT_EQ(time_between_packets, sample.sample_rtt);
EXPECT_EQ(kRegularPacketSize, sample.sample_max_inflight);
EXPECT_TRUE(sample.last_packet_send_state.is_valid);
EXPECT_EQ(2 * kRegularPacketSize,
sample.last_packet_send_state.bytes_in_flight);
EXPECT_EQ(i * kRegularPacketSize,
sample.last_packet_send_state.total_bytes_sent);
EXPECT_EQ((i - 2) * kRegularPacketSize / 2,
sample.last_packet_send_state.total_bytes_acked);
EXPECT_EQ((i - 2) * kRegularPacketSize / 2,
sample.last_packet_send_state.total_bytes_lost);
sampler_.RemoveObsoletePackets(QuicPacketNumber(i - 2));
}
}
TEST_P(BandwidthSamplerTest, AckHeightRespectBandwidthEstimateUpperBound) {
QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10);
QuicBandwidth first_packet_sending_rate =
QuicBandwidth::FromBytesAndTimeDelta(kRegularPacketSize,
time_between_packets);
SendPacket(1);
clock_.AdvanceTime(time_between_packets);
SendPacket(2);
SendPacket(3);
SendPacket(4);
BandwidthSampler::CongestionEventSample sample = OnCongestionEvent({1}, {});
EXPECT_EQ(first_packet_sending_rate, sample.sample_max_bandwidth);
EXPECT_EQ(first_packet_sending_rate, max_bandwidth_);
round_trip_count_++;
est_bandwidth_upper_bound_ = first_packet_sending_rate * 0.3;
clock_.AdvanceTime(time_between_packets);
sample = OnCongestionEvent({2, 3, 4}, {});
EXPECT_EQ(first_packet_sending_rate * 2, sample.sample_max_bandwidth);
EXPECT_EQ(max_bandwidth_, sample.sample_max_bandwidth);
EXPECT_LT(2 * kRegularPacketSize, sample.extra_acked);
}
class MaxAckHeightTrackerTest : public QuicTest {
protected:
MaxAckHeightTrackerTest() : tracker_(10) {
tracker_.SetAckAggregationBandwidthThreshold(1.8);
tracker_.SetStartNewAggregationEpochAfterFullRound(true);
}
void AggregationEpisode(QuicBandwidth aggregation_bandwidth,
QuicTime::Delta aggregation_duration,
QuicByteCount bytes_per_ack,
bool expect_new_aggregation_epoch) {
ASSERT_GE(aggregation_bandwidth, bandwidth_);
const QuicTime start_time = now_;
const QuicByteCount aggregation_bytes =
aggregation_bandwidth * aggregation_duration;
const int num_acks = aggregation_bytes / bytes_per_ack;
ASSERT_EQ(aggregation_bytes, num_acks * bytes_per_ack)
<< "aggregation_bytes: " << aggregation_bytes << " ["
<< aggregation_bandwidth << " in " << aggregation_duration
<< "], bytes_per_ack: " << bytes_per_ack;
const QuicTime::Delta time_between_acks = QuicTime::Delta::FromMicroseconds(
aggregation_duration.ToMicroseconds() / num_acks);
ASSERT_EQ(aggregation_duration, num_acks * time_between_acks)
<< "aggregation_bytes: " << aggregation_bytes
<< ", num_acks: " << num_acks
<< ", time_between_acks: " << time_between_acks;
const QuicTime::Delta total_duration = QuicTime::Delta::FromMicroseconds(
aggregation_bytes * 8 * 1000000 / bandwidth_.ToBitsPerSecond());
ASSERT_EQ(aggregation_bytes, total_duration * bandwidth_)
<< "total_duration: " << total_duration
<< ", bandwidth_: " << bandwidth_;
QuicByteCount last_extra_acked = 0;
for (QuicByteCount bytes = 0; bytes < aggregation_bytes;
bytes += bytes_per_ack) {
QuicByteCount extra_acked = tracker_.Update(
bandwidth_, true, RoundTripCount(), last_sent_packet_number_,
last_acked_packet_number_, now_, bytes_per_ack);
QUIC_VLOG(1) << "T" << now_ << ": Update after " << bytes_per_ack
<< " bytes acked, " << extra_acked << " extra bytes acked";
if ((bytes == 0 && expect_new_aggregation_epoch) ||
(aggregation_bandwidth == bandwidth_)) {
EXPECT_EQ(0u, extra_acked);
} else {
EXPECT_LT(last_extra_acked, extra_acked);
}
now_ = now_ + time_between_acks;
last_extra_acked = extra_acked;
}
const QuicTime time_after_aggregation = now_;
now_ = start_time + total_duration;
QUIC_VLOG(1) << "Advanced time from " << time_after_aggregation << " to "
<< now_ << ". Aggregation time["
<< (time_after_aggregation - start_time) << "], Quiet time["
<< (now_ - time_after_aggregation) << "].";
}
QuicRoundTripCount RoundTripCount() const {
return (now_ - QuicTime::Zero()).ToMicroseconds() / rtt_.ToMicroseconds();
}
MaxAckHeightTracker tracker_;
QuicBandwidth bandwidth_ = QuicBandwidth::FromBytesPerSecond(10 * 1000);
QuicTime now_ = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1);
QuicTime::Delta rtt_ = QuicTime::Delta::FromMilliseconds(60);
QuicPacketNumber last_sent_packet_number_;
QuicPacketNumber last_acked_packet_number_;
};
TEST_F(MaxAckHeightTrackerTest, VeryAggregatedLargeAck) {
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6),
1200, true);
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6),
1200, true);
now_ = now_ - QuicTime::Delta::FromMilliseconds(1);
if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) {
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6),
1200, true);
EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs());
} else {
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6),
1200, false);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
TEST_F(MaxAckHeightTrackerTest, VeryAggregatedSmallAcks) {
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 300,
true);
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 300,
true);
now_ = now_ - QuicTime::Delta::FromMilliseconds(1);
if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) {
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6),
300, true);
EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs());
} else {
AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6),
300, false);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
TEST_F(MaxAckHeightTrackerTest, SomewhatAggregatedLargeAck) {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
1000, true);
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
1000, true);
now_ = now_ - QuicTime::Delta::FromMilliseconds(1);
if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
1000, true);
EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs());
} else {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
1000, false);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
TEST_F(MaxAckHeightTrackerTest, SomewhatAggregatedSmallAcks) {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 100,
true);
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 100,
true);
now_ = now_ - QuicTime::Delta::FromMilliseconds(1);
if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
100, true);
EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs());
} else {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
100, false);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
TEST_F(MaxAckHeightTrackerTest, NotAggregated) {
AggregationEpisode(bandwidth_, QuicTime::Delta::FromMilliseconds(100), 100,
true);
EXPECT_LT(2u, tracker_.num_ack_aggregation_epochs());
}
TEST_F(MaxAckHeightTrackerTest, StartNewEpochAfterAFullRound) {
last_sent_packet_number_ = QuicPacketNumber(10);
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 100,
true);
last_acked_packet_number_ = QuicPacketNumber(11);
tracker_.Update(bandwidth_ * 0.1, true, RoundTripCount(),
last_sent_packet_number_, last_acked_packet_number_, now_,
100);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/bandwidth_sampler.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/bandwidth_sampler_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
212ea646-6de4-4c3e-ac79-06511b9ea44b | cpp | google/arolla | equals_proto | arolla/util/testing/equals_proto.h | arolla/util/testing/equals_proto_test.cc | #ifndef AROLLA_UTIL_TESTING_EQUALS_PROTO_H_
#define AROLLA_UTIL_TESTING_EQUALS_PROTO_H_
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/util/message_differencer.h"
namespace arolla::testing {
template <typename TypeProto>
::testing::AssertionResult EqualsProto(const TypeProto& actual_proto,
absl::string_view expected_proto_text) {
using ::google::protobuf::TextFormat;
using ::google::protobuf::util::MessageDifferencer;
TypeProto expected_proto;
if (!TextFormat::ParseFromString(std::string(expected_proto_text),
&expected_proto)) {
return ::testing::AssertionFailure()
<< "could not parse proto: " << expected_proto_text;
}
MessageDifferencer differencer;
std::string differences;
differencer.ReportDifferencesToString(&differences);
if (!differencer.Compare(expected_proto, actual_proto)) {
return ::testing::AssertionFailure() << "the protos are different:\n"
<< differences;
}
return ::testing::AssertionSuccess();
}
inline auto EqualsProto(absl::string_view expected_proto_text) {
return ::testing::Truly([expected_proto_text = std::string(
expected_proto_text)](const auto& actual_proto) {
return EqualsProto(actual_proto, expected_proto_text);
});
}
}
#endif | #include "arolla/util/testing/equals_proto.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "arolla/util/testing/test.pb.h"
namespace arolla::testing {
namespace {
using ::testing::Not;
TEST(EqualsProtoTest, Predicate) {
{
TestProto test_proto;
EXPECT_TRUE(EqualsProto(test_proto, R"pb()pb"));
EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 0)pb"));
EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 100)pb"));
}
{
TestProto test_proto;
test_proto.set_field(0);
EXPECT_FALSE(EqualsProto(test_proto, R"pb()pb"));
EXPECT_TRUE(EqualsProto(test_proto, R"pb(field: 0)pb"));
EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 100)pb"));
}
{
TestProto test_proto;
test_proto.set_field(100);
EXPECT_FALSE(EqualsProto(test_proto, R"pb()pb"));
EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 0)pb"));
EXPECT_TRUE(EqualsProto(test_proto, R"pb(field: 100)pb"));
}
{
TestProto test_proto;
EXPECT_FALSE(EqualsProto(test_proto, R"pb(unknown_field: 0)pb"));
}
{
TestProto test_proto;
EXPECT_FALSE(EqualsProto(test_proto, "invalid text proto literal"));
}
}
TEST(EqualsProtoTest, Matcher) {
{
TestProto test_proto;
EXPECT_THAT(test_proto, EqualsProto(R"pb()pb"));
EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 0)pb")));
EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 100)pb")));
}
{
TestProto test_proto;
test_proto.set_field(0);
EXPECT_THAT(test_proto, Not(EqualsProto(R"pb()pb")));
EXPECT_THAT(test_proto, EqualsProto(R"pb(field: 0)pb"));
EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 100)pb")));
}
{
TestProto test_proto;
test_proto.set_field(100);
EXPECT_THAT(test_proto, Not(EqualsProto(R"pb()pb")));
EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 0)pb")));
EXPECT_THAT(test_proto, EqualsProto(R"pb(field: 100)pb"));
}
{
TestProto test_proto;
EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(unknown_field: 0)pb")));
}
{
TestProto test_proto;
EXPECT_THAT(test_proto, Not(EqualsProto("invalid text proto literal")));
}
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/testing/equals_proto.h | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/testing/equals_proto_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
68d21ad5-0373-4de2-8fba-27046bfbf55d | cpp | tensorflow/tensorflow | conv_2d | tensorflow/core/kernels/conv_2d.h | tensorflow/lite/delegates/xnnpack/conv_2d_test.cc | #ifndef TENSORFLOW_CORE_KERNELS_CONV_2D_H_
#define TENSORFLOW_CORE_KERNELS_CONV_2D_H_
#include "absl/strings/string_view.h"
#include "unsupported/Eigen/CXX11/Tensor"
#include "xla/tsl/framework/convolution/eigen_spatial_convolutions.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/kernels/eigen_backward_spatial_convolutions.h"
#include "tensorflow/core/util/tensor_format.h"
static bool Conv2dUseFp16Accumulate() {
static bool use_fp16_accumulate = []() {
const char* env = std::getenv("TF_CONV2D_USE_FP16_ACCUMULATE");
return (env != nullptr) && (absl::string_view(env) == "1");
}();
return use_fp16_accumulate;
}
namespace tensorflow {
namespace functor {
template <typename Device, typename Input, typename Filter, typename Output,
typename OutputKernel>
void SpatialConvolutionFunc(const Device& d, Output output, Input input,
Filter filter, int row_stride, int col_stride,
int row_dilation, int col_dilation,
const Eigen::PaddingType& padding,
const OutputKernel& output_kernel,
int padding_top = 0, int padding_bottom = 0,
int padding_left = 0, int padding_right = 0) {
output.device(d) = Eigen::SpatialConvolution(
input, filter, col_stride, row_stride, padding, col_dilation,
row_dilation, output_kernel, padding_left, padding_right, padding_top,
padding_bottom);
}
template <typename Device, typename T,
typename OutputKernel = const Eigen::NoOpOutputKernel>
struct SpatialConvolution {
void operator()(const Device& d, typename TTypes<T, 4>::Tensor output,
typename TTypes<T, 4>::ConstTensor input,
typename TTypes<T, 4>::ConstTensor filter, int row_stride,
int col_stride, int row_dilation, int col_dilation,
const Eigen::PaddingType& padding,
const OutputKernel& output_kernel = OutputKernel()) {
SpatialConvolutionFunc(d, output, input, filter, row_stride, col_stride,
row_dilation, col_dilation, padding, output_kernel);
}
template <typename Input, typename Filter, typename Output>
void operator()(const Device& d, Output output, Input input, Filter filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, const Eigen::PaddingType& padding,
const OutputKernel& output_kernel = OutputKernel()) {
SpatialConvolutionFunc(d, output, input, filter, row_stride, col_stride,
row_dilation, col_dilation, padding, output_kernel);
}
void operator()(const Device& d, typename TTypes<T, 4>::Tensor output,
typename TTypes<T, 4>::ConstTensor input,
typename TTypes<T, 4>::ConstTensor filter, int row_stride,
int col_stride, int row_dilation, int col_dilation,
int padding_top, int padding_bottom, int padding_left,
int padding_right,
const OutputKernel& output_kernel = OutputKernel()) {
SpatialConvolutionFunc(
d, output, input, filter, row_stride, col_stride, row_dilation,
col_dilation, Eigen::PaddingType::PADDING_VALID, output_kernel,
padding_top, padding_bottom, padding_left, padding_right);
}
template <typename Input, typename Filter, typename Output>
void operator()(const Device& d, Output output, Input input, Filter filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, int padding_top, int padding_bottom,
int padding_left, int padding_right,
const OutputKernel& output_kernel = OutputKernel()) {
SpatialConvolutionFunc(
d, output, input, filter, row_stride, col_stride, row_dilation,
col_dilation, Eigen::PaddingType::PADDING_VALID, output_kernel,
padding_top, padding_bottom, padding_left, padding_right);
}
};
template <typename Device, typename OutputKernel>
struct SpatialConvolution<Device, Eigen::half, OutputKernel> {
void operator()(const Device& d,
typename TTypes<Eigen::half, 4>::Tensor output,
typename TTypes<Eigen::half, 4>::ConstTensor input,
typename TTypes<Eigen::half, 4>::ConstTensor filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, const Eigen::PaddingType& padding,
const OutputKernel& output_kernel = OutputKernel()) {
if (Conv2dUseFp16Accumulate()) {
output.device(d) = Eigen::SpatialConvolution(
input, filter, col_stride, row_stride, padding, col_dilation,
row_dilation, output_kernel);
} else {
output.device(d) =
Eigen::SpatialConvolution(input.cast<float>(), filter.cast<float>(),
col_stride, row_stride, padding,
col_dilation, row_dilation, output_kernel)
.template cast<Eigen::half>();
}
}
template <typename Input, typename Filter, typename Output>
void operator()(const Device& d, Output output, Input input, Filter filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, const Eigen::PaddingType& padding,
const OutputKernel& output_kernel = OutputKernel()) {
if (Conv2dUseFp16Accumulate()) {
output.device(d) = Eigen::SpatialConvolution(
input, filter, col_stride, row_stride, padding, col_dilation,
row_dilation, output_kernel);
} else {
output.device(d) =
Eigen::SpatialConvolution(input.template cast<float>(),
filter.template cast<float>(), col_stride,
row_stride, padding, col_dilation,
row_dilation, output_kernel)
.template cast<Eigen::half>();
}
}
void operator()(const Device& d,
typename TTypes<Eigen::half, 4>::Tensor output,
typename TTypes<Eigen::half, 4>::ConstTensor input,
typename TTypes<Eigen::half, 4>::ConstTensor filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, int padding_top, int padding_bottom,
int padding_left, int padding_right,
const OutputKernel& output_kernel = OutputKernel()) {
if (Conv2dUseFp16Accumulate()) {
output.device(d) = Eigen::SpatialConvolution(
input, filter, col_stride, row_stride,
Eigen::PaddingType::PADDING_VALID, col_dilation, row_dilation,
output_kernel, padding_left, padding_right, padding_top,
padding_bottom);
} else {
output.device(d) =
Eigen::SpatialConvolution(
input.cast<float>(), filter.cast<float>(), col_stride, row_stride,
Eigen::PaddingType::PADDING_VALID, col_dilation, row_dilation,
output_kernel, padding_left, padding_right, padding_top,
padding_bottom)
.template cast<Eigen::half>();
}
}
template <typename Input, typename Filter, typename Output>
void operator()(const Device& d, Output output, Input input, Filter filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, int padding_top, int padding_bottom,
int padding_left, int padding_right,
const OutputKernel& output_kernel = OutputKernel()) {
if (Conv2dUseFp16Accumulate()) {
output.device(d) = Eigen::SpatialConvolution(
input, filter, col_stride, row_stride,
Eigen::PaddingType::PADDING_VALID, col_dilation, row_dilation,
output_kernel, padding_left, padding_right, padding_top,
padding_bottom);
} else {
output.device(d) =
Eigen::SpatialConvolution(
input.template cast<float>(), filter.template cast<float>(),
col_stride, row_stride, Eigen::PaddingType::PADDING_VALID,
col_dilation, row_dilation, output_kernel, padding_left,
padding_right, padding_top, padding_bottom)
.template cast<Eigen::half>();
}
}
};
template <typename Device, typename OutputKernel>
struct SpatialConvolution<Device, Eigen::bfloat16, OutputKernel> {
void operator()(const Device& d,
typename TTypes<Eigen::bfloat16, 4>::Tensor output,
typename TTypes<Eigen::bfloat16, 4>::ConstTensor input,
typename TTypes<Eigen::bfloat16, 4>::ConstTensor filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, const Eigen::PaddingType& padding,
const OutputKernel& output_kernel = OutputKernel()) {
output.device(d) =
Eigen::SpatialConvolution(input.cast<float>(), filter.cast<float>(),
col_stride, row_stride, padding, col_dilation,
row_dilation, output_kernel)
.template cast<Eigen::bfloat16>();
}
template <typename Input, typename Filter, typename Output>
void operator()(const Device& d, Output output, Input input, Filter filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, const Eigen::PaddingType& padding,
const OutputKernel& output_kernel = OutputKernel()) {
output.device(d) =
Eigen::SpatialConvolution(input.template cast<float>(),
filter.template cast<float>(), col_stride,
row_stride, padding, col_dilation,
row_dilation, output_kernel)
.template cast<Eigen::bfloat16>();
}
void operator()(const Device& d,
typename TTypes<Eigen::bfloat16, 4>::Tensor output,
typename TTypes<Eigen::bfloat16, 4>::ConstTensor input,
typename TTypes<Eigen::bfloat16, 4>::ConstTensor filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, int padding_top, int padding_bottom,
int padding_left, int padding_right,
const OutputKernel& output_kernel = OutputKernel()) {
output.device(d) =
Eigen::SpatialConvolution(
input.cast<float>(), filter.cast<float>(), col_stride, row_stride,
Eigen::PaddingType::PADDING_VALID, col_dilation, row_dilation,
output_kernel, padding_left, padding_right, padding_top,
padding_bottom)
.template cast<Eigen::bfloat16>();
}
template <typename Input, typename Filter, typename Output>
void operator()(const Device& d, Output output, Input input, Filter filter,
int row_stride, int col_stride, int row_dilation,
int col_dilation, int padding_top, int padding_bottom,
int padding_left, int padding_right,
const OutputKernel& output_kernel = OutputKernel()) {
output.device(d) =
Eigen::SpatialConvolution(
input.template cast<float>(), filter.template cast<float>(),
col_stride, row_stride, Eigen::PaddingType::PADDING_VALID,
col_dilation, row_dilation, output_kernel, padding_left,
padding_right, padding_top, padding_bottom)
.template cast<Eigen::bfloat16>();
}
};
template <typename Device, typename T>
struct SpatialConvolutionBackwardInputFunc {
void operator()(const Device& d, typename TTypes<T, 4>::Tensor input_backward,
typename TTypes<T, 4>::ConstTensor filter,
typename TTypes<T, 4>::ConstTensor output_backward,
Eigen::DenseIndex col_stride, Eigen::DenseIndex row_stride,
Eigen::DenseIndex col_dilation,
Eigen::DenseIndex row_dilation) {
input_backward.device(d) = Eigen::SpatialConvolutionBackwardInput(
filter, output_backward, input_backward.dimension(2),
input_backward.dimension(1), col_stride, row_stride, col_dilation,
row_dilation);
}
};
template <typename T>
struct SpatialConvolutionBackwardInputFunc<Eigen::GpuDevice, T> {
void operator()(const Eigen::GpuDevice& d,
typename TTypes<T, 4>::Tensor input_backward,
typename TTypes<T, 4>::ConstTensor filter,
typename TTypes<T, 4>::ConstTensor output_backward,
Eigen::DenseIndex col_stride, Eigen::DenseIndex row_stride,
Eigen::DenseIndex col_dilation,
Eigen::DenseIndex row_dilation) {
To32Bit(input_backward).device(d) = Eigen::SpatialConvolutionBackwardInput(
To32Bit(filter), To32Bit(output_backward), input_backward.dimension(2),
input_backward.dimension(1), col_stride, row_stride, col_dilation,
row_dilation);
}
};
template <typename Device, typename T>
struct SpatialConvolutionBackwardInputWithExplicitPaddingFunc {
void operator()(const Device& d, typename TTypes<T, 4>::Tensor input_backward,
typename TTypes<T, 4>::ConstTensor filter,
typename TTypes<T, 4>::ConstTensor output_backward,
Eigen::DenseIndex padded_cols, Eigen::DenseIndex padded_rows,
Eigen::DenseIndex col_stride, Eigen::DenseIndex row_stride,
Eigen::DenseIndex col_dilation,
Eigen::DenseIndex row_dilation, Eigen::DenseIndex pad_left,
Eigen::DenseIndex pad_top) {
input_backward.device(d) =
Eigen::SpatialConvolutionBackwardInput(
filter, output_backward, padded_cols, padded_rows, col_stride,
row_stride, col_dilation, row_dilation)
.eval()
.slice(Eigen::DSizes<Eigen::DenseIndex, 4>{0, pad_left, pad_top, 0},
input_backward.dimensions());
}
};
template <typename T>
struct SpatialConvolutionBackwardInputWithExplicitPaddingFunc<Eigen::GpuDevice,
T> {
void operator()(const Eigen::GpuDevice& d,
typename TTypes<T, 4>::Tensor input_backward,
typename TTypes<T, 4>::ConstTensor filter,
typename TTypes<T, 4>::ConstTensor output_backward,
Eigen::DenseIndex padded_cols, Eigen::DenseIndex padded_rows,
Eigen::DenseIndex col_stride, Eigen::DenseIndex row_stride,
Eigen::DenseIndex col_dilation,
Eigen::DenseIndex row_dilation, Eigen::DenseIndex pad_left,
Eigen::DenseIndex pad_top) {
To32Bit(input_backward).device(d) =
Eigen::SpatialConvolutionBackwardInput(
To32Bit(filter), To32Bit(output_backward), padded_cols, padded_rows,
col_stride, row_stride, col_dilation, row_dilation)
.eval()
.slice(Eigen::DSizes<Eigen::DenseIndex, 4>{0, pad_left, pad_top, 0},
input_backward.dimensions());
}
};
template <typename Device, typename T,
typename OutputKernel = const Eigen::NoOpOutputKernel>
struct MatMulConvFunctor {
void operator()(
const Device& d, typename TTypes<T, 2>::Tensor out,
typename TTypes<T, 2>::ConstTensor in0,
typename TTypes<T, 2>::ConstTensor in1,
const Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1>& dim_pair,
const OutputKernel& output_kernel = OutputKernel()) {
out.device(d) = in0.contract(in1, dim_pair, output_kernel);
}
};
template <typename Device, typename OutputKernel>
struct MatMulConvFunctor<Device, Eigen::half, OutputKernel> {
void operator()(
const Device& d, typename TTypes<Eigen::half, 2>::Tensor out,
typename TTypes<Eigen::half, 2>::ConstTensor in0,
typename TTypes<Eigen::half, 2>::ConstTensor in1,
const Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1>& dim_pair,
const OutputKernel& output_kernel = OutputKernel()) {
if (Conv2dUseFp16Accumulate()) {
out.device(d) = in0.contract(in1, dim_pair, output_kernel);
} else {
out.device(d) =
in0.cast<float>()
.contract(in1.template cast<float>(), dim_pair, output_kernel)
.template cast<Eigen::half>();
}
}
};
template <typename Device, typename OutputKernel>
struct MatMulConvFunctor<Device, Eigen::bfloat16, OutputKernel> {
void operator()(
const Device& d, typename TTypes<Eigen::bfloat16, 2>::Tensor out,
typename TTypes<Eigen::bfloat16, 2>::ConstTensor in0,
typename TTypes<Eigen::bfloat16, 2>::ConstTensor in1,
const Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1>& dim_pair,
const OutputKernel& output_kernel = OutputKernel()) {
out.device(d) = in0.cast<float>()
.contract(in1.cast<float>(), dim_pair, output_kernel)
.template cast<Eigen::bfloat16>();
}
};
template <typename Device, typename T, typename IndexType, int NDIMS>
struct TransformFilter {
void operator()(const Device& d, FilterTensorFormat dst_filter_format,
typename TTypes<T, NDIMS, IndexType>::ConstTensor in,
typename TTypes<T, NDIMS, IndexType>::Tensor out) {
Eigen::DSizes<IndexType, NDIMS - 2> spatial_dims;
for (int i = 0; i < spatial_dims.rank(); ++i) {
spatial_dims[i] = in.dimension(i);
}
Eigen::DSizes<IndexType, 3> merged_dims;
merged_dims[0] = spatial_dims.TotalSize();
merged_dims[1] = in.dimension(NDIMS - 2);
merged_dims[2] = in.dimension(NDIMS - 1);
Eigen::DSizes<IndexType, 3> shuffling_perm;
Eigen::DSizes<IndexType, NDIMS> expanded_dims;
if (dst_filter_format == FORMAT_OIHW) {
shuffling_perm = Eigen::DSizes<IndexType, 3>(2, 1, 0);
expanded_dims[0] = merged_dims[2];
expanded_dims[1] = merged_dims[1];
for (int i = 0; i < spatial_dims.rank(); ++i) {
expanded_dims[2 + i] = spatial_dims[i];
}
} else if (dst_filter_format == FORMAT_OHWI) {
shuffling_perm = Eigen::DSizes<IndexType, 3>(2, 0, 1);
expanded_dims[0] = merged_dims[2];
expanded_dims[NDIMS - 1] = merged_dims[1];
for (int i = 0; i < spatial_dims.rank(); ++i) {
expanded_dims[1 + i] = spatial_dims[i];
}
} else {
DCHECK(false) << "Unsupported destination filter format: "
<< ToString(dst_filter_format);
}
out.device(d) =
in.reshape(merged_dims).shuffle(shuffling_perm).reshape(expanded_dims);
}
};
template <typename Device, typename T, typename IndexType>
struct TransformDepth {
void operator()(const Device& d,
typename TTypes<T, 4, IndexType>::ConstTensor in,
const Eigen::DSizes<IndexType, 4>& shuffle,
typename TTypes<T, 4, IndexType>::Tensor out) {
Eigen::DSizes<IndexType, 3> merged_dims;
Eigen::DSizes<IndexType, 4> expanded_dims;
Eigen::DSizes<IndexType, 3> new_shuffle;
if (shuffle[1] == 2 && shuffle[2] == 3) {
merged_dims[0] = in.dimension(0);
merged_dims[1] = in.dimension(1);
merged_dims[2] = in.dimension(2) * in.dimension(3);
new_shuffle[0] = shuffle[0];
new_shuffle[1] = 2;
new_shuffle[2] = shuffle[3];
expanded_dims[0] = in.dimension(shuffle[0]);
expanded_dims[1] = in.dimension(2);
expanded_dims[2] = in.dimension(3);
expanded_dims[3] = in.dimension(shuffle[3]);
} else if (shuffle[0] == 2 && shuffle[1] == 3) {
merged_dims[0] = in.dimension(0);
merged_dims[1] = in.dimension(1);
merged_dims[2] = in.dimension(2) * in.dimension(3);
new_shuffle[0] = 2;
new_shuffle[1] = shuffle[2];
new_shuffle[2] = shuffle[3];
expanded_dims[0] = in.dimension(2);
expanded_dims[1] = in.dimension(3);
expanded_dims[2] = in.dimension(shuffle[2]);
expanded_dims[3] = in.dimension(shuffle[3]);
} else if (shuffle[0] == 0 && shuffle[1] == 3 && shuffle[2] == 1 &&
shuffle[3] == 2) {
merged_dims[0] = in.dimension(0);
merged_dims[1] = in.dimension(1) * in.dimension(2);
merged_dims[2] = in.dimension(3);
new_shuffle[0] = 0;
new_shuffle[1] = 2;
new_shuffle[2] = 1;
expanded_dims[0] = in.dimension(0);
expanded_dims[1] = in.dimension(3);
expanded_dims[2] = in.dimension(1);
expanded_dims[3] = in.dimension(2);
} else {
assert(false && "unexpected shuffle");
}
out.device(d) =
in.reshape(merged_dims).shuffle(new_shuffle).reshape(expanded_dims);
}
};
template <typename Device, typename T, typename IndexType, int NDIMS>
struct PadInput {
void operator()(const Device& d,
typename TTypes<T, NDIMS, IndexType>::ConstTensor in,
const std::array<int, NDIMS - 2>& padding_left,
const std::array<int, NDIMS - 2>& padding_right,
typename TTypes<T, NDIMS, IndexType>::Tensor out,
TensorFormat format, const T& padding_value) {
Eigen::array<Eigen::IndexPair<IndexType>, NDIMS> padding;
padding[GetTensorDimIndex<NDIMS - 2>(format, 'N')] = {0, 0};
for (int i = 0; i < NDIMS - 2; ++i) {
padding[GetTensorDimIndex<NDIMS - 2>(format, '0' + i)] = {
padding_left[i], padding_right[i]};
}
padding[GetTensorDimIndex<NDIMS - 2>(format, 'C')] = {0, 0};
out.device(d) = in.pad(padding, padding_value);
}
};
template <typename Device, typename T, int NDIMS>
struct NHWCToNCHW {
void operator()(const Device& d, typename TTypes<T, NDIMS>::ConstTensor in,
typename TTypes<T, NDIMS>::Tensor out);
};
template <typename Device, typename T, int NDIMS>
struct NCHWToNHWC {
void operator()(const Device& d, typename TTypes<T, NDIMS>::ConstTensor in,
typename TTypes<T, NDIMS>::Tensor out);
};
template <typename Device, typename T, bool conjugate = false>
struct SwapDimension1And2InTensor3 {
void operator()(const Device& d, const T* in,
const absl::Span<const int64_t>& input_dims, T* out);
};
template <typename Device, typename T, bool conjugate = false>
struct SwapDimension0And2InTensor3 {
void operator()(const Device& d, const T* in,
const absl::Span<const int64_t>& input_dims, T* out);
};
template <typename Device, typename T, int NDIMS>
struct ReverseTransformFilter {
void operator()(const Device& d, FilterTensorFormat src_filter_format,
typename TTypes<T, NDIMS>::ConstTensor in,
typename TTypes<T, NDIMS>::Tensor out);
};
}
template <class T>
class ConvAlgorithmMap;
template <>
class ConvAlgorithmMap<Eigen::ThreadPoolDevice> {};
}
#endif | #include <cstdint>
#include <functional>
#include <memory>
#include <random>
#include <gtest/gtest.h>
#include "tensorflow/lite/c/c_api_types.h"
#include "tensorflow/lite/delegates/xnnpack/conv_2d_tester.h"
#include "tensorflow/lite/delegates/xnnpack/xnnpack_delegate.h"
namespace tflite {
namespace xnnpack {
TEST(Conv2D, 1x1) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(5, 25), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(1)
.KernelWidth(1)
.ValidPadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, 3x3) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(5, 25), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(3)
.KernelWidth(3)
.SamePadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, 3x3Stride2) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(5, 25), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(3)
.KernelWidth(3)
.StrideHeight(2)
.StrideWidth(2)
.SamePadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, Grouped) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(5, 25), std::ref(rng));
auto channel_per_group_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
auto groups_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 8), std::ref(rng));
auto groups = groups_rng();
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(groups * channel_per_group_rng())
.OutputChannels(groups * channel_per_group_rng())
.Groups(groups)
.KernelHeight(3)
.KernelWidth(3)
.SamePadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, SmallKernelWithSamePadding) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 7), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.SamePadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, SmallKernelWithValidPadding) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 7), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.ValidPadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, StrideWithSamePadding) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.SamePadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, StrideWithValidPadding) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.ValidPadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, DilationWithSamePadding) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto dilation_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.DilationHeight(dilation_rng())
.DilationWidth(dilation_rng())
.SamePadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, DilationWithValidPadding) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto dilation_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.DilationHeight(dilation_rng())
.DilationWidth(dilation_rng())
.ValidPadding()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, FP16Weights) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.FP16Weights()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, TensorWiseQuantizedInt8Weights) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.TensorWiseQuantizedInt8Weights()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, ChannelWiseQuantizedInt8Weights) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.ChannelWiseQuantizedInt8Weights()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, SparseWeights) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.SparseWeights()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, SparseFP16Weights) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.SparseWeights()
.FP16Weights()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, SparseTensorWiseQuantizedInt8Weights) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.SparseWeights()
.TensorWiseQuantizedInt8Weights()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, SparseChannelWiseQuantizedInt8Weights) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.SparseWeights()
.ChannelWiseQuantizedInt8Weights()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, ReluActivation) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.ReluActivation()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, Relu6Activation) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.Relu6Activation()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, ReluMinus1To1Activation) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.ReluMinus1To1Activation()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, DISABLED_TanhActivation) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.TanhActivation()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, DISABLED_SignBitActivation) {
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(nullptr),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.SignBitActivation()
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, MultiThreading) {
TfLiteXNNPackDelegateOptions delegate_options =
TfLiteXNNPackDelegateOptionsDefault();
delegate_options.num_threads = 2;
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(&delegate_options),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, WeightsCache) {
TfLiteXNNPackDelegateOptions delegate_options =
TfLiteXNNPackDelegateOptionsDefault();
std::unique_ptr<TfLiteXNNPackDelegateWeightsCache,
decltype(&TfLiteXNNPackDelegateWeightsCacheDelete)>
weights_cache(TfLiteXNNPackDelegateWeightsCacheCreate(),
TfLiteXNNPackDelegateWeightsCacheDelete);
delegate_options.weights_cache = weights_cache.get();
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(&delegate_options),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(10, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(1, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.WeightsCache(weights_cache.get())
.Test(xnnpack_delegate.get());
}
TEST(Conv2D, TransientIndirectionBuffer) {
TfLiteXNNPackDelegateOptions xnnpack_options =
TfLiteXNNPackDelegateOptionsDefault();
xnnpack_options.num_threads = 2;
xnnpack_options.flags |=
TFLITE_XNNPACK_DELEGATE_FLAG_TRANSIENT_INDIRECTION_BUFFER;
std::unique_ptr<TfLiteDelegate, decltype(&TfLiteXNNPackDelegateDelete)>
xnnpack_delegate(TfLiteXNNPackDelegateCreate(&xnnpack_options),
TfLiteXNNPackDelegateDelete);
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto batch_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 4), std::ref(rng));
auto input_rng =
std::bind(std::uniform_int_distribution<int32_t>(5, 25), std::ref(rng));
auto kernel_rng =
std::bind(std::uniform_int_distribution<int32_t>(3, 5), std::ref(rng));
auto stride_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 3), std::ref(rng));
auto channel_rng =
std::bind(std::uniform_int_distribution<int32_t>(2, 16), std::ref(rng));
Conv2DTester()
.BatchSize(batch_rng())
.InputHeight(input_rng())
.InputWidth(input_rng())
.InputChannels(channel_rng())
.OutputChannels(channel_rng())
.KernelHeight(kernel_rng())
.KernelWidth(kernel_rng())
.StrideHeight(stride_rng())
.StrideWidth(stride_rng())
.Test(xnnpack_delegate.get());
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/conv_2d.h | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/xnnpack/conv_2d_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
6aadb0b1-e600-47f6-ac26-d99cf7ea00cd | cpp | tensorflow/tensorflow | histogram | third_party/xla/xla/tsl/lib/histogram/histogram.cc | third_party/xla/xla/tsl/lib/histogram/histogram_test.cc | #include "xla/tsl/lib/histogram/histogram.h"
#include <float.h>
#include <math.h>
#include <vector>
#include "xla/tsl/protobuf/histogram.pb.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace histogram {
static std::vector<double>* InitDefaultBucketsInner() {
std::vector<double> buckets;
std::vector<double> neg_buckets;
double v = 1.0e-12;
while (v < 1.0e20) {
buckets.push_back(v);
neg_buckets.push_back(-v);
v *= 1.1;
}
buckets.push_back(DBL_MAX);
neg_buckets.push_back(-DBL_MAX);
std::reverse(neg_buckets.begin(), neg_buckets.end());
std::vector<double>* result = new std::vector<double>;
result->insert(result->end(), neg_buckets.begin(), neg_buckets.end());
result->push_back(0.0);
result->insert(result->end(), buckets.begin(), buckets.end());
return result;
}
static absl::Span<const double> InitDefaultBuckets() {
static std::vector<double>* default_bucket_limits = InitDefaultBucketsInner();
return *default_bucket_limits;
}
Histogram::Histogram() : bucket_limits_(InitDefaultBuckets()) { Clear(); }
Histogram::Histogram(absl::Span<const double> custom_bucket_limits)
: custom_bucket_limits_(custom_bucket_limits.begin(),
custom_bucket_limits.end()),
bucket_limits_(custom_bucket_limits_) {
#ifndef NDEBUG
DCHECK_GT(bucket_limits_.size(), size_t{0});
for (size_t i = 1; i < bucket_limits_.size(); i++) {
DCHECK_GT(bucket_limits_[i], bucket_limits_[i - 1]);
}
#endif
Clear();
}
bool Histogram::DecodeFromProto(const HistogramProto& proto) {
if ((proto.bucket_size() != proto.bucket_limit_size()) ||
(proto.bucket_size() == 0)) {
return false;
}
min_ = proto.min();
max_ = proto.max();
num_ = proto.num();
sum_ = proto.sum();
sum_squares_ = proto.sum_squares();
custom_bucket_limits_.clear();
custom_bucket_limits_.insert(custom_bucket_limits_.end(),
proto.bucket_limit().begin(),
proto.bucket_limit().end());
bucket_limits_ = custom_bucket_limits_;
buckets_.clear();
buckets_.insert(buckets_.end(), proto.bucket().begin(), proto.bucket().end());
return true;
}
void Histogram::Clear() {
min_ = bucket_limits_[bucket_limits_.size() - 1];
max_ = -DBL_MAX;
num_ = 0;
sum_ = 0;
sum_squares_ = 0;
buckets_.resize(bucket_limits_.size());
for (size_t i = 0; i < bucket_limits_.size(); i++) {
buckets_[i] = 0;
}
}
void Histogram::Add(double value) {
int b =
std::upper_bound(bucket_limits_.begin(), bucket_limits_.end(), value) -
bucket_limits_.begin();
buckets_[b] += 1.0;
if (min_ > value) min_ = value;
if (max_ < value) max_ = value;
num_++;
sum_ += value;
sum_squares_ += (value * value);
}
double Histogram::Median() const { return Percentile(50.0); }
double Histogram::Remap(double x, double x0, double x1, double y0,
double y1) const {
return y0 + (x - x0) / (x1 - x0) * (y1 - y0);
}
double Histogram::Percentile(double p) const {
if (num_ == 0.0) return 0.0;
double threshold = num_ * (p / 100.0);
double cumsum_prev = 0;
for (size_t i = 0; i < buckets_.size(); i++) {
double cumsum = cumsum_prev + buckets_[i];
if (cumsum >= threshold) {
if (cumsum == cumsum_prev) {
continue;
}
double lhs = (i == 0 || cumsum_prev == 0) ? min_ : bucket_limits_[i - 1];
lhs = std::max(lhs, min_);
double rhs = bucket_limits_[i];
rhs = std::min(rhs, max_);
double weight = Remap(threshold, cumsum_prev, cumsum, lhs, rhs);
return weight;
}
cumsum_prev = cumsum;
}
return max_;
}
double Histogram::Average() const {
if (num_ == 0.0) return 0;
return sum_ / num_;
}
double Histogram::StandardDeviation() const {
if (num_ == 0.0) return 0;
double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_);
return sqrt(variance);
}
std::string Histogram::ToString() const {
std::string r;
char buf[200];
snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n", num_,
Average(), StandardDeviation());
r.append(buf);
snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n",
(num_ == 0.0 ? 0.0 : min_), Median(), max_);
r.append(buf);
r.append("------------------------------------------------------\n");
const double mult = num_ > 0 ? 100.0 / num_ : 0.0;
double sum = 0;
for (size_t b = 0; b < buckets_.size(); b++) {
if (buckets_[b] <= 0.0) continue;
sum += buckets_[b];
snprintf(buf, sizeof(buf), "[ %10.2g, %10.2g ) %7.0f %7.3f%% %7.3f%% ",
((b == 0) ? -DBL_MAX : bucket_limits_[b - 1]),
bucket_limits_[b],
buckets_[b],
mult * buckets_[b],
mult * sum);
r.append(buf);
int marks = static_cast<int>(20 * (buckets_[b] / num_) + 0.5);
r.append(marks, '#');
r.push_back('\n');
}
return r;
}
void Histogram::EncodeToProto(HistogramProto* proto,
bool preserve_zero_buckets) const {
proto->Clear();
proto->set_min(min_);
proto->set_max(max_);
proto->set_num(num_);
proto->set_sum(sum_);
proto->set_sum_squares(sum_squares_);
for (size_t i = 0; i < buckets_.size();) {
double end = bucket_limits_[i];
double count = buckets_[i];
i++;
if (!preserve_zero_buckets && count <= 0.0) {
while (i < buckets_.size() && buckets_[i] <= 0.0) {
end = bucket_limits_[i];
count = buckets_[i];
i++;
}
}
proto->add_bucket_limit(end);
proto->add_bucket(count);
}
if (proto->bucket_size() == 0.0) {
proto->add_bucket_limit(DBL_MAX);
proto->add_bucket(0.0);
}
}
bool ThreadSafeHistogram::DecodeFromProto(const HistogramProto& proto) {
mutex_lock l(mu_);
return histogram_.DecodeFromProto(proto);
}
void ThreadSafeHistogram::Clear() {
mutex_lock l(mu_);
histogram_.Clear();
}
void ThreadSafeHistogram::Add(double value) {
mutex_lock l(mu_);
histogram_.Add(value);
}
void ThreadSafeHistogram::EncodeToProto(HistogramProto* proto,
bool preserve_zero_buckets) const {
mutex_lock l(mu_);
histogram_.EncodeToProto(proto, preserve_zero_buckets);
}
double ThreadSafeHistogram::Median() const {
mutex_lock l(mu_);
return histogram_.Median();
}
double ThreadSafeHistogram::Percentile(double p) const {
mutex_lock l(mu_);
return histogram_.Percentile(p);
}
double ThreadSafeHistogram::Average() const {
mutex_lock l(mu_);
return histogram_.Average();
}
double ThreadSafeHistogram::StandardDeviation() const {
mutex_lock l(mu_);
return histogram_.StandardDeviation();
}
std::string ThreadSafeHistogram::ToString() const {
mutex_lock l(mu_);
return histogram_.ToString();
}
}
} | #include "xla/tsl/lib/histogram/histogram.h"
#include <float.h>
#include "xla/tsl/protobuf/histogram.pb.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace histogram {
static void Validate(const Histogram& h) {
string s1 = h.ToString();
LOG(ERROR) << s1;
HistogramProto proto_with_zeroes;
h.EncodeToProto(&proto_with_zeroes, true);
Histogram h2;
EXPECT_TRUE(h2.DecodeFromProto(proto_with_zeroes));
string s2 = h2.ToString();
LOG(ERROR) << s2;
EXPECT_EQ(s1, s2);
HistogramProto proto_no_zeroes;
h.EncodeToProto(&proto_no_zeroes, false);
LOG(ERROR) << proto_no_zeroes.DebugString();
Histogram h3;
EXPECT_TRUE(h3.DecodeFromProto(proto_no_zeroes));
string s3 = h3.ToString();
LOG(ERROR) << s3;
EXPECT_EQ(s1, s3);
}
TEST(Histogram, Empty) {
Histogram h;
Validate(h);
}
TEST(Histogram, SingleValue) {
Histogram h;
h.Add(-3.0);
Validate(h);
}
TEST(Histogram, CustomBuckets) {
Histogram h({-10, -5, 0, 5, 10, 100, 1000, 10000, DBL_MAX});
h.Add(-3.0);
h.Add(4.99);
h.Add(5.0);
h.Add(1000.0);
Validate(h);
}
TEST(Histogram, Median) {
Histogram h({0, 10, 100, DBL_MAX});
h.Add(-2);
h.Add(-2);
h.Add(0);
double median = h.Median();
EXPECT_EQ(median, -0.5);
}
TEST(Histogram, Percentile) {
Histogram h({1, 2, 3, 4});
h.Add(-1.0);
h.Add(1.5);
h.Add(1.5);
h.Add(1.5);
h.Add(2.5);
h.Add(2.5);
h.Add(2.5);
h.Add(2.5);
h.Add(3.5);
h.Add(3.9);
EXPECT_EQ(h.Percentile(0), -1.0);
EXPECT_EQ(h.Percentile(25), 1.5);
EXPECT_EQ(h.Percentile(50), 2.25);
EXPECT_EQ(h.Percentile(75), 2.875);
EXPECT_EQ(h.Percentile(90), 3.45);
EXPECT_EQ(h.Percentile(100), 3.9);
}
TEST(Histogram, Basic) {
Histogram h;
for (int i = 0; i < 100; i++) {
h.Add(i);
}
for (int i = 1000; i < 100000; i += 1000) {
h.Add(i);
}
Validate(h);
}
TEST(ThreadSafeHistogram, Basic) {
Histogram h;
for (int i = 0; i < 100; i++) {
h.Add(i);
}
ThreadSafeHistogram tsh;
for (int i = 0; i < 100; i++) {
tsh.Add(i);
}
for (int i = 0; i < 2; ++i) {
bool preserve_zero_buckets = (i == 0);
HistogramProto h_proto;
h.EncodeToProto(&h_proto, preserve_zero_buckets);
HistogramProto tsh_proto;
tsh.EncodeToProto(&tsh_proto, preserve_zero_buckets);
Histogram h2;
EXPECT_TRUE(h2.DecodeFromProto(tsh_proto));
ThreadSafeHistogram tsh2;
EXPECT_TRUE(tsh2.DecodeFromProto(h_proto));
EXPECT_EQ(h2.ToString(), tsh2.ToString());
}
EXPECT_EQ(h.Median(), tsh.Median());
EXPECT_EQ(h.Percentile(40.0), tsh.Percentile(40.0));
EXPECT_EQ(h.Average(), tsh.Average());
EXPECT_EQ(h.StandardDeviation(), tsh.StandardDeviation());
EXPECT_EQ(h.ToString(), tsh.ToString());
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tsl/lib/histogram/histogram.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tsl/lib/histogram/histogram_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
94ed2b30-ae08-4f42-b4db-a5d14276453a | cpp | tensorflow/tensorflow | file_lock | tensorflow/lite/experimental/acceleration/mini_benchmark/file_lock.cc | tensorflow/lite/experimental/acceleration/mini_benchmark/file_lock_test.cc | #include "tensorflow/lite/experimental/acceleration/mini_benchmark/file_lock.h"
#ifndef _WIN32
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <string>
namespace tflite {
namespace acceleration {
bool FileLock::TryLock() {
#ifndef _WIN32
if (fd_ < 0) {
fd_ = open(path_.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600);
}
if (fd_ < 0) {
return false;
}
if (flock(fd_, LOCK_EX | LOCK_NB) == 0) {
return true;
}
#endif
return false;
}
}
} | #include "tensorflow/lite/experimental/acceleration/mini_benchmark/file_lock.h"
#include <csignal>
#include <iostream>
#include <string>
#include <utility>
#include <gtest/gtest.h>
namespace tflite {
namespace acceleration {
namespace {
class FileLockTest : public ::testing::Test {
protected:
void SetUp() override { file_path_ = ::testing::TempDir() + "/file_lock"; }
std::string file_path_;
};
TEST_F(FileLockTest, CanLock) { EXPECT_TRUE(FileLock(file_path_).TryLock()); }
TEST_F(FileLockTest, FailIfLockMoreThanOnce) {
FileLock lock_one(file_path_);
FileLock lock_two(file_path_);
ASSERT_TRUE(lock_one.TryLock());
EXPECT_FALSE(lock_two.TryLock());
}
TEST_F(FileLockTest, LockReleasedWhenThreadCrash) {
pid_t pid = fork();
if (pid == 0) {
FileLock lock(file_path_);
if (!lock.TryLock()) {
_exit(1);
}
std::cout << "Lock acquired successfully.";
kill(getpid(), SIGKILL);
}
int wstatus;
int w = waitpid(pid, &wstatus, WUNTRACED);
ASSERT_NE(w, -1);
FileLock lock_two(file_path_);
EXPECT_TRUE(lock_two.TryLock());
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/experimental/acceleration/mini_benchmark/file_lock.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/experimental/acceleration/mini_benchmark/file_lock_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
95e96d4b-b827-4843-9abd-3d2159c0edd0 | cpp | tensorflow/tensorflow | shape_ops | tensorflow/core/kernels/shape_ops.cc | tensorflow/core/kernels/shape_ops_test.cc | #include "tensorflow/core/kernels/shape_ops.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/register_types.h"
namespace tensorflow {
REGISTER_KERNEL_BUILDER(Name("Shape")
.Device(DEVICE_CPU)
.HostMemory("output")
.TypeConstraint<int32>("out_type"),
ShapeOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Shape")
.Device(DEVICE_CPU)
.HostMemory("output")
.TypeConstraint<int64_t>("out_type"),
ShapeOp<int64_t>);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Shape") \
.Device(DEVICE_GPU) \
.HostMemory("output") \
.TypeConstraint<int32>("out_type") \
.TypeConstraint<type>("T"), \
ShapeOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("Shape") \
.Device(DEVICE_GPU) \
.HostMemory("output") \
.TypeConstraint<int64_t>("out_type") \
.TypeConstraint<type>("T"), \
ShapeOp<int64_t>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_bool(REGISTER_GPU_KERNEL);
TF_CALL_variant(REGISTER_GPU_KERNEL);
TF_CALL_tstring(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
REGISTER_KERNEL_BUILDER(Name("Shape")
.Device(DEVICE_GPU)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_type"),
ShapeOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Shape")
.Device(DEVICE_GPU)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("out_type"),
ShapeOp<int64_t>);
#endif
#define REGISTER_DEFAULT_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Shape") \
.Device(DEVICE_DEFAULT) \
.HostMemory("output") \
.TypeConstraint<int32>("out_type") \
.TypeConstraint<type>("T"), \
ShapeOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("Shape") \
.Device(DEVICE_DEFAULT) \
.HostMemory("output") \
.TypeConstraint<int64_t>("out_type") \
.TypeConstraint<type>("T"), \
ShapeOp<int64_t>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_DEFAULT_KERNEL);
TF_CALL_bool(REGISTER_DEFAULT_KERNEL);
TF_CALL_variant(REGISTER_DEFAULT_KERNEL);
#undef REGISTER_DEFAULT_KERNEL
REGISTER_KERNEL_BUILDER(Name("Shape")
.Device(DEVICE_DEFAULT)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_type"),
ShapeOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Shape")
.Device(DEVICE_DEFAULT)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("out_type"),
ShapeOp<int64_t>);
REGISTER_KERNEL_BUILDER(Name("ShapeN")
.Device(DEVICE_CPU)
.HostMemory("output")
.TypeConstraint<int32>("out_type"),
ShapeNOp<int32>);
REGISTER_KERNEL_BUILDER(Name("ShapeN")
.Device(DEVICE_CPU)
.HostMemory("output")
.TypeConstraint<int64_t>("out_type"),
ShapeNOp<int64_t>);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("ShapeN") \
.Device(DEVICE_GPU) \
.HostMemory("output") \
.TypeConstraint<int32>("out_type") \
.TypeConstraint<type>("T"), \
ShapeNOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("ShapeN") \
.Device(DEVICE_GPU) \
.HostMemory("output") \
.TypeConstraint<int64_t>("out_type") \
.TypeConstraint<type>("T"), \
ShapeNOp<int64_t>)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_bool(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
REGISTER_KERNEL_BUILDER(Name("ShapeN")
.Device(DEVICE_GPU)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_type"),
ShapeNOp<int32>);
REGISTER_KERNEL_BUILDER(Name("ShapeN")
.Device(DEVICE_GPU)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("out_type"),
ShapeNOp<int64_t>);
#endif
#define REGISTER_DEFAULT_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("ShapeN") \
.Device(DEVICE_DEFAULT) \
.HostMemory("output") \
.TypeConstraint<int32>("out_type") \
.TypeConstraint<type>("T"), \
ShapeNOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("ShapeN") \
.Device(DEVICE_DEFAULT) \
.HostMemory("output") \
.TypeConstraint<int64_t>("out_type") \
.TypeConstraint<type>("T"), \
ShapeNOp<int64_t>)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_DEFAULT_KERNEL);
TF_CALL_bool(REGISTER_DEFAULT_KERNEL);
#undef REGISTER_DEFAULT_KERNEL
REGISTER_KERNEL_BUILDER(Name("ShapeN")
.Device(DEVICE_DEFAULT)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_type"),
ShapeNOp<int32>);
REGISTER_KERNEL_BUILDER(Name("ShapeN")
.Device(DEVICE_DEFAULT)
.HostMemory("input")
.HostMemory("output")
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("out_type"),
ShapeNOp<int64_t>);
REGISTER_KERNEL_BUILDER(Name("Rank").Device(DEVICE_CPU).HostMemory("output"),
RankOp);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Rank") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.HostMemory("output"), \
RankOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_variant(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
REGISTER_KERNEL_BUILDER(Name("Rank")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.HostMemory("input")
.HostMemory("output"),
RankOp);
REGISTER_KERNEL_BUILDER(Name("Rank")
.Device(DEVICE_GPU)
.TypeConstraint<bool>("T")
.HostMemory("input")
.HostMemory("output"),
RankOp);
#endif
#define REGISTER_DEFAULT_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Rank") \
.Device(DEVICE_DEFAULT) \
.TypeConstraint<type>("T") \
.HostMemory("output"), \
RankOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_DEFAULT_KERNEL);
TF_CALL_variant(REGISTER_DEFAULT_KERNEL);
#undef REGISTER_DEFAULT_KERNEL
REGISTER_KERNEL_BUILDER(Name("Rank")
.Device(DEVICE_DEFAULT)
.TypeConstraint<int32>("T")
.HostMemory("input")
.HostMemory("output"),
RankOp);
REGISTER_KERNEL_BUILDER(Name("Rank")
.Device(DEVICE_DEFAULT)
.TypeConstraint<bool>("T")
.HostMemory("input")
.HostMemory("output"),
RankOp);
REGISTER_KERNEL_BUILDER(Name("Size")
.Device(DEVICE_CPU)
.HostMemory("output")
.TypeConstraint<int32>("out_type"),
SizeOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Size")
.Device(DEVICE_CPU)
.HostMemory("output")
.TypeConstraint<int64_t>("out_type"),
SizeOp<int64_t>);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Size") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_type") \
.HostMemory("output"), \
SizeOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("Size") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64_t>("out_type") \
.HostMemory("output"), \
SizeOp<int64_t>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_bool(REGISTER_GPU_KERNEL);
TF_CALL_variant(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
REGISTER_KERNEL_BUILDER(Name("Size")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_type")
.HostMemory("input")
.HostMemory("output"),
SizeOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Size")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("out_type")
.HostMemory("input")
.HostMemory("output"),
SizeOp<int64_t>);
#endif
#define REGISTER_DEFAULT_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Size") \
.Device(DEVICE_DEFAULT) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_type") \
.HostMemory("output"), \
SizeOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("Size") \
.Device(DEVICE_DEFAULT) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64_t>("out_type") \
.HostMemory("output"), \
SizeOp<int64_t>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_DEFAULT_KERNEL);
TF_CALL_bool(REGISTER_DEFAULT_KERNEL);
TF_CALL_variant(REGISTER_DEFAULT_KERNEL);
#undef REGISTER_DEFAULT_KERNEL
REGISTER_KERNEL_BUILDER(Name("Size")
.Device(DEVICE_DEFAULT)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_type")
.HostMemory("input")
.HostMemory("output"),
SizeOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Size")
.Device(DEVICE_DEFAULT)
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("out_type")
.HostMemory("input")
.HostMemory("output"),
SizeOp<int64_t>);
REGISTER_KERNEL_BUILDER(Name("ExpandDims")
.Device(DEVICE_CPU)
.HostMemory("dim")
.TypeConstraint<int32>("Tdim"),
ExpandDimsOp<int32>);
REGISTER_KERNEL_BUILDER(Name("ExpandDims")
.Device(DEVICE_CPU)
.HostMemory("dim")
.TypeConstraint<int64_t>("Tdim"),
ExpandDimsOp<int64_t>);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("ExpandDims") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tdim") \
.HostMemory("dim"), \
ExpandDimsOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("ExpandDims") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64_t>("Tdim") \
.HostMemory("dim"), \
ExpandDimsOp<int64_t>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_bool(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
REGISTER_KERNEL_BUILDER(Name("ExpandDims")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("Tdim")
.HostMemory("input")
.HostMemory("dim")
.HostMemory("output"),
ExpandDimsOp<int32>);
REGISTER_KERNEL_BUILDER(Name("ExpandDims")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("Tdim")
.HostMemory("input")
.HostMemory("dim")
.HostMemory("output"),
ExpandDimsOp<int64_t>);
#endif
#define REGISTER_DEFAULT_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("ExpandDims") \
.Device(DEVICE_DEFAULT) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tdim") \
.HostMemory("dim"), \
ExpandDimsOp<int32>); \
REGISTER_KERNEL_BUILDER(Name("ExpandDims") \
.Device(DEVICE_DEFAULT) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64_t>("Tdim") \
.HostMemory("dim"), \
ExpandDimsOp<int64_t>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_DEFAULT_KERNEL);
TF_CALL_bool(REGISTER_DEFAULT_KERNEL);
#undef REGISTER_DEFAULT_KERNEL
REGISTER_KERNEL_BUILDER(Name("ExpandDims")
.Device(DEVICE_DEFAULT)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("Tdim")
.HostMemory("input")
.HostMemory("dim")
.HostMemory("output"),
ExpandDimsOp<int32>);
REGISTER_KERNEL_BUILDER(Name("ExpandDims")
.Device(DEVICE_DEFAULT)
.TypeConstraint<int32>("T")
.TypeConstraint<int64_t>("Tdim")
.HostMemory("input")
.HostMemory("dim")
.HostMemory("output"),
ExpandDimsOp<int64_t>);
REGISTER_KERNEL_BUILDER(Name("Squeeze").Device(DEVICE_CPU), SqueezeOp);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Squeeze").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
SqueezeOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_bool(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
REGISTER_KERNEL_BUILDER(Name("Squeeze")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.HostMemory("input")
.HostMemory("output"),
SqueezeOp);
#endif
#define REGISTER_DEFAULT_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Squeeze").Device(DEVICE_DEFAULT).TypeConstraint<type>("T"), \
SqueezeOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_DEFAULT_KERNEL);
TF_CALL_bool(REGISTER_DEFAULT_KERNEL);
#undef REGISTER_DEFAULT_KERNEL
REGISTER_KERNEL_BUILDER(Name("Squeeze")
.Device(DEVICE_DEFAULT)
.TypeConstraint<int32>("T")
.HostMemory("input")
.HostMemory("output"),
SqueezeOp);
class EnsureShapeOp : public OpKernel {
public:
explicit EnsureShapeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("shape", &expected_shape_));
}
void Compute(OpKernelContext* ctx) override {
TensorShape shape;
OP_REQUIRES_OK(ctx, shape_op_helpers::GetShape(ctx, 0, &shape));
if (!expected_shape_.IsCompatibleWith(shape)) {
ctx->SetStatus(errors::InvalidArgument(
"Shape of tensor ", this->def().input(0), " ", shape.DebugString(),
" is not compatible with expected shape ",
expected_shape_.DebugString(), "."));
}
if (IsRefType(ctx->input_dtype(0))) {
ctx->forward_ref_input_to_ref_output(0, 0);
} else {
ctx->set_output(0, ctx->input(0));
}
}
bool IsExpensive() override { return false; }
private:
PartialTensorShape expected_shape_;
};
REGISTER_KERNEL_BUILDER(Name("EnsureShape").Device(DEVICE_CPU), EnsureShapeOp);
#define REGISTER_DEVICE_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("EnsureShape").Device(DEVICE_DEFAULT).TypeConstraint<type>("T"), \
EnsureShapeOp)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_DEVICE_KERNEL);
REGISTER_DEVICE_KERNEL(Variant);
#undef REGISTER_DEVICE_KERNEL
#define REGISTER_DEVICE_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("EnsureShape") \
.Device(DEVICE_DEFAULT) \
.HostMemory("input") \
.HostMemory("output") \
.TypeConstraint<type>("T"), \
EnsureShapeOp)
REGISTER_DEVICE_HOST_KERNEL(int32);
REGISTER_DEVICE_HOST_KERNEL(bool);
REGISTER_DEVICE_HOST_KERNEL(tstring);
REGISTER_DEVICE_HOST_KERNEL(ResourceHandle);
#undef REGISTER_DEVICE_HOST_KERNEL
} | #include <functional>
#include <memory>
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/testlib.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
namespace {
static void BM_ExpandDims(::testing::benchmark::State& state) {
Graph* g = new Graph(OpRegistry::Global());
Tensor input(DT_INT32, TensorShape({1, 1, 1, 1}));
input.flat<int32>()(0) = 10;
Tensor axis(DT_INT32, TensorShape({}));
axis.flat<int32>()(0) = 2;
Node* node;
TF_CHECK_OK(NodeBuilder(g->NewName("n"), "ExpandDims")
.Input(test::graph::Constant(g, input))
.Input(test::graph::Constant(g, axis))
.Attr("T", DT_INT32)
.Attr("Tdim", DT_INT32)
.Finalize(g, &node));
FixupSourceAndSinkEdges(g);
test::Benchmark("cpu", g, nullptr, nullptr, nullptr,
"SINGLE_THREADED_EXECUTOR", false)
.Run(state);
}
BENCHMARK(BM_ExpandDims)->UseRealTime();
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/shape_ops.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/shape_ops_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
5167545a-1fdc-49e1-b624-b69e33f648e6 | cpp | google/arolla | presence | arolla/expr/optimization/peephole_optimizations/presence.cc | arolla/expr/optimization/peephole_optimizations/presence_test.cc | #include "arolla/expr/optimization/peephole_optimizations/presence.h"
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_node.h"
#include "arolla/expr/optimization/peephole_optimizer.h"
#include "arolla/memory/optional_value.h"
#include "arolla/qtype/base_types.h"
#include "arolla/qtype/optional_qtype.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/standard_type_properties/properties.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr {
namespace presence_impl {
bool IsPresenceType(const ExprNodePtr& expr) {
QTypePtr qtype = expr->qtype();
return qtype != nullptr && qtype == GetPresenceQType(qtype).value_or(nullptr);
}
bool IsAlwaysPresentType(const ExprNodePtr& expr) {
return IsScalarQType(expr->qtype());
}
bool IsAlwaysPresentOptionalValue(const ExprNodePtr& expr) {
const auto& optional_qvalue = expr->qvalue();
return optional_qvalue.has_value() &&
IsOptionalQType(optional_qvalue->GetType()) &&
UnsafeIsPresent(optional_qvalue->AsRef());
}
bool IsAlwaysPresent(const ExprNodePtr& expr) {
return IsAlwaysPresentType(expr) || IsAlwaysPresentOptionalValue(expr);
}
bool IsAlwaysAbsentOptionalValue(const ExprNodePtr& expr) {
const auto& optional_qvalue = expr->qvalue();
return optional_qvalue.has_value() &&
IsOptionalQType(optional_qvalue->GetType()) &&
!UnsafeIsPresent(optional_qvalue->AsRef());
}
}
namespace {
using ::arolla::expr::presence_impl::IsAlwaysAbsentOptionalValue;
using ::arolla::expr::presence_impl::IsAlwaysPresent;
using ::arolla::expr::presence_impl::IsAlwaysPresentOptionalValue;
using ::arolla::expr::presence_impl::IsAlwaysPresentType;
using ::arolla::expr::presence_impl::IsPresenceType;
bool IsLiteral(const ExprNodePtr& node) { return node->is_literal(); }
bool IsOptionalLikeNode(const ExprNodePtr& node) {
QTypePtr qtype = node->qtype();
return qtype != nullptr && IsOptionalLikeQType(qtype);
}
bool IsBaseQType(const ExprNodePtr& node) {
return IsScalarQType(DecayOptionalQType(node->qtype()));
}
absl::Status HasRemovalOptimizations(PeepholeOptimizationPack& optimizations) {
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.has._optional", {Placeholder("a")}));
ExprNodePtr to = Literal(kPresent);
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", IsAlwaysPresentOptionalValue}}));
}
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.presence_not._builtin",
{CallOpReference("core.has._optional",
{Placeholder("a")})}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core.presence_not", {Placeholder("a")}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(from, to));
}
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.presence_not._builtin",
{CallOpReference("core.has._array",
{Placeholder("a")})}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core.presence_not", {Placeholder("a")}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(from, to));
}
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference(
"core.has._optional",
{CallOpReference("core.to_optional._scalar", {Placeholder("a")})}));
ExprNodePtr to = Literal(kPresent);
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", IsAlwaysPresentType}}));
}
return absl::OkStatus();
}
absl::Status PresenceAndRemovalOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.presence_and", {a, b}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, a, {{"b", IsAlwaysPresentType}}));
}
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference("core.presence_not._builtin",
{CallOpReference("core.presence_and", {a, b})}));
ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_not", {b}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", IsAlwaysPresent}}));
}
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.presence_and", {a, b}));
ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.to_optional", {a}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"b", IsAlwaysPresentOptionalValue}}));
}
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.presence_and", {a, b}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, b, {{"a", [](const ExprNodePtr& expr) {
return IsAlwaysPresent(expr) &&
IsPresenceType(expr);
}}}));
}
return absl::OkStatus();
}
absl::Status PresenceOrRemovalOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.presence_or", {a, b}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, a, {{"a", IsAlwaysPresentType}}));
return absl::OkStatus();
}
absl::Status HasPropagationOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ExprNodePtr c = Placeholder("c");
auto is_literal_or_presence = [](const ExprNodePtr& expr) {
return IsLiteral(expr) || IsPresenceType(expr);
};
for (const char* op_has : {"core.has._optional", "core.has._array"}) {
for (const auto& op : {"core.presence_or", "core.presence_and"}) {
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference(op_has, {CallOpReference(op, {a, b})}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference(op, {CallOpReference("core.has", {a}),
CallOpReference("core.has", {b})}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", is_literal_or_presence}}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"b", is_literal_or_presence}}));
}
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference(
op_has, {CallOpReference("core._presence_and_or", {a, c, b})}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core._presence_and_or",
{CallOpReference("core.has", {a}), c,
CallOpReference("core.has", {b})}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", is_literal_or_presence}}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"b", is_literal_or_presence}}));
}
}
return absl::OkStatus();
}
absl::Status ToOptionalPropagationOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ExprNodePtr c = Placeholder("c");
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference("core.to_optional._scalar",
{CallOpReference("core.presence_or", {a, b})}));
ASSIGN_OR_RETURN(
ExprNodePtr to,
CallOpReference("core.presence_or",
{a, CallOpReference("core.to_optional", {b})}));
ASSIGN_OR_RETURN(
optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", IsOptionalLikeNode}, {"b", IsLiteral}}));
}
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference("core.to_optional._scalar",
{CallOpReference("core._presence_and_or", {a, c, b})}));
ASSIGN_OR_RETURN(
ExprNodePtr to,
CallOpReference("core._presence_and_or",
{CallOpReference("core.to_optional", {a}), c,
CallOpReference("core.to_optional", {b})}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", IsLiteral}}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"b", IsLiteral}}));
}
return absl::OkStatus();
}
absl::Status PresenceAndOptionalOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr c = Placeholder("c");
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference("core.presence_and",
{CallOpReference("core.to_optional._scalar", {a}), c}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core.presence_and", {a, c}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(from, to));
}
return absl::OkStatus();
}
absl::Status PresenceAndOrCombinationOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ExprNodePtr c = Placeholder("c");
ExprNodePtr d = Placeholder("d");
{
ASSIGN_OR_RETURN(
ExprNodePtr from1,
CallOpReference("core.presence_or",
{CallOpReference("core.presence_and", {c, a}),
CallOpReference("core.presence_and", {c, b})}));
ASSIGN_OR_RETURN(
ExprNodePtr from2,
CallOpReference("core._presence_and_or",
{c, a, CallOpReference("core.presence_and", {c, b})}));
ASSIGN_OR_RETURN(
ExprNodePtr to,
CallOpReference("core.presence_and",
{c, CallOpReference("core.presence_or", {a, b})}));
for (const auto& from : {from1, from2}) {
ASSIGN_OR_RETURN(
optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(from, to));
}
}
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference(
"core.presence_or",
{CallOpReference("core.presence_or",
{
d,
CallOpReference("core.presence_and", {c, a}),
}),
CallOpReference("core.presence_and", {c, b})}));
ASSIGN_OR_RETURN(
ExprNodePtr to,
CallOpReference(
"core.presence_or",
{d, CallOpReference(
"core.presence_and",
{c, CallOpReference("core.presence_or", {a, b})})}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(from, to));
}
return absl::OkStatus();
}
absl::Status WhereOptimizations(PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ExprNodePtr c = Placeholder("c");
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference(
"core.presence_or",
{CallOpReference("core.presence_and", {a, c}),
CallOpReference(
"core.presence_and",
{b, CallOpReference("core.presence_not._builtin", {c})})}));
ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.to_optional", {
CallOpReference("core.where", {c, a, b})}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"c", IsOptionalLikeNode}}));
}
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference(
"core._presence_and_or",
{a, c,
CallOpReference(
"core.presence_and",
{b, CallOpReference("core.presence_not._builtin", {c})})}));
ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.where", {c, a, b}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(from, to));
}
{
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference("core.presence_or",
{CallOpReference("core.presence_and", {a, c}), b}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core._presence_and_or", {a, c, b}));
ASSIGN_OR_RETURN(
optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to,
{{"a", IsBaseQType}, {"b", IsBaseQType}, {"c", IsBaseQType}}));
}
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.where", {c, a, b}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, a,
{{"c", IsAlwaysPresent},
{"a", IsAlwaysPresentType},
{"b", IsAlwaysPresentType}}));
}
return absl::OkStatus();
}
absl::Status WhereToPresenceAndOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ExprNodePtr c = Placeholder("c");
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core.where", {c, a, b}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core.presence_and", {a, c}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"b", IsAlwaysAbsentOptionalValue}}));
}
return absl::OkStatus();
}
absl::Status PresenceAndOrOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ExprNodePtr c = Placeholder("c");
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core._presence_and_or", {a, b, c}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core.presence_or", {a, c}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"b", IsAlwaysPresent}}));
}
{
ASSIGN_OR_RETURN(ExprNodePtr from,
CallOpReference("core._presence_and_or", {a, b, c}));
ASSIGN_OR_RETURN(ExprNodePtr to,
CallOpReference("core.presence_or", {b, c}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", [](const ExprNodePtr& expr) {
return IsAlwaysPresent(expr) &&
IsPresenceType(expr);
}}}));
}
return absl::OkStatus();
}
absl::Status InsideWherePropagationOptimizations(
PeepholeOptimizationPack& optimizations) {
ExprNodePtr a = Placeholder("a");
ExprNodePtr b = Placeholder("b");
ExprNodePtr c = Placeholder("c");
for (const auto& [op_from, op_to] :
std::vector<std::pair<std::string, std::string>>{
{"core.to_optional._scalar", "core.to_optional"},
{"core.has._optional", "core.has"},
{"core.has._array", "core.has"},
}) {
ASSIGN_OR_RETURN(
ExprNodePtr from,
CallOpReference(op_from, {CallOpReference("core.where", {c, a, b})}));
ASSIGN_OR_RETURN(
ExprNodePtr to,
CallOpReference("core.where", {c, CallOpReference(op_to, {a}),
CallOpReference(op_to, {b})}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"a", IsLiteral}}));
ASSIGN_OR_RETURN(optimizations.emplace_back(),
PeepholeOptimization::CreatePatternOptimization(
from, to, {{"b", IsLiteral}}));
}
return absl::OkStatus();
}
}
absl::StatusOr<PeepholeOptimizationPack> PresenceOptimizations() {
PeepholeOptimizationPack optimizations;
RETURN_IF_ERROR(HasRemovalOptimizations(optimizations));
RETURN_IF_ERROR(PresenceAndRemovalOptimizations(optimizations));
RETURN_IF_ERROR(PresenceOrRemovalOptimizations(optimizations));
RETURN_IF_ERROR(HasPropagationOptimizations(optimizations));
RETURN_IF_ERROR(ToOptionalPropagationOptimizations(optimizations));
RETURN_IF_ERROR(PresenceAndOptionalOptimizations(optimizations));
RETURN_IF_ERROR(PresenceAndOrCombinationOptimizations(optimizations));
RETURN_IF_ERROR(WhereOptimizations(optimizations));
RETURN_IF_ERROR(InsideWherePropagationOptimizations(optimizations));
RETURN_IF_ERROR(PresenceAndOrOptimizations(optimizations));
return optimizations;
}
absl::StatusOr<PeepholeOptimizationPack> CodegenPresenceOptimizations() {
PeepholeOptimizationPack optimizations;
RETURN_IF_ERROR(WhereToPresenceAndOptimizations(optimizations));
return optimizations;
}
} | #include "arolla/expr/optimization/peephole_optimizations/presence.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/statusor.h"
#include "arolla/dense_array/qtype/types.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_node.h"
#include "arolla/expr/optimization/peephole_optimizer.h"
#include "arolla/expr/testing/testing.h"
#include "arolla/memory/optional_value.h"
#include "arolla/qtype/base_types.h"
#include "arolla/qtype/optional_qtype.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/util/unit.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr {
namespace {
using ::arolla::expr::presence_impl::IsAlwaysPresent;
using ::arolla::expr::presence_impl::IsPresenceType;
using ::arolla::testing::EqualsExpr;
using ::arolla::testing::WithQTypeAnnotation;
class PresenceOptimizationsTest : public ::testing::Test {
protected:
void SetUp() override {
ASSERT_OK_AND_ASSIGN(optimizer_,
CreatePeepholeOptimizer({PresenceOptimizations}));
ASSERT_OK_AND_ASSIGN(
codegen_optimizer_,
CreatePeepholeOptimizer(
{PresenceOptimizations, CodegenPresenceOptimizations}));
}
absl::StatusOr<ExprNodePtr> ApplyOptimizer(
absl::StatusOr<ExprNodePtr> status_or_expr) const {
ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr));
return ToLowest(optimizer_->ApplyToNode(expr));
}
absl::StatusOr<ExprNodePtr> ApplyCodegenOptimizer(
absl::StatusOr<ExprNodePtr> status_or_expr) const {
ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr));
return ToLowest(codegen_optimizer_->ApplyToNode(expr));
}
absl::StatusOr<ExprNodePtr> ToLowest(
const absl::StatusOr<ExprNodePtr>& status_or_expr) const {
if (!status_or_expr.ok()) {
return std::move(status_or_expr).status();
}
return ::arolla::expr::ToLowest(*status_or_expr);
}
std::unique_ptr<PeepholeOptimizer> optimizer_;
std::unique_ptr<PeepholeOptimizer> codegen_optimizer_;
};
TEST_F(PresenceOptimizationsTest, IsPresenceType) {
for (QTypePtr tpe :
{GetQType<int>(), GetOptionalQType<int>(), GetDenseArrayQType<int>()}) {
ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe));
EXPECT_FALSE(IsPresenceType(x)) << tpe->name();
}
for (QTypePtr tpe : {GetQType<Unit>(), GetOptionalQType<Unit>(),
GetDenseArrayQType<Unit>()}) {
ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe));
EXPECT_TRUE(IsPresenceType(x)) << tpe->name();
}
}
TEST_F(PresenceOptimizationsTest, IsAlwaysPresent) {
for (QTypePtr tpe : {GetQType<int>(), GetQType<Unit>()}) {
ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe));
EXPECT_TRUE(IsAlwaysPresent(x)) << tpe->name();
}
for (QTypePtr tpe : {GetOptionalQType<int>(), GetDenseArrayQType<Unit>()}) {
ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe));
EXPECT_FALSE(IsAlwaysPresent(x)) << tpe->name();
}
for (auto x :
{Literal(1.), Literal(MakeOptionalValue(1.)), Literal(kPresent)}) {
EXPECT_TRUE(IsAlwaysPresent(x)) << x->qvalue()->Repr();
}
for (auto x : {Literal(OptionalValue<int>()), Literal(kMissing)}) {
EXPECT_FALSE(IsAlwaysPresent(x)) << x->qvalue()->Repr();
}
}
TEST_F(PresenceOptimizationsTest, HasRemoval) {
ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int>()));
ASSERT_OK_AND_ASSIGN(auto y,
WithQTypeAnnotation(Leaf("y"), GetQType<Unit>()));
ASSERT_OK_AND_ASSIGN(auto x_opt,
WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>()));
ASSERT_OK_AND_ASSIGN(
auto y_opt, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>()));
auto unit = Literal(Unit{});
auto present = Literal(kPresent);
auto present_float32 = Literal(MakeOptionalValue(1.0f));
for (const auto& arg : {x, y}) {
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp("core.has", {arg})));
EXPECT_THAT(actual_expr, EqualsExpr(unit));
}
for (const auto& arg : {present, present_float32}) {
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp("core.has", {arg})));
EXPECT_THAT(actual_expr, EqualsExpr(present));
}
{
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp("core.has", {x_opt})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.has", {x_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp("core.has", {y_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(y_opt));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.has", {CallOp("core.presence_not", {x_opt})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_not", {x_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp("core.presence_not",
{CallOp("core.has", {x_opt})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_not", {x_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.has", {CallOp("core.to_optional", {x})})));
EXPECT_THAT(actual_expr, EqualsExpr(present));
}
}
TEST_F(PresenceOptimizationsTest, AndRemoval) {
ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int>()));
ASSERT_OK_AND_ASSIGN(auto y,
WithQTypeAnnotation(Leaf("y"), GetQType<Unit>()));
ASSERT_OK_AND_ASSIGN(auto x_opt,
WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>()));
ASSERT_OK_AND_ASSIGN(
auto y_opt, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>()));
auto present = Literal(kPresent);
auto present_int32 = Literal(MakeOptionalValue(1));
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_and", {x_opt, present})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.to_optional", {x_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_and", {present, y_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(y_opt));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_and", {present_int32, y_opt})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.presence_and", {present_int32, y_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_and", {x_opt, y_opt})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_and", {x_opt, y_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, OrRemoval) {
ASSERT_OK_AND_ASSIGN(ExprNodePtr x,
WithQTypeAnnotation(Leaf("x"), GetQType<int>()));
ASSERT_OK_AND_ASSIGN(ExprNodePtr y,
WithQTypeAnnotation(Leaf("y"), GetQType<Unit>()));
ASSERT_OK_AND_ASSIGN(ExprNodePtr x_opt,
WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>()));
ASSERT_OK_AND_ASSIGN(
ExprNodePtr y_opt,
WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>()));
ExprNodePtr present = Literal(kUnit);
ExprNodePtr present_int32 = Literal(1);
for (const auto& arg : {x, present_int32}) {
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_or", {arg, x_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(arg));
}
for (const auto& arg : {y, present}) {
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_or", {arg, y_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(arg));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_or", {y_opt, y_opt})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_or", {y_opt, y_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_or", {y_opt, present})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.presence_or", {y_opt, present})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, HasPropagation) {
ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int>()));
ASSERT_OK_AND_ASSIGN(auto y,
WithQTypeAnnotation(Leaf("y"), GetQType<Unit>()));
ASSERT_OK_AND_ASSIGN(auto x_opt,
WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>()));
ASSERT_OK_AND_ASSIGN(
auto y_opt, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>()));
ASSERT_OK_AND_ASSIGN(
auto z_opt, WithQTypeAnnotation(Leaf("z"), GetOptionalQType<Unit>()));
auto present = Literal(kPresent);
auto present_int = Literal(MakeOptionalValue(1));
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.has", {CallOp("core.presence_or", {x_opt, x_opt})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(
CallOp("core.has", {CallOp("core.presence_or", {x_opt, x_opt})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.has", {CallOp("core.presence_and", {x_opt, y_opt})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.presence_and", {CallOp("core.has", {x_opt}),
CallOp("core.has", {y_opt})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp(
"core.has", {CallOp("core.presence_or", {x_opt, present_int})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_or",
{CallOp("core.has", {x_opt}),
CallOp("core.has", {present_int})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.has", {CallOp("core.presence_or", {y_opt, z_opt})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_or", {y_opt, z_opt})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp(
"core.has",
{CallOp("core._presence_and_or", {present_int, y_opt, x_opt})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core._presence_and_or",
{CallOp("core.has", {present_int}), y_opt,
CallOp("core.has", {x_opt})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp(
"core.has",
{CallOp("core._presence_and_or", {x_opt, y_opt, present_int})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core._presence_and_or",
{CallOp("core.has", {x_opt}), y_opt,
CallOp("core.has", {present_int})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, ToOptionalPropagation) {
ASSERT_OK_AND_ASSIGN(
auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(
auto y, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(auto z,
WithQTypeAnnotation(Leaf("z"), GetQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(
auto w, WithQTypeAnnotation(Leaf("w"), GetOptionalQType<Unit>()));
auto present = Literal(kPresent);
auto present_scalar_int = Literal(1);
auto present_int = Literal(MakeOptionalValue(1));
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.to_optional", {CallOp("core.presence_or", {x, y})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(
CallOp("core.to_optional", {CallOp("core.presence_or", {x, y})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.to_optional", {CallOp("core.presence_or", {z, y})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(
CallOp("core.to_optional", {CallOp("core.presence_or", {z, y})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.to_optional",
{CallOp("core.presence_or", {y, present_int})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.to_optional",
{CallOp("core.presence_or", {y, present_int})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.to_optional",
{CallOp("core.presence_or", {x, present_scalar_int})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_or",
{x, CallOp("core.to_optional",
{present_scalar_int})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp(
"core.to_optional",
{CallOp("core._presence_and_or", {present_scalar_int, w, z})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core._presence_and_or",
{CallOp("core.to_optional", {present_scalar_int}), w,
CallOp("core.to_optional", {z})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp(
"core.to_optional",
{CallOp("core._presence_and_or", {z, w, present_scalar_int})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core._presence_and_or",
{CallOp("core.to_optional", {z}), w,
CallOp("core.to_optional", {present_scalar_int})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, InsideWherePropagationOptimizations) {
ASSERT_OK_AND_ASSIGN(
auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(
auto y, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(
auto z, WithQTypeAnnotation(Leaf("z"), GetOptionalQType<Unit>()));
auto present = Literal(kPresent);
auto present_int = Literal(MakeOptionalValue(1));
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.has", {CallOp("core.where", {z, x, y})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.has", {CallOp("core.where", {z, x, y})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.to_optional",
{CallOp("core.where", {z, present_int, x})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(
CallOp("core.where", {z, CallOp("core.to_optional", {present_int}),
CallOp("core.to_optional", {x})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.has", {CallOp("core.where", {z, x, present_int})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.where", {z, CallOp("core.has", {x}),
CallOp("core.has", {present_int})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, WhereOptimization) {
ASSERT_OK_AND_ASSIGN(
auto cond, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<Unit>()));
ASSERT_OK_AND_ASSIGN(
auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<float>()));
ASSERT_OK_AND_ASSIGN(
auto y, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<float>()));
ASSERT_OK_AND_ASSIGN(auto x_full,
WithQTypeAnnotation(Leaf("x"), GetQType<float>()));
ASSERT_OK_AND_ASSIGN(auto y_full,
WithQTypeAnnotation(Leaf("y"), GetQType<float>()));
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.where", {Literal(kPresent), x_full, y_full})));
EXPECT_THAT(actual_expr, EqualsExpr(x_full));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.where", {Literal(kPresent), x_full, y})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.where", {Literal(kPresent), x_full, y})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.presence_or",
{CallOp("core.presence_and", {x, cond}),
CallOp("core.presence_and",
{y, CallOp("core.presence_not", {cond})})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.where", {cond, x, y})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(auto scalar_x,
WithQTypeAnnotation(Leaf("x"), GetQType<float>()));
ASSERT_OK_AND_ASSIGN(auto scalar_y,
WithQTypeAnnotation(Leaf("y"), GetQType<float>()));
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.presence_or",
{CallOp("core.presence_and", {scalar_x, cond}),
CallOp("core.presence_and",
{scalar_y, CallOp("core.presence_not", {cond})})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.to_optional",
{CallOp("core.where", {cond, scalar_x, scalar_y})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core._presence_and_or",
{x, cond,
CallOp("core.presence_and",
{y, CallOp("core.presence_not", {cond})})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.where", {cond, x, y})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.presence_or",
{CallOp("core.presence_and",
{x, CallOp("core.presence_not", {cond})}),
CallOp("core.presence_and",
{y, CallOp("core.presence_not", {cond})})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core._presence_and_or",
{x, CallOp("core.presence_not", {cond}),
CallOp("core.presence_and",
{y, CallOp("core.presence_not", {cond})})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(auto y_present,
WithQTypeAnnotation(Leaf("y"), GetQType<float>()));
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.presence_or",
{CallOp("core.presence_and", {x, cond}), y_present})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core._presence_and_or", {x, cond, y_present})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto cond_da,
WithQTypeAnnotation(Leaf("cond"), GetDenseArrayQType<Unit>()));
ASSERT_OK_AND_ASSIGN(
auto x_da, WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<float>()));
ASSERT_OK_AND_ASSIGN(
auto y_da, WithQTypeAnnotation(Leaf("y"), GetDenseArrayQType<float>()));
ASSERT_OK_AND_ASSIGN(
auto expr,
CallOp("core.presence_or",
{CallOp("core.presence_and",
{x_da, CallOp("core.presence_not", {cond_da})}),
CallOp("core.presence_and",
{y_da, CallOp("core.presence_not", {cond_da})})}));
ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr));
ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(expr));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, CodegenWhereOptimization) {
ASSERT_OK_AND_ASSIGN(
auto cond, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<Unit>()));
ASSERT_OK_AND_ASSIGN(
auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<float>()));
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyCodegenOptimizer(
CallOp("core.where", {cond, x, Literal(OptionalValue<float>())})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_and", {x, cond})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, PresenceAndOrSimplifications) {
ASSERT_OK_AND_ASSIGN(
auto cond, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<Unit>()));
auto x = Leaf("x");
auto y = Leaf("y");
{
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp("core._presence_and_or",
{x, Literal(kPresent), y})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_or", {x, y})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp("core._presence_and_or",
{Literal(kPresent), cond, y})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_or", {cond, y})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, PresenceAndOptionalOptimizations) {
ASSERT_OK_AND_ASSIGN(auto a, WithQTypeAnnotation(Leaf("a"), GetQType<int>()));
auto c = Leaf("c");
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_and",
{CallOp("core.to_optional._scalar", {a}), c})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_and", {a, c})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, PresenceNotWithAndOptimizations) {
ASSERT_OK_AND_ASSIGN(
auto c, WithQTypeAnnotation(Leaf("c"), GetOptionalQType<Unit>()));
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_not", {Literal(3.)})));
auto expected_expr = Literal(kMissing);
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(auto actual_expr,
ApplyOptimizer(CallOp(
"core.presence_not",
{CallOp("core.presence_and", {Literal(3.), c})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_not", {c})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(
CallOp("core.presence_not",
{CallOp("core.presence_and",
{Literal(OptionalValue<float>(3.)), c})})));
ASSERT_OK_AND_ASSIGN(auto expected_expr,
ToLowest(CallOp("core.presence_not", {c})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
TEST_F(PresenceOptimizationsTest, PresenceAndOrCombinationSimplifications) {
auto a = Leaf("a");
auto b = Leaf("b");
auto c = Leaf("c");
auto d = Leaf("d");
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr1,
ApplyOptimizer(CallOp("core._presence_and_or",
{c, a, CallOp("core.presence_and", {c, b})})));
ASSERT_OK_AND_ASSIGN(
auto actual_expr2,
ApplyOptimizer(
CallOp("core.presence_or", {CallOp("core.presence_and", {c, a}),
CallOp("core.presence_and", {c, b})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.presence_and",
{c, CallOp("core.presence_or", {a, b})})));
EXPECT_THAT(actual_expr1, EqualsExpr(expected_expr));
EXPECT_THAT(actual_expr2, EqualsExpr(expected_expr));
}
{
ASSERT_OK_AND_ASSIGN(
auto actual_expr,
ApplyOptimizer(CallOp("core.presence_or",
{CallOp("core.presence_or",
{d, CallOp("core.presence_and", {c, a})}),
CallOp("core.presence_and", {c, b})})));
ASSERT_OK_AND_ASSIGN(
auto expected_expr,
ToLowest(CallOp("core.presence_or",
{d, CallOp("core.presence_and",
{c, CallOp("core.presence_or", {a, b})})})));
EXPECT_THAT(actual_expr, EqualsExpr(expected_expr));
}
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/optimization/peephole_optimizations/presence.cc | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/optimization/peephole_optimizations/presence_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
e8a55d3f-1b98-427c-b0aa-d6b46c411ffd | cpp | google/quiche | quiche_linked_hash_map | quiche/common/quiche_linked_hash_map.h | quiche/common/quiche_linked_hash_map_test.cc | #ifndef QUICHE_COMMON_QUICHE_LINKED_HASH_MAP_H_
#define QUICHE_COMMON_QUICHE_LINKED_HASH_MAP_H_
#include <functional>
#include <list>
#include <tuple>
#include <type_traits>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/hash/hash.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace quiche {
template <class Key,
class Value,
class Hash = absl::Hash<Key>,
class Eq = std::equal_to<Key>>
class QuicheLinkedHashMap {
private:
typedef std::list<std::pair<Key, Value>> ListType;
typedef absl::flat_hash_map<Key, typename ListType::iterator, Hash, Eq>
MapType;
public:
typedef typename ListType::iterator iterator;
typedef typename ListType::reverse_iterator reverse_iterator;
typedef typename ListType::const_iterator const_iterator;
typedef typename ListType::const_reverse_iterator const_reverse_iterator;
typedef typename MapType::key_type key_type;
typedef typename ListType::value_type value_type;
typedef typename ListType::size_type size_type;
QuicheLinkedHashMap() = default;
explicit QuicheLinkedHashMap(size_type bucket_count) : map_(bucket_count) {}
QuicheLinkedHashMap(const QuicheLinkedHashMap& other) = delete;
QuicheLinkedHashMap& operator=(const QuicheLinkedHashMap& other) = delete;
QuicheLinkedHashMap(QuicheLinkedHashMap&& other) = default;
QuicheLinkedHashMap& operator=(QuicheLinkedHashMap&& other) = default;
iterator begin() { return list_.begin(); }
const_iterator begin() const { return list_.begin(); }
iterator end() { return list_.end(); }
const_iterator end() const { return list_.end(); }
reverse_iterator rbegin() { return list_.rbegin(); }
const_reverse_iterator rbegin() const { return list_.rbegin(); }
reverse_iterator rend() { return list_.rend(); }
const_reverse_iterator rend() const { return list_.rend(); }
const value_type& front() const { return list_.front(); }
value_type& front() { return list_.front(); }
const value_type& back() const { return list_.back(); }
value_type& back() { return list_.back(); }
void clear() {
map_.clear();
list_.clear();
}
bool empty() const { return list_.empty(); }
void pop_front() { erase(begin()); }
size_type erase(const Key& key) {
typename MapType::iterator found = map_.find(key);
if (found == map_.end()) {
return 0;
}
list_.erase(found->second);
map_.erase(found);
return 1;
}
iterator erase(iterator position) {
typename MapType::iterator found = map_.find(position->first);
QUICHE_CHECK(found->second == position)
<< "Inconsistent iterator for map and list, or the iterator is "
"invalid.";
map_.erase(found);
return list_.erase(position);
}
iterator erase(iterator first, iterator last) {
while (first != last && first != end()) {
first = erase(first);
}
return first;
}
iterator find(const Key& key) {
typename MapType::iterator found = map_.find(key);
if (found == map_.end()) {
return end();
}
return found->second;
}
const_iterator find(const Key& key) const {
typename MapType::const_iterator found = map_.find(key);
if (found == map_.end()) {
return end();
}
return found->second;
}
bool contains(const Key& key) const { return find(key) != end(); }
Value& operator[](const key_type& key) {
return (*((this->insert(std::make_pair(key, Value()))).first)).second;
}
std::pair<iterator, bool> insert(const std::pair<Key, Value>& pair) {
return InsertInternal(pair);
}
std::pair<iterator, bool> insert(std::pair<Key, Value>&& pair) {
return InsertInternal(std::move(pair));
}
size_type size() const { return map_.size(); }
template <typename... Args>
std::pair<iterator, bool> emplace(Args&&... args) {
ListType node_donor;
auto node_pos =
node_donor.emplace(node_donor.end(), std::forward<Args>(args)...);
const auto& k = node_pos->first;
auto ins = map_.insert({k, node_pos});
if (!ins.second) {
return {ins.first->second, false};
}
list_.splice(list_.end(), node_donor, node_pos);
return {ins.first->second, true};
}
void swap(QuicheLinkedHashMap& other) {
map_.swap(other.map_);
list_.swap(other.list_);
}
private:
template <typename U>
std::pair<iterator, bool> InsertInternal(U&& pair) {
auto insert_result = map_.try_emplace(pair.first);
auto map_iter = insert_result.first;
if (!insert_result.second) {
return {map_iter->second, false};
}
auto list_iter = list_.insert(list_.end(), std::forward<U>(pair));
map_iter->second = list_iter;
return {list_iter, true};
}
MapType map_;
ListType list_;
};
}
#endif | #include "quiche/common/quiche_linked_hash_map.h"
#include <memory>
#include <tuple>
#include <utility>
#include "quiche/common/platform/api/quiche_test.h"
using testing::Pair;
using testing::Pointee;
using testing::UnorderedElementsAre;
namespace quiche {
namespace test {
TEST(LinkedHashMapTest, Move) {
QuicheLinkedHashMap<int, std::unique_ptr<int>> m;
m[2] = std::make_unique<int>(12);
m[3] = std::make_unique<int>(13);
QuicheLinkedHashMap<int, std::unique_ptr<int>> n = std::move(m);
EXPECT_THAT(n,
UnorderedElementsAre(Pair(2, Pointee(12)), Pair(3, Pointee(13))));
}
TEST(LinkedHashMapTest, CanEmplaceMoveOnly) {
QuicheLinkedHashMap<int, std::unique_ptr<int>> m;
struct Data {
int k, v;
};
const Data data[] = {{1, 123}, {3, 345}, {2, 234}, {4, 456}};
for (const auto& kv : data) {
m.emplace(std::piecewise_construct, std::make_tuple(kv.k),
std::make_tuple(new int{kv.v}));
}
EXPECT_TRUE(m.contains(2));
auto found = m.find(2);
ASSERT_TRUE(found != m.end());
EXPECT_EQ(234, *found->second);
}
struct NoCopy {
explicit NoCopy(int x) : x(x) {}
NoCopy(const NoCopy&) = delete;
NoCopy& operator=(const NoCopy&) = delete;
NoCopy(NoCopy&&) = delete;
NoCopy& operator=(NoCopy&&) = delete;
int x;
};
TEST(LinkedHashMapTest, CanEmplaceNoMoveNoCopy) {
QuicheLinkedHashMap<int, NoCopy> m;
struct Data {
int k, v;
};
const Data data[] = {{1, 123}, {3, 345}, {2, 234}, {4, 456}};
for (const auto& kv : data) {
m.emplace(std::piecewise_construct, std::make_tuple(kv.k),
std::make_tuple(kv.v));
}
EXPECT_TRUE(m.contains(2));
auto found = m.find(2);
ASSERT_TRUE(found != m.end());
EXPECT_EQ(234, found->second.x);
}
TEST(LinkedHashMapTest, ConstKeys) {
QuicheLinkedHashMap<int, int> m;
m.insert(std::make_pair(1, 2));
std::pair<int, int>& p = *m.begin();
EXPECT_EQ(1, p.first);
}
TEST(LinkedHashMapTest, Iteration) {
QuicheLinkedHashMap<int, int> m;
EXPECT_TRUE(m.begin() == m.end());
m.insert(std::make_pair(2, 12));
m.insert(std::make_pair(1, 11));
m.insert(std::make_pair(3, 13));
QuicheLinkedHashMap<int, int>::iterator i = m.begin();
ASSERT_TRUE(m.begin() == i);
ASSERT_TRUE(m.end() != i);
EXPECT_EQ(2, i->first);
EXPECT_EQ(12, i->second);
++i;
ASSERT_TRUE(m.end() != i);
EXPECT_EQ(1, i->first);
EXPECT_EQ(11, i->second);
++i;
ASSERT_TRUE(m.end() != i);
EXPECT_EQ(3, i->first);
EXPECT_EQ(13, i->second);
++i;
ASSERT_TRUE(m.end() == i);
}
TEST(LinkedHashMapTest, ReverseIteration) {
QuicheLinkedHashMap<int, int> m;
EXPECT_TRUE(m.rbegin() == m.rend());
m.insert(std::make_pair(2, 12));
m.insert(std::make_pair(1, 11));
m.insert(std::make_pair(3, 13));
QuicheLinkedHashMap<int, int>::reverse_iterator i = m.rbegin();
ASSERT_TRUE(m.rbegin() == i);
ASSERT_TRUE(m.rend() != i);
EXPECT_EQ(3, i->first);
EXPECT_EQ(13, i->second);
++i;
ASSERT_TRUE(m.rend() != i);
EXPECT_EQ(1, i->first);
EXPECT_EQ(11, i->second);
++i;
ASSERT_TRUE(m.rend() != i);
EXPECT_EQ(2, i->first);
EXPECT_EQ(12, i->second);
++i;
ASSERT_TRUE(m.rend() == i);
}
TEST(LinkedHashMapTest, Clear) {
QuicheLinkedHashMap<int, int> m;
m.insert(std::make_pair(2, 12));
m.insert(std::make_pair(1, 11));
m.insert(std::make_pair(3, 13));
ASSERT_EQ(3u, m.size());
m.clear();
EXPECT_EQ(0u, m.size());
m.clear();
EXPECT_EQ(0u, m.size());
}
TEST(LinkedHashMapTest, Size) {
QuicheLinkedHashMap<int, int> m;
EXPECT_EQ(0u, m.size());
m.insert(std::make_pair(2, 12));
EXPECT_EQ(1u, m.size());
m.insert(std::make_pair(1, 11));
EXPECT_EQ(2u, m.size());
m.insert(std::make_pair(3, 13));
EXPECT_EQ(3u, m.size());
m.clear();
EXPECT_EQ(0u, m.size());
}
TEST(LinkedHashMapTest, Empty) {
QuicheLinkedHashMap<int, int> m;
ASSERT_TRUE(m.empty());
m.insert(std::make_pair(2, 12));
ASSERT_FALSE(m.empty());
m.clear();
ASSERT_TRUE(m.empty());
}
TEST(LinkedHashMapTest, Erase) {
QuicheLinkedHashMap<int, int> m;
ASSERT_EQ(0u, m.size());
EXPECT_EQ(0u, m.erase(2));
m.insert(std::make_pair(2, 12));
ASSERT_EQ(1u, m.size());
EXPECT_EQ(1u, m.erase(2));
EXPECT_EQ(0u, m.size());
EXPECT_EQ(0u, m.erase(2));
EXPECT_EQ(0u, m.size());
}
TEST(LinkedHashMapTest, Erase2) {
QuicheLinkedHashMap<int, int> m;
ASSERT_EQ(0u, m.size());
EXPECT_EQ(0u, m.erase(2));
m.insert(std::make_pair(2, 12));
m.insert(std::make_pair(1, 11));
m.insert(std::make_pair(3, 13));
m.insert(std::make_pair(4, 14));
ASSERT_EQ(4u, m.size());
EXPECT_EQ(1u, m.erase(1));
EXPECT_EQ(1u, m.erase(3));
EXPECT_EQ(2u, m.size());
QuicheLinkedHashMap<int, int>::iterator it = m.begin();
ASSERT_TRUE(it != m.end());
EXPECT_EQ(12, it->second);
++it;
ASSERT_TRUE(it != m.end());
EXPECT_EQ(14, it->second);
++it;
ASSERT_TRUE(it == m.end());
EXPECT_EQ(0u, m.erase(1));
ASSERT_EQ(2u, m.size());
EXPECT_EQ(1u, m.erase(2));
EXPECT_EQ(1u, m.erase(4));
ASSERT_EQ(0u, m.size());
EXPECT_EQ(0u, m.erase(1));
ASSERT_EQ(0u, m.size());
}
TEST(LinkedHashMapTest, Erase3) {
QuicheLinkedHashMap<int, int> m;
m.insert(std::make_pair(1, 11));
m.insert(std::make_pair(2, 12));
m.insert(std::make_pair(3, 13));
m.insert(std::make_pair(4, 14));
QuicheLinkedHashMap<int, int>::iterator it2 = m.find(2);
QuicheLinkedHashMap<int, int>::iterator it4 = m.find(4);
EXPECT_EQ(m.erase(it2, it4), m.find(4));
EXPECT_EQ(2u, m.size());
QuicheLinkedHashMap<int, int>::iterator it = m.begin();
ASSERT_TRUE(it != m.end());
EXPECT_EQ(11, it->second);
++it;
ASSERT_TRUE(it != m.end());
EXPECT_EQ(14, it->second);
++it;
ASSERT_TRUE(it == m.end());
EXPECT_EQ(m.erase(m.begin()), m.find(4));
it = m.begin();
ASSERT_TRUE(it != m.end());
EXPECT_EQ(14, it->second);
++it;
ASSERT_TRUE(it == m.end());
}
TEST(LinkedHashMapTest, Insertion) {
QuicheLinkedHashMap<int, int> m;
ASSERT_EQ(0u, m.size());
std::pair<QuicheLinkedHashMap<int, int>::iterator, bool> result;
result = m.insert(std::make_pair(2, 12));
ASSERT_EQ(1u, m.size());
EXPECT_TRUE(result.second);
EXPECT_EQ(2, result.first->first);
EXPECT_EQ(12, result.first->second);
result = m.insert(std::make_pair(1, 11));
ASSERT_EQ(2u, m.size());
EXPECT_TRUE(result.second);
EXPECT_EQ(1, result.first->first);
EXPECT_EQ(11, result.first->second);
result = m.insert(std::make_pair(3, 13));
QuicheLinkedHashMap<int, int>::iterator result_iterator = result.first;
ASSERT_EQ(3u, m.size());
EXPECT_TRUE(result.second);
EXPECT_EQ(3, result.first->first);
EXPECT_EQ(13, result.first->second);
result = m.insert(std::make_pair(3, 13));
EXPECT_EQ(3u, m.size());
EXPECT_FALSE(result.second) << "No insertion should have occurred.";
EXPECT_TRUE(result_iterator == result.first)
<< "Duplicate insertion should have given us the original iterator.";
}
static std::pair<int, int> Pair(int i, int j) { return {i, j}; }
TEST(LinkedHashMapTest, Front) {
QuicheLinkedHashMap<int, int> m;
m.insert(std::make_pair(2, 12));
m.insert(std::make_pair(1, 11));
m.insert(std::make_pair(3, 13));
EXPECT_EQ(3u, m.size());
EXPECT_EQ(Pair(2, 12), m.front());
m.pop_front();
EXPECT_EQ(2u, m.size());
EXPECT_EQ(Pair(1, 11), m.front());
m.pop_front();
EXPECT_EQ(1u, m.size());
EXPECT_EQ(Pair(3, 13), m.front());
m.pop_front();
EXPECT_TRUE(m.empty());
}
TEST(LinkedHashMapTest, Find) {
QuicheLinkedHashMap<int, int> m;
EXPECT_TRUE(m.end() == m.find(1))
<< "We shouldn't find anything in an empty map.";
m.insert(std::make_pair(2, 12));
EXPECT_TRUE(m.end() == m.find(1))
<< "We shouldn't find an element that doesn't exist in the map.";
std::pair<QuicheLinkedHashMap<int, int>::iterator, bool> result =
m.insert(std::make_pair(1, 11));
ASSERT_TRUE(result.second);
ASSERT_TRUE(m.end() != result.first);
EXPECT_TRUE(result.first == m.find(1))
<< "We should have found an element we know exists in the map.";
EXPECT_EQ(11, result.first->second);
m.insert(std::make_pair(3, 13));
QuicheLinkedHashMap<int, int>::iterator it = m.find(1);
ASSERT_TRUE(m.end() != it);
EXPECT_EQ(11, it->second);
m.clear();
EXPECT_TRUE(m.end() == m.find(1))
<< "We shouldn't find anything in a map that we've cleared.";
}
TEST(LinkedHashMapTest, Contains) {
QuicheLinkedHashMap<int, int> m;
EXPECT_FALSE(m.contains(1)) << "An empty map shouldn't contain anything.";
m.insert(std::make_pair(2, 12));
EXPECT_FALSE(m.contains(1))
<< "The map shouldn't contain an element that doesn't exist.";
m.insert(std::make_pair(1, 11));
EXPECT_TRUE(m.contains(1))
<< "The map should contain an element that we know exists.";
m.clear();
EXPECT_FALSE(m.contains(1))
<< "A map that we've cleared shouldn't contain anything.";
}
TEST(LinkedHashMapTest, Swap) {
QuicheLinkedHashMap<int, int> m1;
QuicheLinkedHashMap<int, int> m2;
m1.insert(std::make_pair(1, 1));
m1.insert(std::make_pair(2, 2));
m2.insert(std::make_pair(3, 3));
ASSERT_EQ(2u, m1.size());
ASSERT_EQ(1u, m2.size());
m1.swap(m2);
ASSERT_EQ(1u, m1.size());
ASSERT_EQ(2u, m2.size());
}
TEST(LinkedHashMapTest, CustomHashAndEquality) {
struct CustomIntHash {
size_t operator()(int x) const { return x; }
};
QuicheLinkedHashMap<int, int, CustomIntHash> m;
m.insert(std::make_pair(1, 1));
EXPECT_TRUE(m.contains(1));
EXPECT_EQ(1, m[1]);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_linked_hash_map.h | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_linked_hash_map_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
8f2bbdb6-1130-4e57-b10d-d60bc7696f0b | cpp | tensorflow/tensorflow | tstring | tensorflow/core/platform/tstring.h | third_party/xla/third_party/tsl/tsl/platform/tstring_test.cc | #ifndef TENSORFLOW_CORE_PLATFORM_TSTRING_H_
#define TENSORFLOW_CORE_PLATFORM_TSTRING_H_
#include "tensorflow/core/platform/cord.h"
#include "tensorflow/core/platform/ctstring.h"
#include "tensorflow/core/platform/stringpiece.h"
#include "tsl/platform/tstring.h"
namespace tensorflow {
using tstring = tsl::tstring;
}
#endif | #include "tsl/platform/tstring.h"
#include <memory>
#include <string>
#include "tsl/platform/cord.h"
#include "tsl/platform/platform.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/test.h"
using ::tsl::tstring;
static const char kLongString[] =
"abcdefghij"
"klmnopqrst"
"uvwxyz0123"
"456789ABCD"
"EFGHIKLMNO";
const size_t kLongStringLen = sizeof(kLongString) / sizeof(char) - sizeof(char);
TEST(TF_TStringTest, Construction) {
tstring s10;
tstring s11("a\0a", 3);
tstring s12(kLongString);
tstring s13(3, 'b');
tstring s14(absl::string_view("hi"));
tstring s15(std::string("bye"));
EXPECT_EQ("", s10);
EXPECT_TRUE(s10.empty());
EXPECT_EQ(tstring::Type::SMALL, s10.type());
EXPECT_EQ(0, s10.size());
EXPECT_EQ(0, s10.length());
EXPECT_EQ(TF_TString_SmallCapacity, s10.capacity());
EXPECT_EQ(std::string("a\0a", 3), s11);
EXPECT_FALSE(s11.empty());
EXPECT_EQ(3, s11.size());
EXPECT_EQ(3, s11.length());
EXPECT_EQ(kLongString, s12);
EXPECT_EQ(kLongStringLen, s12.size());
EXPECT_EQ(tstring::Type::LARGE, s12.type());
EXPECT_LT(TF_TString_SmallCapacity, s12.capacity());
EXPECT_EQ("bbb", s13);
EXPECT_EQ("hi", s14);
EXPECT_EQ(tstring::Type::SMALL, s14.type());
EXPECT_EQ("bye", s15);
}
TEST(TF_TStringTest, CopyMove) {
tstring s20(kLongString);
tstring s21(s20);
tstring s22;
EXPECT_EQ(s20, s21);
s22 = std::move(s21);
EXPECT_EQ(s20, s22);
EXPECT_EQ("", s21);
EXPECT_EQ(tstring::Type::SMALL, s21.type());
}
TEST(TF_TStringTest, Assignment) {
tstring s30("123456789012345678901234567890");
tstring s31;
tstring s32;
s31 = s30;
EXPECT_EQ(s30, s31);
EXPECT_EQ(tstring::Type::LARGE, s31.type());
EXPECT_EQ(s30.size(), s31.size());
s32 = std::move(s30);
EXPECT_EQ(s31, s32);
EXPECT_EQ("", s30);
EXPECT_EQ(tstring::Type::SMALL, s30.type());
EXPECT_EQ(tstring::Type::LARGE, s32.type());
s32 = tstring::view(kLongString);
EXPECT_EQ(kLongString, s32);
EXPECT_EQ(tstring::Type::VIEW, s32.type());
EXPECT_EQ(kLongStringLen, s32.size());
EXPECT_EQ(0, s32.capacity());
tstring s33(std::move(s32));
EXPECT_EQ(kLongString, s33);
EXPECT_EQ(tstring::Type::VIEW, s33.type());
EXPECT_EQ(kLongStringLen, s33.size());
s32 = std::string(kLongString);
EXPECT_EQ(kLongString, s32);
EXPECT_EQ(tstring::Type::LARGE, s32.type());
EXPECT_EQ(kLongStringLen, s32.size());
s32 = "hello";
EXPECT_EQ("hello", s32);
EXPECT_EQ(tstring::Type::SMALL, s32.type());
EXPECT_EQ(5, s32.size());
s33 = 'a';
EXPECT_EQ("a", s33);
EXPECT_EQ(tstring::Type::SMALL, s33.type());
EXPECT_EQ(1, s33.size());
s32 = absl::string_view(kLongString);
EXPECT_EQ(kLongString, s32);
EXPECT_EQ(tstring::Type::LARGE, s32.type());
EXPECT_EQ(kLongStringLen, s32.size());
s32.resize(TF_TString_SmallCapacity * 2);
EXPECT_EQ(absl::string_view(kLongString, TF_TString_SmallCapacity * 2), s32);
EXPECT_EQ(tstring::Type::LARGE, s32.type());
EXPECT_EQ(TF_TString_SmallCapacity * 2, s32.size());
s32 = tstring::view(kLongString, kLongStringLen);
EXPECT_EQ(kLongString, s32);
EXPECT_EQ(tstring::Type::VIEW, s32.type());
EXPECT_EQ(kLongStringLen, s32.size());
s32.assign("hello1");
EXPECT_EQ("hello1", s32);
s32.assign("hello2", 5);
EXPECT_EQ("hello", s32);
s30.assign_as_view(kLongString);
EXPECT_EQ(tstring::Type::VIEW, s30.type());
s31.assign_as_view(s30);
EXPECT_EQ(tstring::Type::VIEW, s31.type());
EXPECT_EQ(kLongString, s30.c_str());
EXPECT_EQ(kLongString, s31.c_str());
std::string tmp(kLongString);
s32.assign_as_view(tmp);
EXPECT_EQ(tstring::Type::VIEW, s32.type());
EXPECT_STREQ(kLongString, s32.c_str());
s33.assign_as_view(kLongString, 2);
EXPECT_EQ(2, s33.size());
s32.assign_as_view(absl::string_view(kLongString));
EXPECT_EQ(tstring::Type::VIEW, s32.type());
EXPECT_EQ(kLongString, s32.c_str());
#ifdef PLATFORM_GOOGLE
s33 = absl::Cord(kLongString);
EXPECT_EQ(kLongString, s33);
EXPECT_EQ(tstring::Type::LARGE, s33.type());
EXPECT_EQ(kLongStringLen, s33.size());
tstring s34((absl::Cord(kLongString)));
EXPECT_EQ(kLongString, s34);
EXPECT_EQ(tstring::Type::LARGE, s34.type());
EXPECT_EQ(kLongStringLen, s34.size());
#endif
}
TEST(TF_TStringTest, Comparison) {
tstring empty("");
tstring a("a");
tstring aa("aa");
tstring a_("a");
tstring b("b");
const char c[] = "c";
tstring nulla("\0a", 2);
tstring nullb("\0b", 2);
tstring nullaa("\0aa", 3);
EXPECT_TRUE(a < b);
EXPECT_TRUE(a != b);
EXPECT_FALSE(a > b);
EXPECT_FALSE(a == b);
EXPECT_TRUE(a < aa);
EXPECT_TRUE(a != aa);
EXPECT_FALSE(a > aa);
EXPECT_FALSE(a == aa);
EXPECT_TRUE(b > a);
EXPECT_TRUE(b != a);
EXPECT_FALSE(b < a);
EXPECT_FALSE(b == a);
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == c);
EXPECT_TRUE(b != c);
EXPECT_TRUE(empty < a);
EXPECT_TRUE(empty != a);
EXPECT_FALSE(empty > a);
EXPECT_FALSE(empty == a);
EXPECT_TRUE(a > empty);
EXPECT_TRUE(a != empty);
EXPECT_FALSE(a < empty);
EXPECT_FALSE(a == empty);
EXPECT_FALSE(a < a_);
EXPECT_FALSE(a != a_);
EXPECT_FALSE(a > a_);
EXPECT_TRUE(a == a_);
EXPECT_TRUE(nulla < nullaa);
EXPECT_TRUE(nulla != nullaa);
EXPECT_FALSE(nulla > nullaa);
EXPECT_FALSE(nulla == nullaa);
EXPECT_TRUE(nulla < nullb);
EXPECT_TRUE(nullaa > nulla);
EXPECT_TRUE(nullaa != nulla);
EXPECT_FALSE(nullaa < nulla);
EXPECT_FALSE(nullaa == nulla);
}
TEST(TF_TStringTest, Conversion) {
tstring s50(kLongString);
std::string s51(s50);
absl::string_view s52(s50);
EXPECT_EQ(kLongString, s51);
EXPECT_EQ(kLongStringLen, s51.size());
EXPECT_EQ(kLongString, s52);
EXPECT_EQ(kLongStringLen, s52.size());
#ifdef PLATFORM_GOOGLE
absl::AlphaNum s53(s50);
EXPECT_STREQ(kLongString, s53.data());
EXPECT_EQ(kLongStringLen, s53.size());
#endif
}
TEST(TF_TStringTest, Allocation) {
tstring s60;
s60.resize(2);
EXPECT_EQ(std::string("\0\0", 2), s60);
EXPECT_EQ(2, s60.size());
EXPECT_EQ(2, s60.length());
s60.resize(6, 'a');
EXPECT_EQ(std::string("\0\0aaaa", 6), s60);
EXPECT_EQ(6, s60.size());
EXPECT_EQ(6, s60.length());
s60.resize(3, 'b');
EXPECT_EQ(std::string("\0\0a", 3), s60);
EXPECT_EQ(3, s60.size());
EXPECT_EQ(3, s60.length());
s60.clear();
EXPECT_EQ("", s60);
EXPECT_TRUE(s60.empty());
EXPECT_EQ(0, s60.size());
EXPECT_EQ(0, s60.length());
s60.reserve(100);
EXPECT_EQ(111, s60.capacity());
s60.reserve(100);
}
TEST(TF_TStringTest, ElementAccess) {
tstring s70(kLongString);
EXPECT_STREQ(kLongString, s70.data());
EXPECT_EQ(s70.data(), s70.c_str());
for (size_t i = 0; i < s70.size(); i++) {
EXPECT_EQ(kLongString[i], s70.data()[i]);
}
tstring::const_iterator i = s70.begin();
const char* j = kLongString;
for (; *j != '\0'; i++, j++) {
EXPECT_EQ(*j, *i);
}
EXPECT_EQ('\0', *s70.end());
EXPECT_EQ(*i, *s70.end());
EXPECT_EQ(*(i - 1), s70.back());
}
TEST(TF_TStringTest, Modifiers) {
tstring s80("ba");
tstring s81;
tstring s82(kLongString);
s81.append(s80);
EXPECT_EQ("ba", s81);
s81.append(s80);
EXPECT_EQ("baba", s81);
s81.append("\0c", 2);
EXPECT_EQ(std::string("baba\0c", 6), s81);
s81.append("dd");
EXPECT_EQ(std::string("baba\0cdd", 8), s81);
s81.append(3, 'z');
EXPECT_EQ(tstring("baba\0cddzzz", 11), s81);
s81.append(0, 'z');
s81.append("dd", 0);
s81.append("");
s81.append(tstring());
EXPECT_EQ(std::string("baba\0cddzzz", 11), s81);
s81.erase(0, 1);
EXPECT_EQ(std::string("aba\0cddzzz", 10), s81);
s81.erase(4, 6);
EXPECT_EQ(std::string("aba\0", 4), s81);
s81.insert(1, tstring("\0moo\0", 5), 1, 4);
EXPECT_EQ(std::string("amoo\0ba\0", 8), s81);
s81.insert(0, 2, '\0');
s81.insert(s81.size() - 1, 1, 'q');
EXPECT_EQ(std::string("\0\0amoo\0baq\0", 11), s81);
s81.erase(0, s81.size());
EXPECT_EQ(tstring(), s81);
s80.swap(s82);
EXPECT_EQ(kLongString, s80);
EXPECT_EQ("ba", s82);
s82.push_back('\0');
s82.push_back('q');
EXPECT_EQ(std::string("ba\0q", 4), s82);
}
TEST(TF_TStringTest, Friends) {
tstring s90("b");
tstring s91("\0a\0", 3);
tstring s92;
EXPECT_EQ("b", s90 + s92);
EXPECT_EQ("b", s92 + s90);
EXPECT_EQ(std::string("\0a\0", 3), s92 + s91);
EXPECT_EQ(std::string("\0a\0", 3), s91 + s92);
EXPECT_EQ(std::string("b\0a\0", 4), s90 + s91);
EXPECT_EQ(std::string("\0a\0b", 4), s91 + s90);
std::stringstream ss;
ss << s91;
EXPECT_EQ(std::string("\0a\0", 3), ss.str());
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/platform/tstring.h | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/third_party/tsl/tsl/platform/tstring_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
0c2807a6-9de3-4dea-b2ce-9f085bb68d10 | cpp | tensorflow/tensorflow | coordination_service_error_util | third_party/xla/xla/tsl/distributed_runtime/coordination/coordination_service_error_util.cc | third_party/xla/xla/tsl/distributed_runtime/coordination/coordination_service_error_util_test.cc | #include "xla/tsl/distributed_runtime/coordination/coordination_service_error_util.h"
#include <optional>
#include <string>
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "tsl/platform/regexp.h"
namespace tsl {
absl::Status TrimCoordinationErrorMessage(const absl::Status& s) {
if (s.ok()) {
return s;
}
auto status_message = std::string(s.message());
auto additional_info_index = status_message.find("Additional GRPC");
if (additional_info_index == std::string::npos) {
return s;
}
std::optional<absl::Cord> payload =
s.GetPayload(CoordinationErrorPayloadKey());
if (!payload.has_value() && absl::IsUnavailable(s)) {
auto prefix_message =
"Failed to send RPC to coordination service. Either the leader task "
"died/restarted unexpectedly or this task is experiencing network "
"issues. Check earlier logs from this task and the "
"leader (usually slice 0 process/task/worker 0) to debug further.\n";
status_message = absl::StrCat(
prefix_message,
status_message.substr(additional_info_index));
} else {
std::string rpc_name;
RE2::PartialMatch(status_message,
"(/tensorflow.CoordinationService/(\\w+))", &rpc_name);
status_message = status_message.substr(0, additional_info_index);
absl::StrAppend(&status_message, "\nRPC: ", rpc_name);
}
auto trimmed_status = absl::Status(s.code(), status_message);
if (payload.has_value()) {
trimmed_status.SetPayload(CoordinationErrorPayloadKey(), *payload);
}
#if defined(PLATFORM_GOOGLE)
for (const auto& source_location : s.GetSourceLocations()) {
trimmed_status.AddSourceLocation(source_location);
}
#endif
return trimmed_status;
}
} | #include "xla/tsl/distributed_runtime/coordination/coordination_service_error_util.h"
#include <string>
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "xla/tsl/protobuf/coordination_service.pb.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
using ::tensorflow::CoordinatedTask;
using ::tensorflow::CoordinationServiceError;
TEST(CoordinationServiceErrorUtil, MakeCoordinationErrorWithEmptyPayload) {
absl::Status error = absl::InternalError("Test Error");
absl::Status coordination_error = MakeCoordinationError(error);
EXPECT_EQ(coordination_error.code(), error.code());
EXPECT_EQ(coordination_error.message(), error.message());
EXPECT_EQ(
coordination_error.GetPayload(CoordinationErrorPayloadKey()).value(), "");
}
TEST(CoordinationServiceErrorUtil, MakeCoordinationErrorWithErrorOrigin) {
absl::Status error = absl::InternalError("Test Error");
CoordinatedTask source_task;
source_task.set_job_name("test_worker");
source_task.set_task_id(7);
absl::Status coordination_error = MakeCoordinationError(error, source_task);
EXPECT_EQ(coordination_error.code(), error.code());
EXPECT_EQ(coordination_error.message(), error.message());
CoordinationServiceError payload;
payload.ParseFromString(std::string(
coordination_error.GetPayload(CoordinationErrorPayloadKey()).value()));
EXPECT_EQ(payload.source_task().job_name(), source_task.job_name());
EXPECT_EQ(payload.source_task().task_id(), source_task.task_id());
EXPECT_EQ(payload.is_reported_error(), false);
}
TEST(CoordinationServiceErrorUtil, MakeCoordinationErrorWithUserReportedError) {
absl::Status error = absl::InternalError("Test Error");
CoordinatedTask source_task;
source_task.set_job_name("test_worker");
source_task.set_task_id(7);
absl::Status coordination_error =
MakeCoordinationError(error, source_task,
true);
EXPECT_EQ(coordination_error.code(), error.code());
EXPECT_EQ(coordination_error.message(), error.message());
CoordinationServiceError payload;
payload.ParseFromString(std::string(
coordination_error.GetPayload(CoordinationErrorPayloadKey()).value()));
EXPECT_EQ(payload.source_task().job_name(), source_task.job_name());
EXPECT_EQ(payload.source_task().task_id(), source_task.task_id());
EXPECT_EQ(payload.is_reported_error(), true);
}
TEST(CoordinationServiceErrorUtil, MakeCoordinationErrorWithPayload) {
absl::Status error = absl::InternalError("Test Error");
CoordinationServiceError payload;
CoordinatedTask* source_task = payload.mutable_source_task();
source_task->set_job_name("test_worker");
source_task->set_task_id(7);
payload.set_is_reported_error(true);
absl::Status coordination_error = MakeCoordinationError(error, payload);
EXPECT_EQ(coordination_error.code(), error.code());
EXPECT_EQ(coordination_error.message(), error.message());
CoordinationServiceError actual_payload;
actual_payload.ParseFromString(std::string(
coordination_error.GetPayload(CoordinationErrorPayloadKey()).value()));
EXPECT_EQ(actual_payload.source_task().job_name(),
payload.source_task().job_name());
EXPECT_EQ(actual_payload.source_task().task_id(),
payload.source_task().task_id());
EXPECT_EQ(actual_payload.is_reported_error(), payload.is_reported_error());
}
TEST(CoordinationServiceErrorUtil,
TrimCoordinationErrorMessage_CoordinationError) {
absl::Status error = MakeCoordinationError(absl::InternalError(
"Coordination service has stopped. RecordHeartbeat() from task: "
"/job:jax_worker/replica:0/task:2 failed. Additional GRPC error "
"information from remote target coordination_service while calling "
"/tensorflow.CoordinationService/Heartbeat::UNKNOWN:Error received from "
"peer "
"{file:'third_party/grpc/src/core/lib/surface/filter_stack_call.cc', "
"file_line:464, created_time:'2024-08-05T13:57:51.331198242-07:00', "
"grpc_status:13, grpc_message:'Coordination service has stopped. "
"RecordHeartbeat() from task: /job:jax_worker/replica:0/task:2 failed. "
"'} "));
absl::Status trimmed_error = TrimCoordinationErrorMessage(error);
EXPECT_EQ(trimmed_error.code(), error.code());
EXPECT_EQ(trimmed_error.message(),
"Coordination service has stopped. RecordHeartbeat() from task: "
"/job:jax_worker/replica:0/task:2 failed. \nRPC: "
"/tensorflow.CoordinationService/Heartbeat");
EXPECT_EQ(trimmed_error.GetPayload(CoordinationErrorPayloadKey()).value(),
"");
}
TEST(CoordinationServiceErrorUtil, TrimCoordinationErrorMessage_NetworkError) {
absl::Status error = absl::UnavailableError(
"failed to connect to all addresses; last error: UNKNOWN: "
"ipv4:127.0.0.1:10001: Failed to connect to remote host: Connection "
"refused. Additional GRPC error information from remote target "
"coordination_service while calling "
"/tensorflow.CoordinationService/Heartbeat::UNKNOWN:Error received from "
"peer "
"{file:'third_party/grpc/src/core/lib/surface/filter_stack_call.cc', "
"file_line:464, created_time:'2024-08-05T13:57:53.123562608-07:00', "
"grpc_status:14, grpc_message:'failed to connect to all addresses; last "
"error: UNKNOWN: ipv4:127.0.0.1:10001: Failed to connect to remote host: "
"Connection refused'} ");
absl::Status trimmed_error = TrimCoordinationErrorMessage(error);
auto message = trimmed_error.message();
EXPECT_EQ(trimmed_error.code(), error.code());
EXPECT_TRUE(absl::StrContains(message, "Check earlier logs"));
EXPECT_EQ(message.find("failed to connect"),
message.rfind("failed to connect"))
<< trimmed_error;
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tsl/distributed_runtime/coordination/coordination_service_error_util.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/tsl/distributed_runtime/coordination/coordination_service_error_util_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
38927dfd-d806-4ded-8fdd-5adb64b435d7 | cpp | google/arolla | pointwise_op | arolla/array/pointwise_op.h | arolla/array/pointwise_op_test.cc | #ifndef AROLLA_ARRAY_POINTWISE_OP_H_
#define AROLLA_ARRAY_POINTWISE_OP_H_
#include <cstdint>
#include <optional>
#include <utility>
#include "absl/status/statusor.h"
#include "arolla/array/array.h"
#include "arolla/array/id_filter.h"
#include "arolla/dense_array/dense_array.h"
#include "arolla/dense_array/ops/dense_ops.h"
#include "arolla/memory/optional_value.h"
#include "arolla/memory/raw_buffer_factory.h"
#include "arolla/util/meta.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla {
template <class ResT, class DenseArrayOp, class PointwiseFn, class ArgList>
class ArrayPointwiseOp;
template <class ResT, class DenseArrayOp, class PointwiseFn, class... Args>
class ArrayPointwiseOp<ResT, DenseArrayOp, PointwiseFn,
meta::type_list<Args...>> {
public:
explicit ArrayPointwiseOp(DenseArrayOp dense_op, PointwiseFn pointwise_fn,
RawBufferFactory* buf_factory)
: dense_op_(std::move(dense_op)),
pointwise_fn_(std::move(pointwise_fn)),
buf_factory_(std::move(buf_factory)) {}
template <class... As>
absl::StatusOr<Array<ResT>> operator()(const As&... args) const {
ASSIGN_OR_RETURN(int64_t size, GetCommonSize(args...));
if ((((!is_optional_v<Args> && args.IsAllMissingForm())) || ...)) {
return Array<ResT>(size, std::nullopt);
}
IdFilter id_filter(IdFilter::kEmpty);
DenseArray<ResT> data;
if (IsSameIdFilter(args...)) {
id_filter = First(args...).id_filter();
if (id_filter.type() != IdFilter::kEmpty) {
ASSIGN_OR_RETURN(data, ApplyDenseOp(args...));
}
} else {
if ((CanBeIntersected<Args>(args) || ...)) {
IdFilter full(IdFilter::kFull);
id_filter = IdFilter::UpperBoundIntersect(
(CanBeIntersected<Args>(args) ? args.id_filter() : full)...);
} else {
id_filter =
IdFilter::UpperBoundMerge(size, buf_factory_, args.id_filter()...);
}
ASSIGN_OR_RETURN(data, ApplyDenseOp(args.WithIds(
id_filter, args.missing_id_value())...));
}
auto missing_id_value = pointwise_fn_(args.missing_id_value()...);
RETURN_IF_ERROR(GetStatusOrOk(missing_id_value));
return Array<ResT>(
size, std::move(id_filter), std::move(data),
OptionalValue<ResT>(UnStatus(std::move(missing_id_value))));
}
private:
template <class... As>
absl::StatusOr<DenseArray<ResT>> ApplyDenseOp(const As&... args) const {
return dense_op_(args.dense_data()...);
}
template <class Arg, class A>
static bool CanBeIntersected(const A& arg) {
return !is_optional_v<Arg> && !arg.HasMissingIdValue();
}
template <class A, class... As>
static absl::StatusOr<int64_t> GetCommonSize(const A& a, const As&... as) {
if (!((a.size() == as.size()) && ...)) {
return SizeMismatchError({a.size(), as.size()...});
} else {
return a.size();
}
}
template <class A, class... As>
static bool IsSameIdFilter(const A& a, const As&... as) {
return ((a.id_filter().IsSame(as.id_filter()) && ...));
}
template <class A, class... As>
static const A& First(const A& a, const As&...) {
return a;
}
DenseArrayOp dense_op_;
PointwiseFn pointwise_fn_;
RawBufferFactory* buf_factory_;
};
template <int flags, class Fn,
class ResT = dense_ops_internal::result_base_t<Fn>>
auto CreateArrayOp(Fn fn,
RawBufferFactory* buf_factory = GetHeapBufferFactory()) {
auto dense_op = CreateDenseOp<flags | DenseOpFlags::kNoSizeValidation,
decltype(fn), ResT>(fn, buf_factory);
auto optional_fn = WrapFnToAcceptOptionalArgs(fn);
using Op = ArrayPointwiseOp<ResT, decltype(dense_op), decltype(optional_fn),
typename meta::function_traits<Fn>::arg_types>;
return Op(dense_op, optional_fn, buf_factory);
}
template <class Fn, class ResT = dense_ops_internal::result_base_t<Fn>>
auto CreateArrayOp(Fn fn,
RawBufferFactory* buf_factory = GetHeapBufferFactory()) {
return CreateArrayOp<0, decltype(fn), ResT>(fn, buf_factory);
}
}
#endif | #include "arolla/array/pointwise_op.h"
#include <cstdint>
#include <optional>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "arolla/array/array.h"
#include "arolla/array/id_filter.h"
#include "arolla/dense_array/dense_array.h"
#include "arolla/memory/buffer.h"
#include "arolla/memory/optional_value.h"
namespace arolla {
namespace {
using ::testing::ElementsAre;
template <typename T>
struct UnionAddFn {
OptionalValue<T> operator()(OptionalValue<T> a, OptionalValue<T> b) const {
return {a.present || b.present,
(a.present ? a.value : 0) + (b.present ? b.value : 0)};
}
};
TEST(OpAddTest, WithConst) {
auto op = CreateArrayOp([](int a, int b) { return a + b; });
{
ASSERT_OK_AND_ASSIGN(Array<int> block,
op(Array<int>(10, 2), Array<int>(10, 3)));
EXPECT_TRUE(block.IsConstForm());
EXPECT_EQ(block.missing_id_value(), OptionalValue<int>(5));
}
{
ASSERT_OK_AND_ASSIGN(Array<int> block,
op(Array<int>(10, 2), Array<int>(10, std::nullopt)));
EXPECT_TRUE(block.IsAllMissingForm());
}
{
ASSERT_OK_AND_ASSIGN(
Array<int> block,
op(CreateArray<int>({1, std::nullopt, 2}), Array<int>(3, 5)));
EXPECT_TRUE(block.IsDenseForm());
EXPECT_THAT(block, ElementsAre(6, std::nullopt, 7));
}
{
ASSERT_OK_AND_ASSIGN(
Array<int> block,
op(CreateArray<int>({1, std::nullopt, 2}).ToSparseForm(),
Array<int>(3, 5)));
EXPECT_TRUE(block.IsSparseForm());
EXPECT_THAT(block, ElementsAre(6, std::nullopt, 7));
}
{
ASSERT_OK_AND_ASSIGN(Array<int> block,
op(CreateArray<int>({1, std::nullopt, 2}),
Array<int>(3, std::nullopt)));
EXPECT_TRUE(block.IsAllMissingForm());
}
}
TEST(OpAddTest, SameIdFilter) {
auto op = CreateArrayOp([](int a, int b) { return a + b; });
IdFilter ids(10, CreateBuffer<int64_t>({1, 2, 5, 9}));
Array<int> arg1(10, ids, CreateDenseArray<int>({1, 2, std::nullopt, 3}), 2);
Array<int> arg2(10, ids, CreateDenseArray<int>({7, 5, 3, 0}), 3);
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2));
EXPECT_EQ(res.size(), arg1.size());
EXPECT_TRUE(res.id_filter().IsSame(arg1.id_filter()));
EXPECT_EQ(res.missing_id_value(), OptionalValue<int>(5));
EXPECT_THAT(res.dense_data(), ElementsAre(8, 7, std::nullopt, 3));
}
TEST(OpAddTest, DensePlusSparse) {
auto op = CreateArrayOp([](int a, int b) { return a + b; });
auto arg1 = CreateArray<int>({1, 2, 3, 0, 0, 3, 2, 1});
{
auto arg2 = CreateArray<int>(
{4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt})
.ToSparseForm();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2));
EXPECT_EQ(res.size(), arg1.size());
EXPECT_TRUE(res.id_filter().IsSame(arg2.id_filter()));
EXPECT_FALSE(res.HasMissingIdValue());
EXPECT_THAT(res.dense_data(), ElementsAre(5, 9, 6, 3, 9));
}
{
auto arg2 = CreateArray<int>({4, 7, 3, 1, 3, 6, 1, 1}).ToSparseForm(1);
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2));
EXPECT_EQ(res.size(), arg1.size());
EXPECT_TRUE(res.IsDenseForm());
EXPECT_TRUE(arg2.IsSparseForm());
EXPECT_TRUE(res.dense_data().bitmap.empty());
EXPECT_THAT(res.dense_data().values, ElementsAre(5, 9, 6, 1, 3, 9, 3, 2));
}
}
TEST(OpAddTest, SparsePlusSparse) {
auto op = CreateArrayOp([](int a, int b) { return a + b; });
auto arg1 = CreateArray<int>({3, std::nullopt, std::nullopt, std::nullopt,
std::nullopt, 3, 4, 5})
.ToSparseForm();
auto arg2 = CreateArray<int>(
{4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt})
.ToSparseForm();
{
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2));
EXPECT_EQ(res.size(), arg1.size());
EXPECT_TRUE(res.IsSparseForm());
EXPECT_FALSE(res.HasMissingIdValue());
EXPECT_TRUE(res.id_filter().IsSame(arg1.id_filter()));
EXPECT_THAT(res, ElementsAre(7, std::nullopt, std::nullopt, std::nullopt,
std::nullopt, 9, std::nullopt, std::nullopt));
}
{
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg2, arg1));
EXPECT_EQ(res.size(), arg1.size());
EXPECT_TRUE(res.IsSparseForm());
EXPECT_FALSE(res.HasMissingIdValue());
EXPECT_TRUE(res.id_filter().IsSame(arg1.id_filter()));
EXPECT_THAT(res, ElementsAre(7, std::nullopt, std::nullopt, std::nullopt,
std::nullopt, 9, std::nullopt, std::nullopt));
}
}
TEST(OpUnionAddTest, WithConst) {
auto op = CreateArrayOp(UnionAddFn<int>());
{
ASSERT_OK_AND_ASSIGN(Array<int> block,
op(Array<int>(10, 2), Array<int>(10, 3)));
EXPECT_TRUE(block.IsConstForm());
EXPECT_EQ(block.missing_id_value(), OptionalValue<int>(5));
}
{
ASSERT_OK_AND_ASSIGN(Array<int> block,
op(Array<int>(10, 2), Array<int>(10, std::nullopt)));
EXPECT_TRUE(block.IsConstForm());
EXPECT_EQ(block.missing_id_value(), OptionalValue<int>(2));
}
{
ASSERT_OK_AND_ASSIGN(
Array<int> block,
op(CreateArray<int>({1, std::nullopt, 2}), Array<int>(3, 5)));
EXPECT_TRUE(block.IsDenseForm());
EXPECT_THAT(block, ElementsAre(6, 5, 7));
}
{
ASSERT_OK_AND_ASSIGN(
Array<int> block,
op(CreateArray<int>({1, std::nullopt, 2}).ToSparseForm(),
Array<int>(3, 5)));
EXPECT_TRUE(block.IsSparseForm());
EXPECT_THAT(block, ElementsAre(6, 5, 7));
}
{
ASSERT_OK_AND_ASSIGN(Array<int> block,
op(CreateArray<int>({1, std::nullopt, 2}),
Array<int>(3, std::nullopt)));
EXPECT_THAT(block, ElementsAre(1, std::nullopt, 2));
}
}
TEST(OpUnionAddTest, DensePlusSparse) {
auto op = CreateArrayOp(UnionAddFn<int>());
Array<int> arg1(DenseArray<int>{CreateBuffer<int>({1, 2, 3, 0, 0, 3, 2, 1})});
{
auto arg2 = CreateArray<int>(
{4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt})
.ToSparseForm();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2));
EXPECT_TRUE(res.IsFullForm());
EXPECT_THAT(res, ElementsAre(5, 9, 6, 0, 3, 9, 2, 1));
}
{
auto arg2 = CreateArray<int>({4, 7, 3, 1, 3, 6, 1, 1}).ToSparseForm(1);
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2));
EXPECT_TRUE(res.IsFullForm());
EXPECT_THAT(res, ElementsAre(5, 9, 6, 1, 3, 9, 3, 2));
}
}
TEST(OpUnionAddTest, SparsePlusSparse) {
auto op = CreateArrayOp(UnionAddFn<int>());
auto arg1 = CreateArray<int>({3, std::nullopt, std::nullopt, std::nullopt,
std::nullopt, 3, 4, 5})
.ToSparseForm();
auto arg2 = CreateArray<int>(
{4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt})
.ToSparseForm();
{
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2));
EXPECT_THAT(res, ElementsAre(7, 7, 3, std::nullopt, 3, 9, 4, 5));
}
{
ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg2, arg1));
EXPECT_THAT(res, ElementsAre(7, 7, 3, std::nullopt, 3, 9, 4, 5));
}
}
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/pointwise_op.h | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/pointwise_op_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
68fb818f-c069-4546-9b9c-dcb7b2294c41 | cpp | tensorflow/tensorflow | seq_interleave_prefetch | tensorflow/core/grappler/optimizers/data/seq_interleave_prefetch.cc | tensorflow/core/grappler/optimizers/data/seq_interleave_prefetch_test.cc | #include "tensorflow/core/grappler/optimizers/data/seq_interleave_prefetch.h"
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include "absl/container/flat_hash_set.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/model.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/grappler/clusters/cluster.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/mutable_graph_view.h"
#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h"
#include "tensorflow/core/grappler/optimizers/data/function_utils.h"
#include "tensorflow/core/grappler/optimizers/data/graph_utils.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/stringpiece.h"
#include "tensorflow/core/platform/types.h"
#include "tsl/platform/errors.h"
namespace tensorflow {
namespace grappler {
namespace {
constexpr char kInterleaveDatasetOpName[] = "InterleaveDataset";
constexpr char kParallelInterleaveDatasetV2OpName[] =
"ParallelInterleaveDatasetV2";
constexpr char kParallelInterleaveDatasetV3OpName[] =
"ParallelInterleaveDatasetV3";
constexpr char kParallelInterleaveDatasetV4OpName[] =
"ParallelInterleaveDatasetV4";
constexpr char kParallelInterleaveDatasetOpName[] = "ParallelInterleaveDataset";
constexpr char kPrefetchDatasetOpName[] = "PrefetchDataset";
constexpr char kDatasetStr[] = "Dataset";
constexpr char kConstOpName[] = "Const";
constexpr char kOutputShapes[] = "output_shapes";
constexpr char kOutputTypes[] = "output_types";
constexpr char kConstNodeOutputSuffix[] = ":output:0";
constexpr char kDatasetNodeOutputSuffix[] = ":handle:0";
constexpr char kDeterministicAttr[] = "deterministic";
constexpr char kFunctionAttr[] = "f";
constexpr char kDTypeAttr[] = "dtype";
constexpr char kValueAttr[] = "value";
constexpr char kTArgumentsAttr[] = "Targuments";
constexpr char kOutputTypesAttr[] = "output_types";
constexpr char kMetadataAttr[] = "metadata";
constexpr char kOutputShapesAttr[] = "output_shapes";
constexpr char kTOutputTypesAttr[] = "Toutput_types";
constexpr char kSeqInterleavePrefetchRewritePrefix[] =
"inject/seq_interleave_prefetch_rewrite_";
bool IsParallelInterleave(const std::string& op) {
return data::MatchesAnyVersion(kParallelInterleaveDatasetOpName, op);
}
int GetNumInputsForParallelInterleaveOp(const std::string& op) {
if (op == kParallelInterleaveDatasetV2OpName) {
return 4;
} else if (op == kParallelInterleaveDatasetV3OpName) {
return 4;
} else if (op == kParallelInterleaveDatasetV4OpName) {
return 6;
}
return 0;
}
bool NodeOpHasDatasetSuffix(const NodeDef& node) {
return absl::EndsWith(node.op(), kDatasetStr);
}
bool DatasetOpInFunction(const NodeDef& node, const FunctionDef* fn) {
for (const auto& node : fn->node_def()) {
if (NodeOpHasDatasetSuffix(node)) {
return true;
}
}
return false;
}
bool RewritePossibleForNode(const NodeDef& node,
const FunctionLibraryDefinition& fld) {
auto is_deterministic_parallel_interleave_node = [&]() -> bool {
if (!IsParallelInterleave(node.op())) return false;
auto determinism_value = node.attr().find(kDeterministicAttr);
return (determinism_value != node.attr().end()) &&
(determinism_value->second.s() == "true");
};
if (node.attr().count(kFunctionAttr) == 0) return false;
const FunctionDef* fn = fld.Find(node.attr().at(kFunctionAttr).func().name());
if (fn == nullptr) return false;
if (fn->signature().output_arg_size() != 1) return false;
if (is_deterministic_parallel_interleave_node()) {
return DatasetOpInFunction(node, fn);
}
return false;
}
NodeDef CreateBufferSizeNode(DataType dtype,
const std::function<void(TensorProto*)>& add_value,
MutableGraphView* graph, FunctionDef& fdef) {
NodeDef node;
node.set_op(kConstOpName);
function_utils::SetUniqueFunctionNodeName(
absl::StrCat(kSeqInterleavePrefetchRewritePrefix, "buffer_size"), &fdef,
&node);
(*node.mutable_attr())[kDTypeAttr].set_type(dtype);
auto tensor = std::make_unique<tensorflow::TensorProto>();
auto tensor_shape = std::make_unique<tensorflow::TensorShapeProto>();
tensor->set_allocated_tensor_shape(tensor_shape.release());
tensor->set_dtype(dtype);
add_value(tensor.get());
(*node.mutable_attr())[kValueAttr].set_allocated_tensor(tensor.release());
return node;
}
Status CreateAndAppendPrefetchNode(MutableGraphView* graph, FunctionDef& fdef) {
auto get_last_dataset_op_node = [&]() -> const NodeDef* {
const auto& output_arg = fdef.signature().output_arg(0).name();
const auto& ret_val = fdef.ret().at(output_arg);
auto input = function_utils::FunctionDefTensorDesc(ret_val);
const NodeDef* dataset_op_node = nullptr;
while (
function_utils::ContainsFunctionNodeWithName(input.node_name, fdef)) {
int idx = function_utils::FindFunctionNodeWithName(input.node_name, fdef);
const NodeDef& node = fdef.node_def(idx);
if (NodeOpHasDatasetSuffix(node)) {
dataset_op_node = &node;
break;
}
input = function_utils::FunctionDefTensorDesc(node.input(0));
}
return dataset_op_node;
};
const NodeDef* add_after = get_last_dataset_op_node();
if (add_after == nullptr) {
return errors::NotFound(
"Could not find any dataset node to append `Prefetch` at its output in "
"`seq_interleave_prefetch` rewrite");
}
NodeDef prefetch_node;
prefetch_node.set_op(kPrefetchDatasetOpName);
function_utils::SetUniqueFunctionNodeName(
absl::StrCat(kSeqInterleavePrefetchRewritePrefix,
fdef.signature().name()),
&fdef, &prefetch_node);
const auto input_dataset =
absl::StrCat(add_after->name(), kDatasetNodeOutputSuffix);
NodeDef buffer_size_node = CreateBufferSizeNode(
DT_INT64,
[](TensorProto* proto) { proto->add_int64_val(data::model::kAutotune); },
graph, fdef);
prefetch_node.add_input(input_dataset);
prefetch_node.add_input(
absl::StrCat(buffer_size_node.name(), kConstNodeOutputSuffix));
if (add_after->attr().count(kOutputShapes) > 0) {
graph_utils::CopyAttribute(kOutputShapes, *add_after, &prefetch_node);
} else {
tensorflow::TensorShapeProto* shape =
(*(prefetch_node.mutable_attr()))[kOutputShapes]
.mutable_list()
->add_shape();
shape->set_unknown_rank(true);
}
if (add_after->attr().count(kOutputTypes) > 0) {
graph_utils::CopyAttribute(kOutputTypes, *add_after, &prefetch_node);
} else if (add_after->attr().count(kTOutputTypesAttr) > 0) {
(*(prefetch_node.mutable_attr()))[kOutputTypes] =
add_after->attr().at(kTOutputTypesAttr);
} else {
(*(prefetch_node.mutable_attr()))[kOutputTypes].mutable_list()->add_type(
tensorflow::DataType::DT_STRING);
}
std::string old_input = input_dataset;
std::string new_input =
absl::StrCat(prefetch_node.name(), kDatasetNodeOutputSuffix);
function_utils::ReplaceReferences(old_input, new_input, &fdef);
*fdef.add_node_def() = std::move(prefetch_node);
*fdef.add_node_def() = std::move(buffer_size_node);
return absl::OkStatus();
}
Status AddInterleaveNode(MutableGraphView* graph,
const NodeDef& parallel_interleave_node,
const std::string& interleave_map_func_name,
absl::flat_hash_set<string>& nodes_to_delete) {
NodeDef interleave_node;
interleave_node.set_op(kInterleaveDatasetOpName);
graph_utils::SetUniqueGraphNodeName(
absl::StrCat(kSeqInterleavePrefetchRewritePrefix,
parallel_interleave_node.name()),
graph->graph(), &interleave_node);
int num_other_args =
parallel_interleave_node.input_size() -
GetNumInputsForParallelInterleaveOp(parallel_interleave_node.op());
int inputs_from_parallel_interleave = 1 + num_other_args +
1 +
1 ;
for (int i = 0; i < inputs_from_parallel_interleave; ++i) {
interleave_node.add_input(parallel_interleave_node.input(i));
}
if (parallel_interleave_node.attr().contains(kTArgumentsAttr)) {
graph_utils::CopyAttribute(kTArgumentsAttr, parallel_interleave_node,
&interleave_node);
}
if (parallel_interleave_node.attr().contains(kOutputTypesAttr)) {
graph_utils::CopyAttribute(kOutputTypesAttr, parallel_interleave_node,
&interleave_node);
}
if (parallel_interleave_node.attr().contains(kOutputShapesAttr)) {
graph_utils::CopyAttribute(kOutputShapesAttr, parallel_interleave_node,
&interleave_node);
}
if (parallel_interleave_node.attr().contains(kMetadataAttr)) {
graph_utils::CopyAttribute(kMetadataAttr, parallel_interleave_node,
&interleave_node);
}
const auto& parallel_interleave_fn_attr =
parallel_interleave_node.attr().at(kFunctionAttr);
(*interleave_node.mutable_attr())[kFunctionAttr] =
parallel_interleave_fn_attr;
(*interleave_node.mutable_attr())[kFunctionAttr].mutable_func()->set_name(
interleave_map_func_name);
graph_utils::CopyShapesAndTypesAttrs(parallel_interleave_node,
&interleave_node);
*interleave_node.mutable_experimental_type() =
parallel_interleave_node.experimental_type();
NodeDef* new_node_graph = graph->AddNode(std::move(interleave_node));
TF_RETURN_IF_ERROR(graph->UpdateFanouts(parallel_interleave_node.name(),
new_node_graph->name()));
nodes_to_delete.insert(parallel_interleave_node.name());
return absl::OkStatus();
}
}
Status SeqInterleavePrefetch::OptimizeAndCollectStats(
Cluster* cluster, const GrapplerItem& item, GraphDef* output,
OptimizationStats* stats) {
*output = item.graph;
MutableGraphView graph(output);
absl::flat_hash_set<string> nodes_to_delete;
FunctionLibraryDefinition fld(OpRegistry::Global(), item.graph.library());
for (const NodeDef& node : item.graph.node()) {
if (!RewritePossibleForNode(node, fld)) continue;
const FunctionDef* parallel_interleave_fn =
fld.Find(node.attr().at("f").func().name());
FunctionDef interleave_fn(*parallel_interleave_fn);
interleave_fn.mutable_signature()->set_name(
absl::StrCat(kSeqInterleavePrefetchRewritePrefix,
parallel_interleave_fn->signature().name()));
TF_RETURN_IF_ERROR(AddInterleaveNode(
&graph, node, interleave_fn.signature().name(), nodes_to_delete));
TF_RETURN_IF_ERROR(CreateAndAppendPrefetchNode(&graph, interleave_fn));
TF_RETURN_IF_ERROR(fld.ReplaceFunction(
parallel_interleave_fn->signature().name(), interleave_fn));
stats->num_changes++;
}
*output->mutable_library() = fld.ToProto();
TF_RETURN_IF_ERROR(graph.DeleteNodes(nodes_to_delete));
return absl::OkStatus();
}
REGISTER_GRAPH_OPTIMIZER_AS(SeqInterleavePrefetch, "seq_interleave_prefetch");
}
} | #include "tensorflow/core/grappler/optimizers/data/seq_interleave_prefetch.h"
#include <string>
#include <gtest/gtest.h>
#include "absl/strings/str_cat.h"
#include "xla/tsl/lib/core/status_test_util.h"
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/optimizers/data/function_utils.h"
#include "tensorflow/core/grappler/optimizers/data/graph_test_utils.h"
#include "tensorflow/core/grappler/optimizers/data/graph_utils.h"
#include "tensorflow/core/platform/status.h"
namespace tensorflow {
namespace grappler {
namespace {
using test::function::GDef;
using test::function::NDef;
constexpr char kPrefetchDatasetOpName[] = "PrefetchDataset";
constexpr char kInterleaveDatasetOpName[] = "InterleaveDataset";
constexpr char kParallelInterleaveDatasetOpName[] =
"ParallelInterleaveDatasetV4";
constexpr char kSeqInterleavePrefetchRewritePrefix[] =
"inject/seq_interleave_prefetch_rewrite_";
constexpr char kFdefProtoStr[] =
R"pb(signature {
name: "parallel_interleave_fdef"
input_arg { name: "args_0" type: DT_STRING }
output_arg { name: "identity" type: DT_VARIANT }
is_stateful: true
control_output: "SSTableDataset"
}
node_def {
name: "key_prefix"
op: "Const"
attr {
key: "dtype"
value { type: DT_STRING }
}
attr {
key: "value"
value {
tensor {
dtype: DT_STRING
tensor_shape {}
string_val: ""
}
}
}
}
node_def {
name: "start_key"
op: "Const"
attr {
key: "dtype"
value { type: DT_STRING }
}
attr {
key: "value"
value {
tensor {
dtype: DT_STRING
tensor_shape {}
string_val: ""
}
}
}
}
node_def {
name: "stop_key"
op: "Const"
attr {
key: "dtype"
value { type: DT_STRING }
}
attr {
key: "value"
value {
tensor {
dtype: DT_STRING
tensor_shape {}
string_val: ""
}
}
}
}
node_def {
name: "SSTableDataset"
op: "SSTableDataset"
input: "args_0"
input: "key_prefix:output:0"
input: "start_key:output:0"
input: "stop_key:output:0"
attr {
key: "metadata"
value { s: "" }
}
attr {
key: "split_size"
value { i: 0 }
}
experimental_type {
type_id: TFT_PRODUCT
args {
type_id: TFT_DATASET
args {
type_id: TFT_TENSOR
args { type_id: TFT_STRING }
}
}
}
}
node_def {
name: "Identity"
op: "Identity"
input: "SSTableDataset:handle:0"
input: "^NoOp"
attr {
key: "T"
value { type: DT_VARIANT }
}
}
node_def { name: "NoOp" op: "NoOp" input: "^SSTableDataset" }
ret { key: "identity" value: "Identity:output:0" }
attr {
key: "_construction_context"
value { s: "kEagerRuntime" }
}
attr {
key: "_tf_data_function"
value { b: true }
}
control_ret { key: "SSTableDataset" value: "SSTableDataset" }
arg_attr {
key: 0
value {
attr {
key: "_output_shapes"
value { list { shape {} } }
}
attr {
key: "_user_specified_name"
value { s: "args_0" }
}
}
})pb";
GraphDef ParallelInterleaveCase(bool deterministic) {
FunctionDef fdef;
protobuf::TextFormat::ParseFromString(kFdefProtoStr, &fdef);
return GDef(
{NDef("stop", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("range", "RangeDataset", {"stop"}, {}),
NDef("cycle_length", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("block_length", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("num_parallel_calls", "Const", {},
{{"value", 1}, {"dtype", DT_INT32}}),
graph_tests_utils::MakeParallelInterleaveV4Node(
"parallel_interleave", "range", "cycle_length", "block_length",
"num_parallel_calls", "parallel_interleave_fdef",
deterministic ? "true" : "false")},
{
fdef,
});
}
GraphDef MultipleParallelInterleaveCase(bool deterministic) {
FunctionDef fdef_1, fdef_2, fdef_3;
protobuf::TextFormat::ParseFromString(kFdefProtoStr, &fdef_1);
fdef_1.mutable_signature()->set_name("parallel_interleave_fdef_1");
protobuf::TextFormat::ParseFromString(kFdefProtoStr, &fdef_2);
fdef_2.mutable_signature()->set_name("parallel_interleave_fdef_2");
protobuf::TextFormat::ParseFromString(kFdefProtoStr, &fdef_3);
fdef_3.mutable_signature()->set_name("parallel_interleave_fdef_3");
auto make_parallel_interleave_node =
[&deterministic](const int node_num, const FunctionDef &fdef) {
return graph_tests_utils::MakeParallelInterleaveV4Node(
absl::StrCat("parallel_interleave_", node_num), "range",
"cycle_length", "block_length", "num_parallel_calls",
fdef.signature().name(), deterministic ? "true" : "false");
};
return GDef(
{NDef("stop", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("range", "RangeDataset", {"stop"}, {}),
NDef("cycle_length", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("block_length", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("num_parallel_calls", "Const", {},
{{"value", 1}, {"dtype", DT_INT32}}),
make_parallel_interleave_node(1, fdef_1),
make_parallel_interleave_node(2, fdef_2),
make_parallel_interleave_node(3, fdef_3)},
{
fdef_1,
fdef_2,
fdef_3,
});
}
GraphDef InterleaveCase(bool deterministic) {
FunctionDef fdef;
protobuf::TextFormat::ParseFromString(kFdefProtoStr, &fdef);
return GDef(
{NDef("stop", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("range", "RangeDataset", {"stop"}, {}),
NDef("cycle_length", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
NDef("block_length", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
graph_tests_utils::MakeInterleaveNode(
"sequential_interleave", "range", "cycle_length", "block_length",
"parallel_interleave_fdef", deterministic ? "true" : "false")},
{
fdef,
});
}
bool PrefetchInFunction(const NodeDef &node,
const FunctionLibraryDefinition &flib) {
auto f_attr_it = node.attr().find("f");
if (f_attr_it == node.attr().end()) return false;
const FunctionDef *func = flib.Find(f_attr_it->second.func().name());
if (func == nullptr) {
return false;
}
for (int i = 0; i < func->node_def_size(); i++) {
NodeDef node_in_func = func->node_def(i);
if (tensorflow::data::MatchesAnyVersion(
kPrefetchDatasetOpName,
node_in_func.op())) {
return true;
}
}
return false;
}
bool IsInterleaveNode(const NodeDef &node) {
return (node.op() == kInterleaveDatasetOpName);
}
}
Status OptimizeWithInjectInterleavePrefetch(const GrapplerItem &item,
GraphDef *output) {
SeqInterleavePrefetch optimizer;
return optimizer.Optimize(nullptr, item, output);
}
class SeqInterleavePrefetchParameterizedTest
: public ::testing::TestWithParam<bool> {};
TEST_P(SeqInterleavePrefetchParameterizedTest,
ParallelInterleaveHasConditionalInjection) {
GrapplerItem item;
bool deterministic = GetParam();
item.graph = ParallelInterleaveCase(deterministic);
item.fetch.push_back("Sink");
GraphDef output;
TF_ASSERT_OK(OptimizeWithInjectInterleavePrefetch(item, &output));
FunctionLibraryDefinition lib_def(OpRegistry::Global(), output.library());
const std::string ¶llel_interleave_fdef_name = "parallel_interleave_fdef";
const std::string &interleave_fdef_name = absl::StrCat(
kSeqInterleavePrefetchRewritePrefix, parallel_interleave_fdef_name);
if (deterministic) {
EXPECT_TRUE(
!graph_utils::ContainsGraphNodeWithName("parallel_interleave", output));
EXPECT_TRUE(!graph_utils::ContainsNodeWithOp(
kParallelInterleaveDatasetOpName, output));
EXPECT_TRUE(
graph_utils::ContainsNodeWithOp(kInterleaveDatasetOpName, output));
for (auto node : output.node()) {
if (!IsInterleaveNode(node)) continue;
EXPECT_TRUE(PrefetchInFunction(node, lib_def));
}
const FunctionDef *parallel_interleave_fdef =
lib_def.Find(parallel_interleave_fdef_name);
const FunctionDef *interleave_fdef = lib_def.Find(interleave_fdef_name);
EXPECT_EQ(parallel_interleave_fdef, nullptr);
EXPECT_NE(interleave_fdef, nullptr);
EXPECT_EQ(lib_def.ListFunctionNames().at(0), interleave_fdef_name);
EXPECT_TRUE(function_utils::FindFunctionNodeWithOp(kPrefetchDatasetOpName,
*interleave_fdef));
} else {
EXPECT_TRUE(graph_utils::ContainsNodeWithOp(
kParallelInterleaveDatasetOpName, output));
EXPECT_TRUE(
!graph_utils::ContainsNodeWithOp(kInterleaveDatasetOpName, output));
EXPECT_TRUE(
graph_utils::ContainsGraphNodeWithName("parallel_interleave", output));
EXPECT_NE(lib_def.Find(parallel_interleave_fdef_name), nullptr);
}
EXPECT_EQ(lib_def.num_functions(), 1);
}
TEST_P(SeqInterleavePrefetchParameterizedTest,
MultipleParallelInterleavesHaveConditionalInjection) {
GrapplerItem item;
bool deterministic = GetParam();
item.graph = MultipleParallelInterleaveCase(deterministic);
item.fetch.push_back("Sink");
GraphDef output;
TF_ASSERT_OK(OptimizeWithInjectInterleavePrefetch(item, &output));
FunctionLibraryDefinition lib_def(OpRegistry::Global(), output.library());
if (deterministic) {
EXPECT_TRUE(!graph_utils::ContainsNodeWithOp(
kParallelInterleaveDatasetOpName, output));
EXPECT_TRUE(
graph_utils::ContainsNodeWithOp(kInterleaveDatasetOpName, output));
for (int i = 1; i <= 3; ++i) {
EXPECT_TRUE(!graph_utils::ContainsGraphNodeWithName(
absl::StrCat("parallel_interleave_", std::to_string(i)), output));
}
for (auto node : output.node()) {
if (!IsInterleaveNode(node)) continue;
EXPECT_TRUE(PrefetchInFunction(node, lib_def));
}
} else {
EXPECT_TRUE(graph_utils::ContainsNodeWithOp(
kParallelInterleaveDatasetOpName, output));
EXPECT_TRUE(
!graph_utils::ContainsNodeWithOp(kInterleaveDatasetOpName, output));
for (int i = 1; i <= 3; ++i) {
EXPECT_TRUE(graph_utils::ContainsGraphNodeWithName(
absl::StrCat("parallel_interleave_", std::to_string(i)), output));
}
}
}
TEST_P(SeqInterleavePrefetchParameterizedTest,
SequentialInterleaveHasNoInjection) {
GrapplerItem item;
item.graph = InterleaveCase(GetParam());
item.fetch.push_back("Sink");
GraphDef output;
TF_ASSERT_OK(OptimizeWithInjectInterleavePrefetch(item, &output));
EXPECT_TRUE(
graph_utils::ContainsNodeWithOp(kInterleaveDatasetOpName, output));
EXPECT_TRUE(
graph_utils::ContainsGraphNodeWithName("sequential_interleave", output));
FunctionLibraryDefinition lib_def(OpRegistry::Global(), output.library());
for (auto node : output.node()) {
if (!IsInterleaveNode(node)) continue;
EXPECT_FALSE(PrefetchInFunction(node, lib_def));
}
}
INSTANTIATE_TEST_SUITE_P(Determinism, SeqInterleavePrefetchParameterizedTest,
::testing::Values(false, true));
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/grappler/optimizers/data/seq_interleave_prefetch.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/grappler/optimizers/data/seq_interleave_prefetch_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
818c848f-fc2a-436f-9cfd-302b0d2cda6a | cpp | abseil/abseil-cpp | hash_policy_testing | absl/container/internal/hash_policy_testing.h | absl/container/internal/hash_policy_testing_test.cc | #ifndef ABSL_CONTAINER_INTERNAL_HASH_POLICY_TESTING_H_
#define ABSL_CONTAINER_INTERNAL_HASH_POLICY_TESTING_H_
#include <cstdlib>
#include <limits>
#include <memory>
#include <ostream>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/hash/hash.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace container_internal {
namespace hash_testing_internal {
template <class Derived>
struct WithId {
WithId() : id_(next_id<Derived>()) {}
WithId(const WithId& that) : id_(that.id_) {}
WithId(WithId&& that) : id_(that.id_) { that.id_ = 0; }
WithId& operator=(const WithId& that) {
id_ = that.id_;
return *this;
}
WithId& operator=(WithId&& that) {
id_ = that.id_;
that.id_ = 0;
return *this;
}
size_t id() const { return id_; }
friend bool operator==(const WithId& a, const WithId& b) {
return a.id_ == b.id_;
}
friend bool operator!=(const WithId& a, const WithId& b) { return !(a == b); }
protected:
explicit WithId(size_t id) : id_(id) {}
private:
size_t id_;
template <class T>
static size_t next_id() {
static size_t gId = 1;
return gId++;
}
};
}
struct NonStandardLayout {
NonStandardLayout() {}
explicit NonStandardLayout(std::string s) : value(std::move(s)) {}
virtual ~NonStandardLayout() {}
friend bool operator==(const NonStandardLayout& a,
const NonStandardLayout& b) {
return a.value == b.value;
}
friend bool operator!=(const NonStandardLayout& a,
const NonStandardLayout& b) {
return a.value != b.value;
}
template <typename H>
friend H AbslHashValue(H h, const NonStandardLayout& v) {
return H::combine(std::move(h), v.value);
}
std::string value;
};
struct StatefulTestingHash
: absl::container_internal::hash_testing_internal::WithId<
StatefulTestingHash> {
template <class T>
size_t operator()(const T& t) const {
return absl::Hash<T>{}(t);
}
};
struct StatefulTestingEqual
: absl::container_internal::hash_testing_internal::WithId<
StatefulTestingEqual> {
template <class T, class U>
bool operator()(const T& t, const U& u) const {
return t == u;
}
};
template <class T = int>
struct Alloc : std::allocator<T> {
using propagate_on_container_swap = std::true_type;
explicit Alloc(size_t id = 0) : id_(id) {}
Alloc(const Alloc&) = default;
Alloc& operator=(const Alloc&) = default;
template <class U>
Alloc(const Alloc<U>& that) : std::allocator<T>(that), id_(that.id()) {}
template <class U>
struct rebind {
using other = Alloc<U>;
};
size_t id() const { return id_; }
friend bool operator==(const Alloc& a, const Alloc& b) {
return a.id_ == b.id_;
}
friend bool operator!=(const Alloc& a, const Alloc& b) { return !(a == b); }
private:
size_t id_ = (std::numeric_limits<size_t>::max)();
};
template <class Map>
auto items(const Map& m) -> std::vector<
std::pair<typename Map::key_type, typename Map::mapped_type>> {
using std::get;
std::vector<std::pair<typename Map::key_type, typename Map::mapped_type>> res;
res.reserve(m.size());
for (const auto& v : m) res.emplace_back(get<0>(v), get<1>(v));
return res;
}
template <class Set>
auto keys(const Set& s)
-> std::vector<typename std::decay<typename Set::key_type>::type> {
std::vector<typename std::decay<typename Set::key_type>::type> res;
res.reserve(s.size());
for (const auto& v : s) res.emplace_back(v);
return res;
}
}
ABSL_NAMESPACE_END
}
#if defined(__GLIBCXX__) && __GLIBCXX__ <= 20140425
#define ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS 0
#else
#define ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS 1
#endif
#endif | #include "absl/container/internal/hash_policy_testing.h"
#include "gtest/gtest.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace container_internal {
namespace {
TEST(_, Hash) {
StatefulTestingHash h1;
EXPECT_EQ(1, h1.id());
StatefulTestingHash h2;
EXPECT_EQ(2, h2.id());
StatefulTestingHash h1c(h1);
EXPECT_EQ(1, h1c.id());
StatefulTestingHash h2m(std::move(h2));
EXPECT_EQ(2, h2m.id());
EXPECT_EQ(0, h2.id());
StatefulTestingHash h3;
EXPECT_EQ(3, h3.id());
h3 = StatefulTestingHash();
EXPECT_EQ(4, h3.id());
h3 = std::move(h1);
EXPECT_EQ(1, h3.id());
}
}
}
ABSL_NAMESPACE_END
} | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_policy_testing.h | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_policy_testing_test.cc | 03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4 |
bb987976-7a50-4c17-970f-4192c7c8ad98 | cpp | google/quiche | connect_tunnel | quiche/quic/tools/connect_tunnel.cc | quiche/quic/tools/connect_tunnel_test.cc | #include "quiche/quic/tools/connect_tunnel.h"
#include <cstdint>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/quic/core/quic_error_codes.h"
#include "quiche/quic/core/quic_server_id.h"
#include "quiche/quic/core/socket_factory.h"
#include "quiche/quic/platform/api/quic_socket_address.h"
#include "quiche/quic/tools/quic_backend_response.h"
#include "quiche/quic/tools/quic_name_lookup.h"
#include "quiche/quic/tools/quic_simple_server_backend.h"
#include "quiche/common/http/http_header_block.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_mem_slice.h"
namespace quic {
namespace {
constexpr size_t kReadSize = 4 * 1024;
std::optional<QuicServerId> ValidateHeadersAndGetAuthority(
const quiche::HttpHeaderBlock& request_headers) {
QUICHE_DCHECK(request_headers.contains(":method"));
QUICHE_DCHECK(request_headers.find(":method")->second == "CONNECT");
QUICHE_DCHECK(!request_headers.contains(":protocol"));
auto scheme_it = request_headers.find(":scheme");
if (scheme_it != request_headers.end()) {
QUICHE_DVLOG(1) << "CONNECT request contains unexpected scheme: "
<< scheme_it->second;
return std::nullopt;
}
auto path_it = request_headers.find(":path");
if (path_it != request_headers.end()) {
QUICHE_DVLOG(1) << "CONNECT request contains unexpected path: "
<< path_it->second;
return std::nullopt;
}
auto authority_it = request_headers.find(":authority");
if (authority_it == request_headers.end() || authority_it->second.empty()) {
QUICHE_DVLOG(1) << "CONNECT request missing authority";
return std::nullopt;
}
std::optional<QuicServerId> server_id =
QuicServerId::ParseFromHostPortString(authority_it->second);
if (!server_id.has_value()) {
QUICHE_DVLOG(1) << "CONNECT request authority is malformed: "
<< authority_it->second;
return std::nullopt;
}
return server_id;
}
bool ValidateAuthority(
const QuicServerId& authority,
const absl::flat_hash_set<QuicServerId>& acceptable_destinations) {
if (acceptable_destinations.contains(authority)) {
return true;
}
QUICHE_DVLOG(1) << "CONNECT request authority: "
<< authority.ToHostPortString()
<< " is not an acceptable allow-listed destiation ";
return false;
}
}
ConnectTunnel::ConnectTunnel(
QuicSimpleServerBackend::RequestHandler* client_stream_request_handler,
SocketFactory* socket_factory,
absl::flat_hash_set<QuicServerId> acceptable_destinations)
: acceptable_destinations_(std::move(acceptable_destinations)),
socket_factory_(socket_factory),
client_stream_request_handler_(client_stream_request_handler) {
QUICHE_DCHECK(client_stream_request_handler_);
QUICHE_DCHECK(socket_factory_);
}
ConnectTunnel::~ConnectTunnel() {
QUICHE_DCHECK_EQ(client_stream_request_handler_, nullptr);
QUICHE_DCHECK(!IsConnectedToDestination());
QUICHE_DCHECK(!receive_started_);
}
void ConnectTunnel::OpenTunnel(const quiche::HttpHeaderBlock& request_headers) {
QUICHE_DCHECK(!IsConnectedToDestination());
std::optional<QuicServerId> authority =
ValidateHeadersAndGetAuthority(request_headers);
if (!authority.has_value()) {
TerminateClientStream(
"invalid request headers",
QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::MESSAGE_ERROR));
return;
}
if (!ValidateAuthority(authority.value(), acceptable_destinations_)) {
TerminateClientStream(
"disallowed request authority",
QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::REQUEST_REJECTED));
return;
}
QuicSocketAddress address =
tools::LookupAddress(AF_UNSPEC, authority.value());
if (!address.IsInitialized()) {
TerminateClientStream("host resolution error");
return;
}
destination_socket_ =
socket_factory_->CreateTcpClientSocket(address,
0,
0,
this);
QUICHE_DCHECK(destination_socket_);
absl::Status connect_result = destination_socket_->ConnectBlocking();
if (!connect_result.ok()) {
TerminateClientStream(
"error connecting TCP socket to destination server: " +
connect_result.ToString());
return;
}
QUICHE_DVLOG(1) << "CONNECT tunnel opened from stream "
<< client_stream_request_handler_->stream_id() << " to "
<< authority.value().ToHostPortString();
SendConnectResponse();
BeginAsyncReadFromDestination();
}
bool ConnectTunnel::IsConnectedToDestination() const {
return !!destination_socket_;
}
void ConnectTunnel::SendDataToDestination(absl::string_view data) {
QUICHE_DCHECK(IsConnectedToDestination());
QUICHE_DCHECK(!data.empty());
absl::Status send_result =
destination_socket_->SendBlocking(std::string(data));
if (!send_result.ok()) {
TerminateClientStream("TCP error sending data to destination server: " +
send_result.ToString());
}
}
void ConnectTunnel::OnClientStreamClose() {
QUICHE_DCHECK(client_stream_request_handler_);
QUICHE_DVLOG(1) << "CONNECT stream "
<< client_stream_request_handler_->stream_id() << " closed";
client_stream_request_handler_ = nullptr;
if (IsConnectedToDestination()) {
destination_socket_->Disconnect();
}
destination_socket_.reset();
}
void ConnectTunnel::ConnectComplete(absl::Status ) {
QUICHE_NOTREACHED();
}
void ConnectTunnel::ReceiveComplete(
absl::StatusOr<quiche::QuicheMemSlice> data) {
QUICHE_DCHECK(IsConnectedToDestination());
QUICHE_DCHECK(receive_started_);
receive_started_ = false;
if (!data.ok()) {
if (client_stream_request_handler_) {
TerminateClientStream("TCP error receiving data from destination server");
} else {
QUICHE_DVLOG(1) << "TCP error receiving data from destination server "
"after stream already closed.";
}
return;
} else if (data.value().empty()) {
OnDestinationConnectionClosed();
return;
}
QUICHE_DCHECK(client_stream_request_handler_);
client_stream_request_handler_->SendStreamData(data.value().AsStringView(),
false);
BeginAsyncReadFromDestination();
}
void ConnectTunnel::SendComplete(absl::Status ) {
QUICHE_NOTREACHED();
}
void ConnectTunnel::BeginAsyncReadFromDestination() {
QUICHE_DCHECK(IsConnectedToDestination());
QUICHE_DCHECK(client_stream_request_handler_);
QUICHE_DCHECK(!receive_started_);
receive_started_ = true;
destination_socket_->ReceiveAsync(kReadSize);
}
void ConnectTunnel::OnDestinationConnectionClosed() {
QUICHE_DCHECK(IsConnectedToDestination());
QUICHE_DCHECK(client_stream_request_handler_);
QUICHE_DVLOG(1) << "CONNECT stream "
<< client_stream_request_handler_->stream_id()
<< " destination connection closed";
destination_socket_->Disconnect();
destination_socket_.reset();
QUICHE_DCHECK(client_stream_request_handler_);
client_stream_request_handler_->SendStreamData("", true);
}
void ConnectTunnel::SendConnectResponse() {
QUICHE_DCHECK(IsConnectedToDestination());
QUICHE_DCHECK(client_stream_request_handler_);
quiche::HttpHeaderBlock response_headers;
response_headers[":status"] = "200";
QuicBackendResponse response;
response.set_headers(std::move(response_headers));
response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE);
client_stream_request_handler_->OnResponseBackendComplete(&response);
}
void ConnectTunnel::TerminateClientStream(absl::string_view error_description,
QuicResetStreamError error_code) {
QUICHE_DCHECK(client_stream_request_handler_);
std::string error_description_str =
error_description.empty() ? ""
: absl::StrCat(" due to ", error_description);
QUICHE_DVLOG(1) << "Terminating CONNECT stream "
<< client_stream_request_handler_->stream_id()
<< " with error code " << error_code.ietf_application_code()
<< error_description_str;
client_stream_request_handler_->TerminateStreamWithError(error_code);
}
} | #include "quiche/quic/tools/connect_tunnel.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/connecting_client_socket.h"
#include "quiche/quic/core/quic_connection_id.h"
#include "quiche/quic/core/quic_error_codes.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/core/socket_factory.h"
#include "quiche/quic/platform/api/quic_socket_address.h"
#include "quiche/quic/platform/api/quic_test_loopback.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/quic/tools/quic_backend_response.h"
#include "quiche/quic/tools/quic_simple_server_backend.h"
#include "quiche/common/http/http_header_block.h"
#include "quiche/common/platform/api/quiche_mem_slice.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace quic::test {
namespace {
using ::testing::_;
using ::testing::AllOf;
using ::testing::AnyOf;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Ge;
using ::testing::Gt;
using ::testing::InvokeWithoutArgs;
using ::testing::IsEmpty;
using ::testing::Matcher;
using ::testing::NiceMock;
using ::testing::Pair;
using ::testing::Property;
using ::testing::Return;
using ::testing::StrictMock;
class MockRequestHandler : public QuicSimpleServerBackend::RequestHandler {
public:
QuicConnectionId connection_id() const override {
return TestConnectionId(41212);
}
QuicStreamId stream_id() const override { return 100; }
std::string peer_host() const override { return "127.0.0.1"; }
MOCK_METHOD(QuicSpdyStream*, GetStream, (), (override));
MOCK_METHOD(void, OnResponseBackendComplete,
(const QuicBackendResponse* response), (override));
MOCK_METHOD(void, SendStreamData, (absl::string_view data, bool close_stream),
(override));
MOCK_METHOD(void, TerminateStreamWithError, (QuicResetStreamError error),
(override));
};
class MockSocketFactory : public SocketFactory {
public:
MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateTcpClientSocket,
(const quic::QuicSocketAddress& peer_address,
QuicByteCount receive_buffer_size,
QuicByteCount send_buffer_size,
ConnectingClientSocket::AsyncVisitor* async_visitor),
(override));
MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>,
CreateConnectingUdpClientSocket,
(const quic::QuicSocketAddress& peer_address,
QuicByteCount receive_buffer_size,
QuicByteCount send_buffer_size,
ConnectingClientSocket::AsyncVisitor* async_visitor),
(override));
};
class MockSocket : public ConnectingClientSocket {
public:
MOCK_METHOD(absl::Status, ConnectBlocking, (), (override));
MOCK_METHOD(void, ConnectAsync, (), (override));
MOCK_METHOD(void, Disconnect, (), (override));
MOCK_METHOD(absl::StatusOr<QuicSocketAddress>, GetLocalAddress, (),
(override));
MOCK_METHOD(absl::StatusOr<quiche::QuicheMemSlice>, ReceiveBlocking,
(QuicByteCount max_size), (override));
MOCK_METHOD(void, ReceiveAsync, (QuicByteCount max_size), (override));
MOCK_METHOD(absl::Status, SendBlocking, (std::string data), (override));
MOCK_METHOD(absl::Status, SendBlocking, (quiche::QuicheMemSlice data),
(override));
MOCK_METHOD(void, SendAsync, (std::string data), (override));
MOCK_METHOD(void, SendAsync, (quiche::QuicheMemSlice data), (override));
};
class ConnectTunnelTest : public quiche::test::QuicheTest {
public:
void SetUp() override {
#if defined(_WIN32)
WSADATA wsa_data;
const WORD version_required = MAKEWORD(2, 2);
ASSERT_EQ(WSAStartup(version_required, &wsa_data), 0);
#endif
auto socket = std::make_unique<StrictMock<MockSocket>>();
socket_ = socket.get();
ON_CALL(socket_factory_,
CreateTcpClientSocket(
AnyOf(QuicSocketAddress(TestLoopback4(), kAcceptablePort),
QuicSocketAddress(TestLoopback6(), kAcceptablePort)),
_, _, &tunnel_))
.WillByDefault(Return(ByMove(std::move(socket))));
}
protected:
static constexpr absl::string_view kAcceptableDestination = "localhost";
static constexpr uint16_t kAcceptablePort = 977;
StrictMock<MockRequestHandler> request_handler_;
NiceMock<MockSocketFactory> socket_factory_;
StrictMock<MockSocket>* socket_;
ConnectTunnel tunnel_{
&request_handler_,
&socket_factory_,
{{std::string(kAcceptableDestination), kAcceptablePort},
{TestLoopback4().ToString(), kAcceptablePort},
{absl::StrCat("[", TestLoopback6().ToString(), "]"), kAcceptablePort}}};
};
TEST_F(ConnectTunnelTest, OpenTunnel) {
EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, ReceiveAsync(Gt(0)));
EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() {
tunnel_.ReceiveComplete(absl::CancelledError());
}));
quiche::HttpHeaderBlock expected_response_headers;
expected_response_headers[":status"] = "200";
QuicBackendResponse expected_response;
expected_response.set_headers(std::move(expected_response_headers));
expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE);
EXPECT_CALL(request_handler_,
OnResponseBackendComplete(
AllOf(Property(&QuicBackendResponse::response_type,
QuicBackendResponse::INCOMPLETE_RESPONSE),
Property(&QuicBackendResponse::headers,
ElementsAre(Pair(":status", "200"))),
Property(&QuicBackendResponse::trailers, IsEmpty()),
Property(&QuicBackendResponse::body, IsEmpty()))));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] =
absl::StrCat(kAcceptableDestination, ":", kAcceptablePort);
tunnel_.OpenTunnel(request_headers);
EXPECT_TRUE(tunnel_.IsConnectedToDestination());
tunnel_.OnClientStreamClose();
EXPECT_FALSE(tunnel_.IsConnectedToDestination());
}
TEST_F(ConnectTunnelTest, OpenTunnelToIpv4LiteralDestination) {
EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, ReceiveAsync(Gt(0)));
EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() {
tunnel_.ReceiveComplete(absl::CancelledError());
}));
quiche::HttpHeaderBlock expected_response_headers;
expected_response_headers[":status"] = "200";
QuicBackendResponse expected_response;
expected_response.set_headers(std::move(expected_response_headers));
expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE);
EXPECT_CALL(request_handler_,
OnResponseBackendComplete(
AllOf(Property(&QuicBackendResponse::response_type,
QuicBackendResponse::INCOMPLETE_RESPONSE),
Property(&QuicBackendResponse::headers,
ElementsAre(Pair(":status", "200"))),
Property(&QuicBackendResponse::trailers, IsEmpty()),
Property(&QuicBackendResponse::body, IsEmpty()))));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] =
absl::StrCat(TestLoopback4().ToString(), ":", kAcceptablePort);
tunnel_.OpenTunnel(request_headers);
EXPECT_TRUE(tunnel_.IsConnectedToDestination());
tunnel_.OnClientStreamClose();
EXPECT_FALSE(tunnel_.IsConnectedToDestination());
}
TEST_F(ConnectTunnelTest, OpenTunnelToIpv6LiteralDestination) {
EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, ReceiveAsync(Gt(0)));
EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() {
tunnel_.ReceiveComplete(absl::CancelledError());
}));
quiche::HttpHeaderBlock expected_response_headers;
expected_response_headers[":status"] = "200";
QuicBackendResponse expected_response;
expected_response.set_headers(std::move(expected_response_headers));
expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE);
EXPECT_CALL(request_handler_,
OnResponseBackendComplete(
AllOf(Property(&QuicBackendResponse::response_type,
QuicBackendResponse::INCOMPLETE_RESPONSE),
Property(&QuicBackendResponse::headers,
ElementsAre(Pair(":status", "200"))),
Property(&QuicBackendResponse::trailers, IsEmpty()),
Property(&QuicBackendResponse::body, IsEmpty()))));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] =
absl::StrCat("[", TestLoopback6().ToString(), "]:", kAcceptablePort);
tunnel_.OpenTunnel(request_headers);
EXPECT_TRUE(tunnel_.IsConnectedToDestination());
tunnel_.OnClientStreamClose();
EXPECT_FALSE(tunnel_.IsConnectedToDestination());
}
TEST_F(ConnectTunnelTest, OpenTunnelWithMalformedRequest) {
EXPECT_CALL(request_handler_,
TerminateStreamWithError(Property(
&QuicResetStreamError::ietf_application_code,
static_cast<uint64_t>(QuicHttp3ErrorCode::MESSAGE_ERROR))));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
tunnel_.OpenTunnel(request_headers);
EXPECT_FALSE(tunnel_.IsConnectedToDestination());
tunnel_.OnClientStreamClose();
}
TEST_F(ConnectTunnelTest, OpenTunnelWithUnacceptableDestination) {
EXPECT_CALL(
request_handler_,
TerminateStreamWithError(Property(
&QuicResetStreamError::ietf_application_code,
static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_REJECTED))));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] = "unacceptable.test:100";
tunnel_.OpenTunnel(request_headers);
EXPECT_FALSE(tunnel_.IsConnectedToDestination());
tunnel_.OnClientStreamClose();
}
TEST_F(ConnectTunnelTest, ReceiveFromDestination) {
static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55";
EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, ReceiveAsync(Ge(kData.size()))).Times(2);
EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() {
tunnel_.ReceiveComplete(absl::CancelledError());
}));
EXPECT_CALL(request_handler_, OnResponseBackendComplete(_));
EXPECT_CALL(request_handler_, SendStreamData(kData, false));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] =
absl::StrCat(kAcceptableDestination, ":", kAcceptablePort);
tunnel_.OpenTunnel(request_headers);
tunnel_.ReceiveComplete(MemSliceFromString(kData));
tunnel_.OnClientStreamClose();
}
TEST_F(ConnectTunnelTest, SendToDestination) {
static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55";
EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, ReceiveAsync(Gt(0)));
EXPECT_CALL(*socket_, SendBlocking(Matcher<std::string>(Eq(kData))))
.WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() {
tunnel_.ReceiveComplete(absl::CancelledError());
}));
EXPECT_CALL(request_handler_, OnResponseBackendComplete(_));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] =
absl::StrCat(kAcceptableDestination, ":", kAcceptablePort);
tunnel_.OpenTunnel(request_headers);
tunnel_.SendDataToDestination(kData);
tunnel_.OnClientStreamClose();
}
TEST_F(ConnectTunnelTest, DestinationDisconnect) {
EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, ReceiveAsync(Gt(0)));
EXPECT_CALL(*socket_, Disconnect());
EXPECT_CALL(request_handler_, OnResponseBackendComplete(_));
EXPECT_CALL(request_handler_, SendStreamData("", true));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] =
absl::StrCat(kAcceptableDestination, ":", kAcceptablePort);
tunnel_.OpenTunnel(request_headers);
tunnel_.ReceiveComplete(quiche::QuicheMemSlice());
EXPECT_FALSE(tunnel_.IsConnectedToDestination());
tunnel_.OnClientStreamClose();
}
TEST_F(ConnectTunnelTest, DestinationTcpConnectionError) {
EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus()));
EXPECT_CALL(*socket_, ReceiveAsync(Gt(0)));
EXPECT_CALL(*socket_, Disconnect());
EXPECT_CALL(request_handler_, OnResponseBackendComplete(_));
EXPECT_CALL(request_handler_,
TerminateStreamWithError(Property(
&QuicResetStreamError::ietf_application_code,
static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR))));
quiche::HttpHeaderBlock request_headers;
request_headers[":method"] = "CONNECT";
request_headers[":authority"] =
absl::StrCat(kAcceptableDestination, ":", kAcceptablePort);
tunnel_.OpenTunnel(request_headers);
tunnel_.ReceiveComplete(absl::UnknownError("error"));
tunnel_.OnClientStreamClose();
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/connect_tunnel.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/connect_tunnel_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
038207ec-d0ae-40ec-acc6-a8a7e593e33f | cpp | tensorflow/tensorflow | xplane_to_kernel_stats_db | tensorflow/core/profiler/convert/xplane_to_kernel_stats_db.cc | tensorflow/core/profiler/convert/xplane_to_kernel_stats_db_test.cc | #include "tensorflow/core/profiler/convert/xplane_to_kernel_stats_db.h"
#include <functional>
#include <ostream>
#include <string>
#include "absl/strings/string_view.h"
#include "xla/tsl/profiler/utils/tf_op_utils.h"
#include "xla/tsl/profiler/utils/tf_xplane_visitor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/protobuf/kernel_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/xplane.pb.h"
#include "tensorflow/core/profiler/utils/gpu_event_stats.h"
#include "tensorflow/core/profiler/utils/kernel_stats_utils.h"
#include "tensorflow/core/profiler/utils/trace_utils.h"
#include "tensorflow/core/profiler/utils/xplane_visitor.h"
namespace tensorflow {
namespace profiler {
void ConvertDeviceTraceXPlaneToKernelReports(
const XPlane& device_trace,
const std::function<void(const GpuEventStats&, KernelReport*)>&
on_kernel_fn,
KernelReportMap* reports) {
XPlaneVisitor plane = tsl::profiler::CreateTfXPlaneVisitor(&device_trace);
plane.ForEachLine([&](const XLineVisitor& line) {
if (IsDerivedThreadId(line.Id())) {
return;
}
line.ForEachEvent([&](const XEventVisitor& event) {
if (event.DurationNs() == 0) return;
KernelReport kernel;
GpuEventStats stats(&event);
if (!stats.IsKernel()) return;
kernel.set_name(std::string(event.Name()));
kernel.set_is_kernel_using_tensor_core(
IsKernelUsingTensorCore(event.Name()));
kernel.set_total_duration_ns(event.DurationNs());
kernel.set_min_duration_ns(event.DurationNs());
kernel.set_max_duration_ns(event.DurationNs());
ParseKernelLaunchParams(stats.kernel_details, &kernel);
if (stats.IsTfOp()) {
tsl::profiler::TfOp tf_op =
tsl::profiler::ParseTfOpFullname(stats.tf_op_fullname);
kernel.set_op_name(std::string(tf_op.name));
bool tensor_core_eligible =
IsEinsumTensorCoreEligible(stats.equation) ||
IsOpTensorCoreEligible(kernel.op_name());
if (!tensor_core_eligible && kernel.is_kernel_using_tensor_core()) {
VLOG(1) << "Detected new Op using TensorCores: " << kernel.op_name()
<< std::endl;
tensor_core_eligible = true;
}
kernel.set_is_op_tensor_core_eligible(tensor_core_eligible);
}
if (on_kernel_fn) {
on_kernel_fn(stats, &kernel);
}
KernelReportValue value;
value.total_duration_ns = event.DurationNs();
value.min_duration_ns = event.DurationNs();
value.max_duration_ns = event.DurationNs();
value.occurrences = 1;
InsertOrUpdateKernelReport(kernel, value, reports);
});
});
}
}
} | #include "tensorflow/core/profiler/convert/xplane_to_kernel_stats_db.h"
#include "absl/strings/string_view.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/protobuf/kernel_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/xplane.pb.h"
#include "tensorflow/core/profiler/utils/kernel_stats_utils.h"
#include "tensorflow/core/profiler/utils/xplane_builder.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/profiler/utils/xplane_test_utils.h"
namespace tensorflow {
namespace profiler {
namespace {
TEST(ConvertXplaneToKernelStats, MultiKernels) {
XSpace space;
XPlane* device_trace = space.add_planes();
XPlaneBuilder device_trace_builder(device_trace);
device_trace_builder.GetOrCreateLine(0);
XLineBuilder line_builder = device_trace_builder.GetOrCreateLine(0);
CreateXEvent(&device_trace_builder, &line_builder, "kernel_name_shortest",
10000, 1000,
{{StatType::kTfOp, "mul_786"},
{StatType::kKernelDetails, R"MULTI(regs:16
static_shared:0
dynamic_shared:0
grid:1,1,1
block:1,1,1
occ_pct:50.0)MULTI"},
{StatType::kEquation, ""}});
CreateXEvent(&device_trace_builder, &line_builder, "kernel_name_middle",
20000, 2000,
{{StatType::kTfOp, "Conv2D"},
{StatType::kKernelDetails, R"MULTI(regs:32
static_shared:0
dynamic_shared:16384
grid:2,1,1
block:32,1,1
occ_pct=13.0)MULTI"},
{StatType::kEquation, ""}});
CreateXEvent(&device_trace_builder, &line_builder,
"volta_fp16_s884gemm_fp16_128x128_ldg8_f2f_tn",
30000, 3000,
{{StatType::kTfOp, "Einsum_80"},
{StatType::kKernelDetails, R"MULTI(regs:32
static_shared:0
dynamic_shared:16384
grid:3,1,1
block:64,1,1
occ_pct:25.0)MULTI"},
{StatType::kEquation, ""}});
KernelReportMap reports;
ConvertDeviceTraceXPlaneToKernelReports(*device_trace, {}, &reports);
KernelStatsDb kernel_stats;
CopyTopKDurationKernelReportsToDb(reports, &kernel_stats);
EXPECT_EQ(kernel_stats.reports_size(), 3);
{
const auto& kernel = kernel_stats.reports().at(2);
EXPECT_EQ(kernel.name(), "kernel_name_shortest");
EXPECT_EQ(kernel.registers_per_thread(), 16);
EXPECT_EQ(kernel.static_shmem_bytes(), 0);
EXPECT_EQ(kernel.dynamic_shmem_bytes(), 0);
EXPECT_EQ(kernel.grid_dim().at(0), 1);
EXPECT_EQ(kernel.grid_dim().at(1), 1);
EXPECT_EQ(kernel.grid_dim().at(2), 1);
EXPECT_EQ(kernel.block_dim().at(0), 1);
EXPECT_EQ(kernel.block_dim().at(1), 1);
EXPECT_EQ(kernel.block_dim().at(2), 1);
EXPECT_EQ(kernel.total_duration_ns(), 1);
EXPECT_FALSE(kernel.is_kernel_using_tensor_core());
EXPECT_FALSE(kernel.is_op_tensor_core_eligible());
EXPECT_EQ(kernel.op_name(), "mul_786");
}
{
const auto& kernel = kernel_stats.reports().at(1);
EXPECT_EQ(kernel.name(), "kernel_name_middle");
EXPECT_EQ(kernel.registers_per_thread(), 32);
EXPECT_EQ(kernel.static_shmem_bytes(), 0);
EXPECT_EQ(kernel.dynamic_shmem_bytes(), 16384);
EXPECT_EQ(kernel.grid_dim().at(0), 2);
EXPECT_EQ(kernel.grid_dim().at(1), 1);
EXPECT_EQ(kernel.grid_dim().at(2), 1);
EXPECT_EQ(kernel.block_dim().at(0), 32);
EXPECT_EQ(kernel.block_dim().at(1), 1);
EXPECT_EQ(kernel.block_dim().at(2), 1);
EXPECT_EQ(kernel.total_duration_ns(), 2);
EXPECT_FALSE(kernel.is_kernel_using_tensor_core());
EXPECT_TRUE(kernel.is_op_tensor_core_eligible());
EXPECT_EQ(kernel.op_name(), "Conv2D");
}
{
const auto& kernel = kernel_stats.reports().at(0);
EXPECT_EQ(kernel.name(), "volta_fp16_s884gemm_fp16_128x128_ldg8_f2f_tn");
EXPECT_EQ(kernel.registers_per_thread(), 32);
EXPECT_EQ(kernel.static_shmem_bytes(), 0);
EXPECT_EQ(kernel.dynamic_shmem_bytes(), 16384);
EXPECT_EQ(kernel.grid_dim().at(0), 3);
EXPECT_EQ(kernel.grid_dim().at(1), 1);
EXPECT_EQ(kernel.grid_dim().at(2), 1);
EXPECT_EQ(kernel.block_dim().at(0), 64);
EXPECT_EQ(kernel.block_dim().at(1), 1);
EXPECT_EQ(kernel.block_dim().at(2), 1);
EXPECT_EQ(kernel.total_duration_ns(), 3);
EXPECT_TRUE(kernel.is_kernel_using_tensor_core());
EXPECT_TRUE(kernel.is_op_tensor_core_eligible());
EXPECT_EQ(kernel.op_name(), "Einsum_80");
}
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/profiler/convert/xplane_to_kernel_stats_db.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/profiler/convert/xplane_to_kernel_stats_db_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
f5ee04c2-fce6-4a1e-9a0e-8ccf8a7ee393 | cpp | google/tsl | numbers | tsl/platform/numbers.cc | tsl/platform/numbers_test.cc | #include "tsl/platform/numbers.h"
#include <ctype.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cinttypes>
#include <cmath>
#include <cstdint>
#include <locale>
#include <unordered_map>
#include "double-conversion/double-conversion.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/stringprintf.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace {
template <typename T>
const std::unordered_map<std::string, T>* GetSpecialNumsSingleton() {
static const std::unordered_map<std::string, T>* special_nums =
CHECK_NOTNULL((new const std::unordered_map<std::string, T>{
{"inf", std::numeric_limits<T>::infinity()},
{"+inf", std::numeric_limits<T>::infinity()},
{"-inf", -std::numeric_limits<T>::infinity()},
{"infinity", std::numeric_limits<T>::infinity()},
{"+infinity", std::numeric_limits<T>::infinity()},
{"-infinity", -std::numeric_limits<T>::infinity()},
{"nan", std::numeric_limits<T>::quiet_NaN()},
{"+nan", std::numeric_limits<T>::quiet_NaN()},
{"-nan", -std::numeric_limits<T>::quiet_NaN()},
}));
return special_nums;
}
template <typename T>
T locale_independent_strtonum(const char* str, const char** endptr) {
auto special_nums = GetSpecialNumsSingleton<T>();
std::stringstream s(str);
std::string special_num_str;
s >> special_num_str;
for (size_t i = 0; i < special_num_str.length(); ++i) {
special_num_str[i] =
std::tolower(special_num_str[i], std::locale::classic());
}
auto entry = special_nums->find(special_num_str);
if (entry != special_nums->end()) {
*endptr = str + (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str))
: s.tellg());
return entry->second;
} else {
if (special_num_str.compare(0, 2, "0x") == 0 ||
special_num_str.compare(0, 3, "-0x") == 0) {
return strtol(str, const_cast<char**>(endptr), 16);
}
}
s.str(str);
s.clear();
s.imbue(std::locale::classic());
T result;
s >> result;
if (s.fail()) {
if (result == std::numeric_limits<T>::max() ||
result == std::numeric_limits<T>::infinity()) {
result = std::numeric_limits<T>::infinity();
s.clear(s.rdstate() & ~std::ios::failbit);
} else if (result == -std::numeric_limits<T>::max() ||
result == -std::numeric_limits<T>::infinity()) {
result = -std::numeric_limits<T>::infinity();
s.clear(s.rdstate() & ~std::ios::failbit);
}
}
if (endptr) {
*endptr =
str +
(s.fail() ? static_cast<std::iostream::pos_type>(0)
: (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str))
: s.tellg()));
}
return result;
}
static inline const double_conversion::StringToDoubleConverter&
StringToFloatConverter() {
static const double_conversion::StringToDoubleConverter converter(
double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES |
double_conversion::StringToDoubleConverter::ALLOW_HEX |
double_conversion::StringToDoubleConverter::ALLOW_TRAILING_SPACES |
double_conversion::StringToDoubleConverter::ALLOW_CASE_INSENSIBILITY,
0., 0., "inf", "nan");
return converter;
}
}
namespace strings {
size_t FastInt32ToBufferLeft(int32_t i, char* buffer) {
uint32_t u = i;
size_t length = 0;
if (i < 0) {
*buffer++ = '-';
++length;
u = 0 - u;
}
length += FastUInt32ToBufferLeft(u, buffer);
return length;
}
size_t FastUInt32ToBufferLeft(uint32_t i, char* buffer) {
char* start = buffer;
do {
*buffer++ = ((i % 10) + '0');
i /= 10;
} while (i > 0);
*buffer = 0;
std::reverse(start, buffer);
return buffer - start;
}
size_t FastInt64ToBufferLeft(int64_t i, char* buffer) {
uint64_t u = i;
size_t length = 0;
if (i < 0) {
*buffer++ = '-';
++length;
u = 0 - u;
}
length += FastUInt64ToBufferLeft(u, buffer);
return length;
}
size_t FastUInt64ToBufferLeft(uint64_t i, char* buffer) {
char* start = buffer;
do {
*buffer++ = ((i % 10) + '0');
i /= 10;
} while (i > 0);
*buffer = 0;
std::reverse(start, buffer);
return buffer - start;
}
static const double kDoublePrecisionCheckMax = DBL_MAX / 1.000000000000001;
size_t DoubleToBuffer(double value, char* buffer) {
static_assert(DBL_DIG < 20, "DBL_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
if (std::abs(value) <= kDoublePrecisionCheckMax) {
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
if (locale_independent_strtonum<double>(buffer, nullptr) == value) {
return snprintf_result;
}
}
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG + 2, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
namespace {
char SafeFirstChar(absl::string_view str) {
if (str.empty()) return '\0';
return str[0];
}
void SkipSpaces(absl::string_view* str) {
while (isspace(SafeFirstChar(*str))) str->remove_prefix(1);
}
}
bool safe_strto64(absl::string_view str, int64_t* value) {
SkipSpaces(&str);
int64_t vlimit = kint64max;
int sign = 1;
if (absl::ConsumePrefix(&str, "-")) {
sign = -1;
vlimit = kint64min;
}
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
if (sign == 1) {
do {
int digit = SafeFirstChar(str) - '0';
if ((vlimit - digit) / 10 < result) {
return false;
}
result = result * 10 + digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
} else {
do {
int digit = SafeFirstChar(str) - '0';
if ((vlimit + digit) / 10 > result) {
return false;
}
result = result * 10 - digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
}
SkipSpaces(&str);
if (!str.empty()) return false;
*value = result;
return true;
}
bool safe_strtou64(absl::string_view str, uint64_t* value) {
SkipSpaces(&str);
if (!isdigit(SafeFirstChar(str))) return false;
uint64_t result = 0;
do {
int digit = SafeFirstChar(str) - '0';
if ((kuint64max - digit) / 10 < result) {
return false;
}
result = result * 10 + digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = result;
return true;
}
bool safe_strto32(absl::string_view str, int32_t* value) {
SkipSpaces(&str);
int64_t vmax = kint32max;
int sign = 1;
if (absl::ConsumePrefix(&str, "-")) {
sign = -1;
++vmax;
}
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
do {
result = result * 10 + SafeFirstChar(str) - '0';
if (result > vmax) {
return false;
}
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = static_cast<int32_t>(result * sign);
return true;
}
bool safe_strtou32(absl::string_view str, uint32_t* value) {
SkipSpaces(&str);
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
do {
result = result * 10 + SafeFirstChar(str) - '0';
if (result > kuint32max) {
return false;
}
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = static_cast<uint32_t>(result);
return true;
}
bool safe_strtof(absl::string_view str, float* value) {
int processed_characters_count = -1;
auto len = str.size();
if (len >= kFastToBufferSize) return false;
if (len > std::numeric_limits<int>::max()) return false;
*value = StringToFloatConverter().StringToFloat(
str.data(), static_cast<int>(len), &processed_characters_count);
return processed_characters_count > 0;
}
bool safe_strtod(absl::string_view str, double* value) {
int processed_characters_count = -1;
auto len = str.size();
if (len >= kFastToBufferSize) return false;
if (len > std::numeric_limits<int>::max()) return false;
*value = StringToFloatConverter().StringToDouble(
str.data(), static_cast<int>(len), &processed_characters_count);
return processed_characters_count > 0;
}
size_t FloatToBuffer(float value, char* buffer) {
static_assert(FLT_DIG < 10, "FLT_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
float parsed_value;
if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) {
snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG + 3, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
}
return snprintf_result;
}
std::string FpToString(Fprint fp) {
char buf[17];
snprintf(buf, sizeof(buf), "%016llx", static_cast<long long>(fp));
return std::string(buf);
}
bool StringToFp(const std::string& s, Fprint* fp) {
char junk;
uint64_t result;
if (sscanf(s.c_str(), "%" SCNx64 "%c", &result, &junk) == 1) {
*fp = result;
return true;
} else {
return false;
}
}
absl::string_view Uint64ToHexString(uint64_t v, char* buf) {
static const char* hexdigits = "0123456789abcdef";
const int num_byte = 16;
buf[num_byte] = '\0';
for (int i = num_byte - 1; i >= 0; i--) {
buf[i] = hexdigits[v & 0xf];
v >>= 4;
}
return absl::string_view(buf, num_byte);
}
bool HexStringToUint64(const absl::string_view& s, uint64_t* result) {
uint64_t v = 0;
if (s.empty()) {
return false;
}
for (size_t i = 0; i < s.size(); i++) {
char c = s[i];
if (c >= '0' && c <= '9') {
v = (v << 4) + (c - '0');
} else if (c >= 'a' && c <= 'f') {
v = (v << 4) + 10 + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
v = (v << 4) + 10 + (c - 'A');
} else {
return false;
}
}
*result = v;
return true;
}
std::string HumanReadableNum(int64_t value) {
std::string s;
if (value < 0) {
s += "-";
value = -value;
}
if (value < 1000) {
Appendf(&s, "%lld", static_cast<long long>(value));
} else if (value >= static_cast<int64_t>(1e15)) {
Appendf(&s, "%0.3G", static_cast<double>(value));
} else {
static const char units[] = "kMBT";
const char* unit = units;
while (value >= static_cast<int64_t>(1000000)) {
value /= static_cast<int64_t>(1000);
++unit;
CHECK(unit < units + TF_ARRAYSIZE(units));
}
Appendf(&s, "%.2f%c", value / 1000.0, *unit);
}
return s;
}
std::string HumanReadableNumBytes(int64_t num_bytes) {
if (num_bytes == kint64min) {
return "-8E";
}
const char* neg_str = (num_bytes < 0) ? "-" : "";
if (num_bytes < 0) {
num_bytes = -num_bytes;
}
if (num_bytes < 1024) {
char buf[8];
snprintf(buf, sizeof(buf), "%s%lldB", neg_str,
static_cast<long long>(num_bytes));
return std::string(buf);
}
static const char units[] = "KMGTPE";
const char* unit = units;
while (num_bytes >= static_cast<int64_t>(1024) * 1024) {
num_bytes /= 1024;
++unit;
CHECK(unit < units + TF_ARRAYSIZE(units));
}
char buf[16];
snprintf(buf, sizeof(buf), ((*unit == 'K') ? "%s%.1f%ciB" : "%s%.2f%ciB"),
neg_str, num_bytes / 1024.0, *unit);
return std::string(buf);
}
std::string HumanReadableElapsedTime(double seconds) {
std::string human_readable;
if (seconds < 0) {
human_readable = "-";
seconds = -seconds;
}
const double microseconds = seconds * 1.0e6;
if (microseconds < 999.5) {
strings::Appendf(&human_readable, "%0.3g us", microseconds);
return human_readable;
}
double milliseconds = seconds * 1e3;
if (milliseconds >= .995 && milliseconds < 1) {
milliseconds = 1.0;
}
if (milliseconds < 999.5) {
strings::Appendf(&human_readable, "%0.3g ms", milliseconds);
return human_readable;
}
if (seconds < 60.0) {
strings::Appendf(&human_readable, "%0.3g s", seconds);
return human_readable;
}
seconds /= 60.0;
if (seconds < 60.0) {
strings::Appendf(&human_readable, "%0.3g min", seconds);
return human_readable;
}
seconds /= 60.0;
if (seconds < 24.0) {
strings::Appendf(&human_readable, "%0.3g h", seconds);
return human_readable;
}
seconds /= 24.0;
if (seconds < 30.0) {
strings::Appendf(&human_readable, "%0.3g days", seconds);
return human_readable;
}
if (seconds < 365.2425) {
strings::Appendf(&human_readable, "%0.3g months", seconds / 30.436875);
return human_readable;
}
seconds /= 365.2425;
strings::Appendf(&human_readable, "%0.3g years", seconds);
return human_readable;
}
}
} | #include "tsl/platform/numbers.h"
#include <cmath>
#include <string>
#include "tsl/platform/test.h"
namespace tsl {
namespace strings {
TEST(FpToString, Ints) {
for (int s = 0; s < 64; s++) {
for (int delta = -1; delta <= 1; delta++) {
uint64 fp = (1ull << s) + delta;
string s = FpToString(fp);
uint64 fp2;
EXPECT_TRUE(StringToFp(s, &fp2));
EXPECT_EQ(fp, fp2);
}
}
Fprint dummy;
EXPECT_FALSE(StringToFp("", &dummy));
EXPECT_FALSE(StringToFp("xyz", &dummy));
EXPECT_FALSE(StringToFp("0000000000000000xyz", &dummy));
}
TEST(Uint64ToHexString, Ints) {
for (int s = 0; s < 64; s++) {
for (int delta = -1; delta <= 1; delta++) {
uint64 fp = (1ull << s) + delta;
char buf[kFastToBufferSize];
absl::string_view s = Uint64ToHexString(fp, buf);
uint64 fp2;
EXPECT_TRUE(HexStringToUint64(s, &fp2));
EXPECT_EQ(fp, fp2) << s;
}
}
uint64 dummy;
EXPECT_FALSE(HexStringToUint64("", &dummy));
EXPECT_FALSE(HexStringToUint64("xyz", &dummy));
EXPECT_FALSE(HexStringToUint64("0000000000000000xyz", &dummy));
}
TEST(HumanReadableNum, Basic) {
EXPECT_EQ(HumanReadableNum(823), "823");
EXPECT_EQ(HumanReadableNum(1024), "1.02k");
EXPECT_EQ(HumanReadableNum(4000), "4.00k");
EXPECT_EQ(HumanReadableNum(999499), "999.50k");
EXPECT_EQ(HumanReadableNum(1000000), "1.00M");
EXPECT_EQ(HumanReadableNum(1048575), "1.05M");
EXPECT_EQ(HumanReadableNum(1048576), "1.05M");
EXPECT_EQ(HumanReadableNum(23956812342), "23.96B");
EXPECT_EQ(HumanReadableNum(123456789012345678), "1.23E+17");
}
TEST(HumanReadableNumBytes, Bytes) {
EXPECT_EQ("0B", HumanReadableNumBytes(0));
EXPECT_EQ("4B", HumanReadableNumBytes(4));
EXPECT_EQ("1023B", HumanReadableNumBytes(1023));
EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1024));
EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1025));
EXPECT_EQ("1.5KiB", HumanReadableNumBytes(1500));
EXPECT_EQ("1.9KiB", HumanReadableNumBytes(1927));
EXPECT_EQ("2.0KiB", HumanReadableNumBytes(2048));
EXPECT_EQ("1.00MiB", HumanReadableNumBytes(1 << 20));
EXPECT_EQ("11.77MiB", HumanReadableNumBytes(12345678));
EXPECT_EQ("1.00GiB", HumanReadableNumBytes(1 << 30));
EXPECT_EQ("1.00TiB", HumanReadableNumBytes(1LL << 40));
EXPECT_EQ("1.00PiB", HumanReadableNumBytes(1LL << 50));
EXPECT_EQ("1.00EiB", HumanReadableNumBytes(1LL << 60));
EXPECT_EQ("-1B", HumanReadableNumBytes(-1));
EXPECT_EQ("-4B", HumanReadableNumBytes(-4));
EXPECT_EQ("-1000B", HumanReadableNumBytes(-1000));
EXPECT_EQ("-11.77MiB", HumanReadableNumBytes(-12345678));
EXPECT_EQ("-8E", HumanReadableNumBytes(kint64min));
}
TEST(HumanReadableElapsedTime, Basic) {
EXPECT_EQ(HumanReadableElapsedTime(-10), "-10 s");
EXPECT_EQ(HumanReadableElapsedTime(-0.001), "-1 ms");
EXPECT_EQ(HumanReadableElapsedTime(-60.0), "-1 min");
EXPECT_EQ(HumanReadableElapsedTime(0.00000001), "0.01 us");
EXPECT_EQ(HumanReadableElapsedTime(0.0000012), "1.2 us");
EXPECT_EQ(HumanReadableElapsedTime(0.0012), "1.2 ms");
EXPECT_EQ(HumanReadableElapsedTime(0.12), "120 ms");
EXPECT_EQ(HumanReadableElapsedTime(1.12), "1.12 s");
EXPECT_EQ(HumanReadableElapsedTime(90.0), "1.5 min");
EXPECT_EQ(HumanReadableElapsedTime(600.0), "10 min");
EXPECT_EQ(HumanReadableElapsedTime(9000.0), "2.5 h");
EXPECT_EQ(HumanReadableElapsedTime(87480.0), "1.01 days");
EXPECT_EQ(HumanReadableElapsedTime(7776000.0), "2.96 months");
EXPECT_EQ(HumanReadableElapsedTime(78840000.0), "2.5 years");
EXPECT_EQ(HumanReadableElapsedTime(382386614.40), "12.1 years");
EXPECT_EQ(HumanReadableElapsedTime(DBL_MAX), "5.7e+300 years");
}
TEST(safe_strto32, Int32s) {
int32 result;
EXPECT_EQ(true, safe_strto32("1", &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto32("123", &result));
EXPECT_EQ(123, result);
EXPECT_EQ(true, safe_strto32(" -123 ", &result));
EXPECT_EQ(-123, result);
EXPECT_EQ(true, safe_strto32("2147483647", &result));
EXPECT_EQ(2147483647, result);
EXPECT_EQ(true, safe_strto32("-2147483648", &result));
EXPECT_EQ(-2147483648, result);
EXPECT_EQ(false, safe_strto32(" 132as ", &result));
EXPECT_EQ(false, safe_strto32(" 132.2 ", &result));
EXPECT_EQ(false, safe_strto32(" -", &result));
EXPECT_EQ(false, safe_strto32("", &result));
EXPECT_EQ(false, safe_strto32(" ", &result));
EXPECT_EQ(false, safe_strto32("123 a", &result));
EXPECT_EQ(false, safe_strto32("2147483648", &result));
EXPECT_EQ(false, safe_strto32("-2147483649", &result));
EXPECT_EQ(true, safe_strto32(absl::string_view("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto32(absl::string_view(" -123", 4), &result));
EXPECT_EQ(-12, result);
EXPECT_EQ(false, safe_strto32(absl::string_view(nullptr, 0), &result));
}
TEST(safe_strtou32, UInt32s) {
uint32 result;
EXPECT_TRUE(safe_strtou32("0", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtou32("1", &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou32("123", &result));
EXPECT_EQ(123, result);
EXPECT_TRUE(safe_strtou32("4294967295", &result));
EXPECT_EQ(4294967295, result);
EXPECT_FALSE(safe_strtou32(" 132as ", &result));
EXPECT_FALSE(safe_strtou32(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou32(" -", &result));
EXPECT_FALSE(safe_strtou32("", &result));
EXPECT_FALSE(safe_strtou32(" ", &result));
EXPECT_FALSE(safe_strtou32("123 a", &result));
EXPECT_FALSE(safe_strtou32("123 456", &result));
EXPECT_FALSE(safe_strtou32("4294967296", &result));
EXPECT_FALSE(safe_strtou32("-1", &result));
EXPECT_TRUE(safe_strtou32(absl::string_view("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou32(absl::string_view(" 123", 3), &result));
EXPECT_EQ(12, result);
EXPECT_FALSE(safe_strtou32(absl::string_view(nullptr, 0), &result));
}
TEST(safe_strto64, Int64s) {
int64 result;
EXPECT_EQ(true, safe_strto64("1", &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto64("123", &result));
EXPECT_EQ(123, result);
EXPECT_EQ(true, safe_strto64(" -123 ", &result));
EXPECT_EQ(-123, result);
EXPECT_EQ(true, safe_strto64("9223372036854775807", &result));
EXPECT_EQ(9223372036854775807, result);
EXPECT_EQ(true, safe_strto64("-9223372036854775808", &result));
EXPECT_EQ(kint64min, result);
EXPECT_EQ(false, safe_strto64(" 132as ", &result));
EXPECT_EQ(false, safe_strto64(" 132.2 ", &result));
EXPECT_EQ(false, safe_strto64(" -", &result));
EXPECT_EQ(false, safe_strto64("", &result));
EXPECT_EQ(false, safe_strto64(" ", &result));
EXPECT_EQ(false, safe_strto64("123 a", &result));
EXPECT_EQ(false, safe_strto64("9223372036854775808", &result));
EXPECT_EQ(false, safe_strto64("-9223372036854775809", &result));
EXPECT_EQ(true, safe_strto64(absl::string_view("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto64(absl::string_view(" -123", 4), &result));
EXPECT_EQ(-12, result);
EXPECT_EQ(false, safe_strto64(absl::string_view(nullptr, 0), &result));
}
TEST(safe_strtou64, UInt64s) {
uint64 result;
EXPECT_TRUE(safe_strtou64("0", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtou64("1", &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou64("123", &result));
EXPECT_EQ(123, result);
EXPECT_TRUE(safe_strtou64(" 345 ", &result));
EXPECT_EQ(345, result);
EXPECT_TRUE(safe_strtou64("18446744073709551615", &result));
EXPECT_EQ(18446744073709551615UL, result);
EXPECT_FALSE(safe_strtou64(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou64(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou64(" -", &result));
EXPECT_FALSE(safe_strtou64("", &result));
EXPECT_FALSE(safe_strtou64(" ", &result));
EXPECT_FALSE(safe_strtou64("123 a", &result));
EXPECT_FALSE(safe_strtou64("123 456", &result));
EXPECT_FALSE(safe_strtou64("18446744073709551616", &result));
EXPECT_FALSE(safe_strtou64("-1", &result));
EXPECT_TRUE(safe_strtou64(absl::string_view("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou64(absl::string_view(" 123", 3), &result));
EXPECT_EQ(12, result);
EXPECT_FALSE(safe_strtou64(absl::string_view(nullptr, 0), &result));
}
TEST(safe_strtof, Float) {
float result = 0;
EXPECT_TRUE(safe_strtof("0.123456", &result));
EXPECT_EQ(0.123456f, result);
EXPECT_FALSE(safe_strtof("0.12345abc", &result));
EXPECT_TRUE(safe_strtof("1e39", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("-1e39", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("1e-50", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtof("0xF", &result));
EXPECT_EQ(0xF, result);
EXPECT_TRUE(safe_strtof("-0x2A", &result));
EXPECT_EQ(-42.0f, result);
EXPECT_TRUE(safe_strtof(" -0x2", &result));
EXPECT_EQ(-2.0f, result);
EXPECT_TRUE(safe_strtof("8 \t", &result));
EXPECT_EQ(8.0f, result);
EXPECT_TRUE(safe_strtof("\t20.0\t ", &result));
EXPECT_EQ(20.0f, result);
EXPECT_FALSE(safe_strtof("-infinity is awesome", &result));
char test_str[2 * kFastToBufferSize];
for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a';
test_str[kFastToBufferSize + 1] = '\0';
EXPECT_FALSE(safe_strtof(test_str, &result));
EXPECT_TRUE(safe_strtof("-inf", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("+inf", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("InF", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("-INF", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("-nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("-NaN", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("+NAN", &result));
EXPECT_TRUE(std::isnan(result));
}
TEST(safe_strtod, Double) {
double result = 0;
EXPECT_TRUE(safe_strtod("0.1234567890123", &result));
EXPECT_EQ(0.1234567890123, result);
EXPECT_FALSE(safe_strtod("0.1234567890123abc", &result));
char test_str[2 * kFastToBufferSize];
for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a';
test_str[kFastToBufferSize + 1] = '\0';
EXPECT_FALSE(safe_strtod(test_str, &result));
EXPECT_TRUE(safe_strtod("1e310", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("-1e310", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("1e-325", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtod(" -0x1c", &result));
EXPECT_EQ(-28.0, result);
EXPECT_TRUE(safe_strtod("50 \t", &result));
EXPECT_EQ(50.0, result);
EXPECT_TRUE(safe_strtod("\t82.0\t ", &result));
EXPECT_EQ(82.0, result);
EXPECT_FALSE(safe_strtod("infinity", &result));
EXPECT_TRUE(safe_strtod("-inf", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("+inf", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("InF", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("-INF", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("-nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("-NaN", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("+NAN", &result));
EXPECT_TRUE(std::isnan(result));
}
}
} | https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/numbers.cc | https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/numbers_test.cc | 6d708fdcdd4f40537b7fa273371215a6fa3d4423 |
8ea32162-2193-47e5-a498-0124570cc283 | cpp | tensorflow/tensorflow | register_span | tensorflow/core/tfrt/mlrt/interpreter/register_span.h | tensorflow/core/tfrt/mlrt/interpreter/register_span_test.cc | #ifndef TENSORFLOW_CORE_TFRT_MLRT_INTERPRETER_REGISTER_SPAN_H_
#define TENSORFLOW_CORE_TFRT_MLRT_INTERPRETER_REGISTER_SPAN_H_
#include <iterator>
#include "absl/types/span.h"
#include "tensorflow/core/tfrt/mlrt/bytecode/bytecode.h"
#include "tensorflow/core/tfrt/mlrt/bytecode/span.h"
#include "tensorflow/core/tfrt/mlrt/interpreter/iterator.h"
#include "tensorflow/core/tfrt/mlrt/interpreter/value.h"
namespace mlrt {
class RegisterIterator
: public iterator_internal::IteratorBase<RegisterIterator, Value,
absl::Span<Value>> {
public:
using IteratorBase<RegisterIterator, Value, absl::Span<Value>>::IteratorBase;
};
class ConstRegisterIterator
: public iterator_internal::IteratorBase<ConstRegisterIterator, const Value,
absl::Span<const Value>> {
using IteratorBase<ConstRegisterIterator, const Value,
absl::Span<const Value>>::IteratorBase;
};
class RegisterSpan {
public:
using value_type = Value;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using reference = Value&;
using const_reference = const Value&;
using pointer = Value*;
using const_pointer = const Value*;
using iterator = RegisterIterator;
using const_iterator = ConstRegisterIterator;
RegisterSpan() = default;
RegisterSpan(bc::Span<uint32_t> reg_indices, absl::Span<Value> regs)
: reg_indices_(reg_indices), regs_(regs) {}
Value& operator[](size_t idx) { return regs_[reg_indices_[idx]]; }
const Value& operator[](size_t idx) const { return regs_[reg_indices_[idx]]; }
Value& back() const { return regs_[reg_indices_.back()]; }
size_t size() const { return reg_indices_.size(); }
iterator begin() const { return iterator(reg_indices_.begin(), regs_); }
iterator end() const { return iterator(reg_indices_.end(), regs_); }
RegisterSpan drop_front(int num = 1) {
return RegisterSpan(reg_indices_.drop_front(num), regs_);
}
RegisterSpan drop_back(int num = 1) {
return RegisterSpan(reg_indices_.drop_back(num), regs_);
}
private:
bc::Span<uint32_t> reg_indices_;
absl::Span<Value> regs_;
};
template <typename T>
class RegisterValueIterator {
using Iter = RegisterValueIterator;
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;
explicit RegisterValueIterator(RegisterIterator reg_iter)
: reg_iter_(reg_iter) {}
reference operator*() const { return (*reg_iter_).Get<T>(); }
pointer operator->() const { return &(*reg_iter_).Get<T>(); }
reference operator[](difference_type i) const {
return (*(reg_iter_ + i)).Get<T>();
}
Iter& operator+=(difference_type d) {
reg_iter_ += d;
return *this;
}
Iter& operator-=(difference_type d) {
reg_iter_ -= d;
return *this;
}
Iter& operator++() {
++reg_iter_;
return *this;
}
Iter operator++(int) {
Iter r = *this;
++reg_iter_;
return r;
}
Iter& operator--() {
--reg_iter_;
return *this;
}
Iter operator--(int) {
Iter r = *this;
--reg_iter_;
return r;
}
Iter operator+(difference_type d) const {
Iter r = *this;
r += d;
return r;
}
friend Iter operator+(difference_type d, const Iter& i) { return i + d; }
Iter operator-(difference_type d) const {
Iter r = *this;
r -= d;
return r;
}
difference_type operator-(const Iter& other) const {
return reg_iter_ - other.reg_iter_;
}
friend bool operator==(const Iter& a, const Iter& b) {
return a.reg_iter_ == b.reg_iter_;
}
friend bool operator!=(const Iter& a, const Iter& b) {
return a.reg_iter_ != b.reg_iter_;
}
friend bool operator<(const Iter& a, const Iter& b) {
return a.reg_iter_ < b.reg_iter_;
}
friend bool operator<=(const Iter& a, const Iter& b) {
return a.reg_iter_ <= b.reg_iter_;
}
friend bool operator>(const Iter& a, const Iter& b) {
return a.reg_iter_ > b.reg_iter_;
}
friend bool operator>=(const Iter& a, const Iter& b) {
return a.reg_iter_ >= b.reg_iter_;
}
private:
RegisterIterator reg_iter_;
};
template <typename T>
class RegisterValueSpan {
public:
using value_type = T;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using iterator = RegisterValueIterator<T>;
using const_iterator = RegisterValueIterator<const T>;
RegisterValueSpan(bc::Span<uint32_t> reg_indices, absl::Span<Value> regs)
: reg_span_(reg_indices, regs) {}
RegisterValueSpan(RegisterSpan reg_span) : reg_span_(reg_span) {}
T& operator[](size_t idx) { return reg_span_[idx].Get<T>(); }
const T& operator[](size_t idx) const { return reg_span_[idx].Get<T>(); }
void Destroy(size_t idx) { reg_span_[idx].Destroy<T>(); }
size_t size() const { return reg_span_.size(); }
iterator begin() const { return iterator(reg_span_.begin()); }
iterator end() const { return iterator(reg_span_.end()); }
bool empty() const { return size() == 0; }
RegisterValueSpan drop_front(int num = 1) {
return reg_span_.drop_front(num);
}
RegisterValueSpan drop_back(int num = 1) { return reg_span_.drop_back(num); }
RegisterSpan reg_span() const { return reg_span_; }
private:
RegisterSpan reg_span_;
};
}
#endif | #include "tensorflow/core/tfrt/mlrt/interpreter/register_span.h"
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/types/span.h"
#include "tensorflow/core/tfrt/mlrt/bytecode/bytecode.h"
#include "tensorflow/core/tfrt/mlrt/interpreter/value.h"
namespace mlrt {
namespace {
TEST(RegisterSpan, RegisterSpan) {
std::vector<Value> regs(4);
regs[0].Set<int>(0);
regs[1].Set<int>(1);
regs[2].Set<int>(2);
regs[3].Set<int>(3);
bc::Buffer buffer;
bc::Allocator allocator(&buffer);
auto reg_indices_ctor =
bc::New<bc::Vector<uint32_t>>(&allocator, std::vector<uint32_t>{1, 2});
bc::Vector<uint32_t> reg_indices(buffer.Get(reg_indices_ctor.address()));
RegisterSpan reg_span(reg_indices, absl::MakeSpan(regs));
ASSERT_EQ(reg_span.size(), 2);
EXPECT_EQ(reg_span[0].Get<int>(), 1);
EXPECT_EQ(reg_span[1].Get<int>(), 2);
EXPECT_THAT(RegisterValueSpan<int>(reg_span),
::testing::ElementsAreArray({1, 2}));
}
TEST(RegisterSpan, RegisterSpanToStdVector) {
std::vector<Value> regs(4);
regs[0].Set<int>(0);
regs[1].Set<int>(1);
regs[2].Set<int>(2);
regs[3].Set<int>(3);
bc::Buffer buffer;
bc::Allocator allocator(&buffer);
auto reg_indices_ctor =
bc::New<bc::Vector<uint32_t>>(&allocator, std::vector<uint32_t>{1, 2});
bc::Vector<uint32_t> reg_indices(buffer.Get(reg_indices_ctor.address()));
RegisterSpan reg_span(reg_indices, absl::MakeSpan(regs));
std::vector<Value> subset(reg_span.begin(), reg_span.end());
ASSERT_EQ(subset.size(), 2);
EXPECT_EQ(subset[0].Get<int>(), 1);
EXPECT_EQ(subset[1].Get<int>(), 2);
}
TEST(RegisterSpan, RegisterValueSpan) {
std::vector<Value> regs(4);
regs[0].Set<int>(0);
regs[1].Set<int>(1);
regs[2].Set<int>(2);
regs[3].Set<int>(3);
bc::Buffer buffer;
bc::Allocator allocator(&buffer);
auto reg_indices_ctor =
bc::New<bc::Vector<uint32_t>>(&allocator, std::vector<uint32_t>{1, 3});
bc::Vector<uint32_t> reg_indices(buffer.Get(reg_indices_ctor.address()));
RegisterValueSpan<int> reg_span(reg_indices, absl::MakeSpan(regs));
ASSERT_EQ(reg_span.size(), 2);
EXPECT_EQ(reg_span[0], 1);
EXPECT_EQ(reg_span[1], 3);
EXPECT_THAT(reg_span, ::testing::ElementsAreArray({1, 3}));
}
TEST(RegisterSpan, Modifiers) {
std::vector<Value> regs(4);
regs[0].Set<int>(0);
regs[1].Set<int>(1);
regs[2].Set<int>(2);
regs[3].Set<int>(3);
bc::Buffer buffer;
bc::Allocator allocator(&buffer);
auto reg_indices_ctor = bc::New<bc::Vector<uint32_t>>(
&allocator, std::vector<uint32_t>{0, 2, 1, 3});
bc::Vector<uint32_t> reg_indices(buffer.Get(reg_indices_ctor.address()));
RegisterSpan reg_span(reg_indices, absl::MakeSpan(regs));
RegisterValueSpan<int> reg_value_span(reg_span);
EXPECT_THAT(RegisterValueSpan<int>(reg_span.drop_back(2)),
::testing::ElementsAreArray({0, 2}));
EXPECT_THAT(reg_value_span.drop_front(2),
::testing::ElementsAreArray({1, 3}));
reg_value_span.Destroy(1);
EXPECT_FALSE(regs[2].HasValue());
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/tfrt/mlrt/interpreter/register_span.h | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/tfrt/mlrt/interpreter/register_span_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
b1ba6c91-c123-4aa3-ad58-8bf8217b1498 | cpp | tensorflow/tensorflow | top_n | tensorflow/lite/kernels/ctc/top_n.h | tensorflow/core/lib/gtl/top_n_test.cc | #ifndef TENSORFLOW_LITE_KERNELS_CTC_TOP_N_H_
#define TENSORFLOW_LITE_KERNELS_CTC_TOP_N_H_
#include <stddef.h>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#include "tensorflow/lite/kernels/internal/compatibility.h"
namespace tflite {
namespace gtl {
template <class T, class Cmp = std::greater<T> >
class TopN {
public:
enum State { UNORDERED, BOTTOM_KNOWN, HEAP_SORTED };
using UnsortedIterator = typename std::vector<T>::const_iterator;
explicit TopN(size_t limit) : TopN(limit, Cmp()) {}
TopN(size_t limit, const Cmp &cmp) : limit_(limit), cmp_(cmp) {}
size_t limit() const { return limit_; }
size_t size() const { return std::min(elements_.size(), limit_); }
bool empty() const { return size() == 0; }
void reserve(size_t n) { elements_.reserve(std::min(n, limit_ + 1)); }
void push(const T &v) { push(v, nullptr); }
void push(const T &v, T *dropped) { PushInternal(v, dropped); }
void push(T &&v) {
push(std::move(v), nullptr);
}
void push(T &&v, T *dropped) {
PushInternal(std::move(v), dropped);
}
const T &peek_bottom();
std::vector<T> *Extract();
std::vector<T> *ExtractUnsorted();
std::vector<T> *ExtractNondestructive() const;
void ExtractNondestructive(std::vector<T> *output) const;
std::vector<T> *ExtractUnsortedNondestructive() const;
void ExtractUnsortedNondestructive(std::vector<T> *output) const;
UnsortedIterator unsorted_begin() const { return elements_.begin(); }
UnsortedIterator unsorted_end() const { return elements_.begin() + size(); }
Cmp *comparator() { return &cmp_; }
void Reset();
private:
template <typename U>
void PushInternal(U &&v, T *dropped);
std::vector<T> elements_;
size_t limit_;
Cmp cmp_;
State state_ = UNORDERED;
};
template <class T, class Cmp>
template <typename U>
void TopN<T, Cmp>::PushInternal(U &&v, T *dropped) {
if (limit_ == 0) {
if (dropped) *dropped = std::forward<U>(v);
return;
}
if (state_ != HEAP_SORTED) {
elements_.push_back(std::forward<U>(v));
if (state_ == UNORDERED || cmp_(elements_.back(), elements_.front())) {
} else {
using std::swap;
swap(elements_.front(), elements_.back());
}
if (elements_.size() == limit_ + 1) {
std::make_heap(elements_.begin(), elements_.end(), cmp_);
if (dropped) *dropped = std::move(elements_.front());
std::pop_heap(elements_.begin(), elements_.end(), cmp_);
state_ = HEAP_SORTED;
}
} else {
if (cmp_(v, elements_.front())) {
elements_.back() = std::forward<U>(v);
std::push_heap(elements_.begin(), elements_.end(), cmp_);
if (dropped) *dropped = std::move(elements_.front());
std::pop_heap(elements_.begin(), elements_.end(), cmp_);
} else {
if (dropped) *dropped = std::forward<U>(v);
}
}
}
template <class T, class Cmp>
const T &TopN<T, Cmp>::peek_bottom() {
TFLITE_DCHECK(!empty());
if (state_ == UNORDERED) {
int min_candidate = 0;
for (size_t i = 1; i < elements_.size(); ++i) {
if (cmp_(elements_[min_candidate], elements_[i])) {
min_candidate = i;
}
}
if (min_candidate != 0) {
using std::swap;
swap(elements_[0], elements_[min_candidate]);
}
state_ = BOTTOM_KNOWN;
}
return elements_.front();
}
template <class T, class Cmp>
std::vector<T> *TopN<T, Cmp>::Extract() {
auto out = new std::vector<T>;
out->swap(elements_);
if (state_ != HEAP_SORTED) {
std::sort(out->begin(), out->end(), cmp_);
} else {
out->pop_back();
std::sort_heap(out->begin(), out->end(), cmp_);
}
return out;
}
template <class T, class Cmp>
std::vector<T> *TopN<T, Cmp>::ExtractUnsorted() {
auto out = new std::vector<T>;
out->swap(elements_);
if (state_ == HEAP_SORTED) {
out->pop_back();
}
return out;
}
template <class T, class Cmp>
std::vector<T> *TopN<T, Cmp>::ExtractNondestructive() const {
auto out = new std::vector<T>;
ExtractNondestructive(out);
return out;
}
template <class T, class Cmp>
void TopN<T, Cmp>::ExtractNondestructive(std::vector<T> *output) const {
TFLITE_DCHECK(output);
*output = elements_;
if (state_ != HEAP_SORTED) {
std::sort(output->begin(), output->end(), cmp_);
} else {
output->pop_back();
std::sort_heap(output->begin(), output->end(), cmp_);
}
}
template <class T, class Cmp>
std::vector<T> *TopN<T, Cmp>::ExtractUnsortedNondestructive() const {
auto elements = new std::vector<T>;
ExtractUnsortedNondestructive(elements);
return elements;
}
template <class T, class Cmp>
void TopN<T, Cmp>::ExtractUnsortedNondestructive(std::vector<T> *output) const {
TFLITE_DCHECK(output);
*output = elements_;
if (state_ == HEAP_SORTED) {
output->pop_back();
}
}
template <class T, class Cmp>
void TopN<T, Cmp>::Reset() {
elements_.clear();
state_ = UNORDERED;
}
}
}
#endif | #include "tensorflow/core/lib/gtl/top_n.h"
#include <string>
#include <vector>
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
namespace {
using tensorflow::string;
using tensorflow::gtl::TopN;
using tensorflow::random::PhiloxRandom;
using tensorflow::random::SimplePhilox;
template <class T>
T ConsumeRawPtr(T *p) {
T tmp = std::move(*p);
delete p;
return tmp;
}
template <class Cmp>
void TestIntTopNHelper(size_t limit, size_t n_elements, const Cmp &cmp,
SimplePhilox *random, bool test_peek,
bool test_extract_unsorted) {
LOG(INFO) << "Testing limit=" << limit << ", n_elements=" << n_elements
<< ", test_peek=" << test_peek
<< ", test_extract_unsorted=" << test_extract_unsorted;
TopN<int, Cmp> top(limit, cmp);
std::vector<int> shadow(n_elements);
for (int i = 0; i != n_elements; ++i) shadow[i] = random->Uniform(limit);
for (int e : shadow) top.push(e);
std::sort(shadow.begin(), shadow.end(), cmp);
size_t top_size = std::min(limit, n_elements);
EXPECT_EQ(top_size, top.size());
if (test_peek && top_size != 0) {
EXPECT_EQ(shadow[top_size - 1], top.peek_bottom());
}
std::vector<int> v;
if (test_extract_unsorted) {
v = ConsumeRawPtr(top.ExtractUnsorted());
std::sort(v.begin(), v.end(), cmp);
} else {
v = ConsumeRawPtr(top.Extract());
}
EXPECT_EQ(top_size, v.size());
for (int i = 0; i != top_size; ++i) {
VLOG(1) << "Top element " << v[i];
EXPECT_EQ(shadow[i], v[i]);
}
}
template <class Cmp>
void TestIntTopN(size_t limit, size_t n_elements, const Cmp &cmp,
SimplePhilox *random) {
TestIntTopNHelper(limit, n_elements, cmp, random, true, false);
TestIntTopNHelper(limit, n_elements, cmp, random, false, false);
TestIntTopNHelper(limit, n_elements, cmp, random, true, true);
TestIntTopNHelper(limit, n_elements, cmp, random, false, true);
}
TEST(TopNTest, Misc) {
PhiloxRandom philox(1, 1);
SimplePhilox random(&philox);
TestIntTopN(0, 5, std::greater<int>(), &random);
TestIntTopN(32, 0, std::greater<int>(), &random);
TestIntTopN(6, 6, std::greater<int>(), &random);
TestIntTopN(6, 6, std::less<int>(), &random);
TestIntTopN(1000, 999, std::greater<int>(), &random);
TestIntTopN(1000, 1000, std::greater<int>(), &random);
TestIntTopN(1000, 1001, std::greater<int>(), &random);
TestIntTopN(2300, 28393, std::less<int>(), &random);
TestIntTopN(30, 100, std::greater<int>(), &random);
TestIntTopN(100, 30, std::less<int>(), &random);
TestIntTopN(size_t(-1), 3, std::greater<int>(), &random);
TestIntTopN(size_t(-1), 0, std::greater<int>(), &random);
TestIntTopN(0, 5, std::greater<int>(), &random);
}
TEST(TopNTest, String) {
LOG(INFO) << "Testing strings";
TopN<string> top(3);
EXPECT_TRUE(top.empty());
top.push("abracadabra");
top.push("waldemar");
EXPECT_EQ(2, top.size());
EXPECT_EQ("abracadabra", top.peek_bottom());
top.push("");
EXPECT_EQ(3, top.size());
EXPECT_EQ("", top.peek_bottom());
top.push("top");
EXPECT_EQ(3, top.size());
EXPECT_EQ("abracadabra", top.peek_bottom());
top.push("Google");
top.push("test");
EXPECT_EQ(3, top.size());
EXPECT_EQ("test", top.peek_bottom());
TopN<string> top2(top);
TopN<string> top3(5);
top3 = top;
EXPECT_EQ("test", top3.peek_bottom());
{
std::vector<string> s = ConsumeRawPtr(top.Extract());
EXPECT_EQ(s[0], "waldemar");
EXPECT_EQ(s[1], "top");
EXPECT_EQ(s[2], "test");
}
top2.push("zero");
EXPECT_EQ(top2.peek_bottom(), "top");
{
std::vector<string> s = ConsumeRawPtr(top2.Extract());
EXPECT_EQ(s[0], "zero");
EXPECT_EQ(s[1], "waldemar");
EXPECT_EQ(s[2], "top");
}
{
std::vector<string> s = ConsumeRawPtr(top3.Extract());
EXPECT_EQ(s[0], "waldemar");
EXPECT_EQ(s[1], "top");
EXPECT_EQ(s[2], "test");
}
TopN<string> top4(3);
for (int i = 0; i < 2; ++i) {
top4.push("abcd");
top4.push("ijkl");
top4.push("efgh");
top4.push("mnop");
std::vector<string> s = ConsumeRawPtr(top4.Extract());
EXPECT_EQ(s[0], "mnop");
EXPECT_EQ(s[1], "ijkl");
EXPECT_EQ(s[2], "efgh");
top4.Reset();
}
}
TEST(TopNTest, Ptr) {
LOG(INFO) << "Testing 2-argument push()";
TopN<string *> topn(3);
for (int i = 0; i < 8; ++i) {
string *dropped = nullptr;
topn.push(new string(std::to_string(i)), &dropped);
delete dropped;
}
for (int i = 8; i > 0; --i) {
string *dropped = nullptr;
topn.push(new string(std::to_string(i)), &dropped);
delete dropped;
}
std::vector<string *> extract = ConsumeRawPtr(topn.Extract());
for (auto &temp : extract) {
delete temp;
}
extract.clear();
}
struct PointeeGreater {
template <typename T>
bool operator()(const T &a, const T &b) const {
return *a > *b;
}
};
TEST(TopNTest, MoveOnly) {
using StrPtr = std::unique_ptr<string>;
TopN<StrPtr, PointeeGreater> topn(3);
for (int i = 0; i < 8; ++i) topn.push(StrPtr(new string(std::to_string(i))));
for (int i = 8; i > 0; --i) topn.push(StrPtr(new string(std::to_string(i))));
std::vector<StrPtr> extract = ConsumeRawPtr(topn.Extract());
EXPECT_EQ(extract.size(), 3);
EXPECT_EQ(*(extract[0]), "8");
EXPECT_EQ(*(extract[1]), "7");
EXPECT_EQ(*(extract[2]), "7");
}
TEST(TopNTest, Nondestructive) {
LOG(INFO) << "Testing Nondestructive extracts";
TopN<int> top4(4);
for (int i = 0; i < 8; ++i) {
top4.push(i);
std::vector<int> v = ConsumeRawPtr(top4.ExtractNondestructive());
EXPECT_EQ(std::min(i + 1, 4), v.size());
for (size_t j = 0; j < v.size(); ++j) EXPECT_EQ(i - j, v[j]);
}
TopN<int> top3(3);
for (int i = 0; i < 8; ++i) {
top3.push(i);
std::vector<int> v = ConsumeRawPtr(top3.ExtractUnsortedNondestructive());
std::sort(v.begin(), v.end(), std::greater<int>());
EXPECT_EQ(std::min(i + 1, 3), v.size());
for (size_t j = 0; j < v.size(); ++j) EXPECT_EQ(i - j, v[j]);
}
}
struct ForbiddenCmp {
bool operator()(int lhs, int rhs) const {
LOG(FATAL) << "ForbiddenCmp called " << lhs << " " << rhs;
}
};
TEST(TopNTest, ZeroLimit) {
TopN<int, ForbiddenCmp> top(0);
top.push(1);
top.push(2);
int dropped = -1;
top.push(1, &dropped);
top.push(2, &dropped);
std::vector<int> v;
top.ExtractNondestructive(&v);
EXPECT_EQ(0, v.size());
}
TEST(TopNTest, Iteration) {
TopN<int> top(4);
for (int i = 0; i < 8; ++i) top.push(i);
std::vector<int> actual(top.unsorted_begin(), top.unsorted_end());
std::sort(actual.begin(), actual.end());
EXPECT_EQ(actual.size(), 4);
EXPECT_EQ(actual[0], 4);
EXPECT_EQ(actual[1], 5);
EXPECT_EQ(actual[2], 6);
EXPECT_EQ(actual[3], 7);
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/ctc/top_n.h | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/lib/gtl/top_n_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
f45d9aec-4168-4cdc-9d17-b4e43a86edd1 | cpp | google/cel-cpp | cel_value_equal | eval/internal/cel_value_equal.cc | eval/internal/cel_value_equal_test.cc | #include "eval/internal/cel_value_equal.h"
#include <cstdint>
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "base/kind.h"
#include "eval/public/cel_number.h"
#include "eval/public/cel_value.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/legacy_type_adapter.h"
#include "eval/public/structs/legacy_type_info_apis.h"
#include "internal/number.h"
#include "google/protobuf/arena.h"
namespace cel::interop_internal {
namespace {
using ::cel::internal::Number;
using ::google::api::expr::runtime::CelList;
using ::google::api::expr::runtime::CelMap;
using ::google::api::expr::runtime::CelValue;
using ::google::api::expr::runtime::GetNumberFromCelValue;
using ::google::api::expr::runtime::LegacyTypeAccessApis;
using ::google::api::expr::runtime::LegacyTypeInfoApis;
struct HeterogeneousEqualProvider {
absl::optional<bool> operator()(const CelValue& lhs,
const CelValue& rhs) const;
};
template <class Type>
absl::optional<bool> Inequal(Type lhs, Type rhs) {
return lhs != rhs;
}
template <class Type>
absl::optional<bool> Equal(Type lhs, Type rhs) {
return lhs == rhs;
}
template <typename EqualsProvider>
absl::optional<bool> ListEqual(const CelList* t1, const CelList* t2) {
if (t1 == t2) {
return true;
}
int index_size = t1->size();
if (t2->size() != index_size) {
return false;
}
google::protobuf::Arena arena;
for (int i = 0; i < index_size; i++) {
CelValue e1 = (*t1).Get(&arena, i);
CelValue e2 = (*t2).Get(&arena, i);
absl::optional<bool> eq = EqualsProvider()(e1, e2);
if (eq.has_value()) {
if (!(*eq)) {
return false;
}
} else {
return eq;
}
}
return true;
}
template <typename EqualsProvider>
absl::optional<bool> MapEqual(const CelMap* t1, const CelMap* t2) {
if (t1 == t2) {
return true;
}
if (t1->size() != t2->size()) {
return false;
}
google::protobuf::Arena arena;
auto list_keys = t1->ListKeys(&arena);
if (!list_keys.ok()) {
return absl::nullopt;
}
const CelList* keys = *list_keys;
for (int i = 0; i < keys->size(); i++) {
CelValue key = (*keys).Get(&arena, i);
CelValue v1 = (*t1).Get(&arena, key).value();
absl::optional<CelValue> v2 = (*t2).Get(&arena, key);
if (!v2.has_value()) {
auto number = GetNumberFromCelValue(key);
if (!number.has_value()) {
return false;
}
if (!key.IsInt64() && number->LosslessConvertibleToInt()) {
CelValue int_key = CelValue::CreateInt64(number->AsInt());
absl::optional<bool> eq = EqualsProvider()(key, int_key);
if (eq.has_value() && *eq) {
v2 = (*t2).Get(&arena, int_key);
}
}
if (!key.IsUint64() && !v2.has_value() &&
number->LosslessConvertibleToUint()) {
CelValue uint_key = CelValue::CreateUint64(number->AsUint());
absl::optional<bool> eq = EqualsProvider()(key, uint_key);
if (eq.has_value() && *eq) {
v2 = (*t2).Get(&arena, uint_key);
}
}
}
if (!v2.has_value()) {
return false;
}
absl::optional<bool> eq = EqualsProvider()(v1, *v2);
if (!eq.has_value() || !*eq) {
return eq;
}
}
return true;
}
bool MessageEqual(const CelValue::MessageWrapper& m1,
const CelValue::MessageWrapper& m2) {
const LegacyTypeInfoApis* lhs_type_info = m1.legacy_type_info();
const LegacyTypeInfoApis* rhs_type_info = m2.legacy_type_info();
if (lhs_type_info->GetTypename(m1) != rhs_type_info->GetTypename(m2)) {
return false;
}
const LegacyTypeAccessApis* accessor = lhs_type_info->GetAccessApis(m1);
if (accessor == nullptr) {
return false;
}
return accessor->IsEqualTo(m1, m2);
}
template <class EqualityProvider>
absl::optional<bool> HomogenousCelValueEqual(const CelValue& t1,
const CelValue& t2) {
if (t1.type() != t2.type()) {
return absl::nullopt;
}
switch (t1.type()) {
case Kind::kNullType:
return Equal<CelValue::NullType>(CelValue::NullType(),
CelValue::NullType());
case Kind::kBool:
return Equal<bool>(t1.BoolOrDie(), t2.BoolOrDie());
case Kind::kInt64:
return Equal<int64_t>(t1.Int64OrDie(), t2.Int64OrDie());
case Kind::kUint64:
return Equal<uint64_t>(t1.Uint64OrDie(), t2.Uint64OrDie());
case Kind::kDouble:
return Equal<double>(t1.DoubleOrDie(), t2.DoubleOrDie());
case Kind::kString:
return Equal<CelValue::StringHolder>(t1.StringOrDie(), t2.StringOrDie());
case Kind::kBytes:
return Equal<CelValue::BytesHolder>(t1.BytesOrDie(), t2.BytesOrDie());
case Kind::kDuration:
return Equal<absl::Duration>(t1.DurationOrDie(), t2.DurationOrDie());
case Kind::kTimestamp:
return Equal<absl::Time>(t1.TimestampOrDie(), t2.TimestampOrDie());
case Kind::kList:
return ListEqual<EqualityProvider>(t1.ListOrDie(), t2.ListOrDie());
case Kind::kMap:
return MapEqual<EqualityProvider>(t1.MapOrDie(), t2.MapOrDie());
case Kind::kCelType:
return Equal<CelValue::CelTypeHolder>(t1.CelTypeOrDie(),
t2.CelTypeOrDie());
default:
break;
}
return absl::nullopt;
}
absl::optional<bool> HeterogeneousEqualProvider::operator()(
const CelValue& lhs, const CelValue& rhs) const {
return CelValueEqualImpl(lhs, rhs);
}
}
absl::optional<bool> CelValueEqualImpl(const CelValue& v1, const CelValue& v2) {
if (v1.type() == v2.type()) {
if (CelValue::MessageWrapper lhs, rhs;
v1.GetValue(&lhs) && v2.GetValue(&rhs)) {
return MessageEqual(lhs, rhs);
}
return HomogenousCelValueEqual<HeterogeneousEqualProvider>(v1, v2);
}
absl::optional<Number> lhs = GetNumberFromCelValue(v1);
absl::optional<Number> rhs = GetNumberFromCelValue(v2);
if (rhs.has_value() && lhs.has_value()) {
return *lhs == *rhs;
}
if (v1.IsError() || v1.IsUnknownSet() || v2.IsError() || v2.IsUnknownSet()) {
return absl::nullopt;
}
return false;
}
} | #include "eval/internal/cel_value_equal.h"
#include <array>
#include <cmath>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "google/rpc/context/attribute_context.pb.h"
#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "absl/types/variant.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/message_wrapper.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/structs/trivial_legacy_type_info.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
namespace cel::interop_internal {
namespace {
using ::google::api::expr::runtime::CelList;
using ::google::api::expr::runtime::CelMap;
using ::google::api::expr::runtime::CelProtoWrapper;
using ::google::api::expr::runtime::CelValue;
using ::google::api::expr::runtime::ContainerBackedListImpl;
using ::google::api::expr::runtime::CreateContainerBackedMap;
using ::google::api::expr::runtime::MessageWrapper;
using ::google::api::expr::runtime::TestMessage;
using ::google::api::expr::runtime::TrivialTypeInfo;
using ::testing::_;
using ::testing::Combine;
using ::testing::Optional;
using ::testing::Values;
using ::testing::ValuesIn;
struct EqualityTestCase {
enum class ErrorKind { kMissingOverload, kMissingIdentifier };
absl::string_view expr;
absl::variant<bool, ErrorKind> result;
CelValue lhs = CelValue::CreateNull();
CelValue rhs = CelValue::CreateNull();
};
bool IsNumeric(CelValue::Type type) {
return type == CelValue::Type::kDouble || type == CelValue::Type::kInt64 ||
type == CelValue::Type::kUint64;
}
const CelList& CelListExample1() {
static ContainerBackedListImpl* example =
new ContainerBackedListImpl({CelValue::CreateInt64(1)});
return *example;
}
const CelList& CelListExample2() {
static ContainerBackedListImpl* example =
new ContainerBackedListImpl({CelValue::CreateInt64(2)});
return *example;
}
const CelMap& CelMapExample1() {
static CelMap* example = []() {
std::vector<std::pair<CelValue, CelValue>> values{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)}};
auto map = CreateContainerBackedMap(absl::MakeSpan(values));
return map->release();
}();
return *example;
}
const CelMap& CelMapExample2() {
static CelMap* example = []() {
std::vector<std::pair<CelValue, CelValue>> values{
{CelValue::CreateInt64(2), CelValue::CreateInt64(4)}};
auto map = CreateContainerBackedMap(absl::MakeSpan(values));
return map->release();
}();
return *example;
}
const std::vector<CelValue>& ValueExamples1() {
static std::vector<CelValue>* examples = []() {
google::protobuf::Arena arena;
auto result = std::make_unique<std::vector<CelValue>>();
result->push_back(CelValue::CreateNull());
result->push_back(CelValue::CreateBool(false));
result->push_back(CelValue::CreateInt64(1));
result->push_back(CelValue::CreateUint64(1));
result->push_back(CelValue::CreateDouble(1.0));
result->push_back(CelValue::CreateStringView("string"));
result->push_back(CelValue::CreateBytesView("bytes"));
result->push_back(CelProtoWrapper::CreateMessage(
std::make_unique<TestMessage>().release(), &arena));
result->push_back(CelValue::CreateDuration(absl::Seconds(1)));
result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(1)));
result->push_back(CelValue::CreateList(&CelListExample1()));
result->push_back(CelValue::CreateMap(&CelMapExample1()));
result->push_back(CelValue::CreateCelTypeView("type"));
return result.release();
}();
return *examples;
}
const std::vector<CelValue>& ValueExamples2() {
static std::vector<CelValue>* examples = []() {
google::protobuf::Arena arena;
auto result = std::make_unique<std::vector<CelValue>>();
auto message2 = std::make_unique<TestMessage>();
message2->set_int64_value(2);
result->push_back(CelValue::CreateNull());
result->push_back(CelValue::CreateBool(true));
result->push_back(CelValue::CreateInt64(2));
result->push_back(CelValue::CreateUint64(2));
result->push_back(CelValue::CreateDouble(2.0));
result->push_back(CelValue::CreateStringView("string2"));
result->push_back(CelValue::CreateBytesView("bytes2"));
result->push_back(
CelProtoWrapper::CreateMessage(message2.release(), &arena));
result->push_back(CelValue::CreateDuration(absl::Seconds(2)));
result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(2)));
result->push_back(CelValue::CreateList(&CelListExample2()));
result->push_back(CelValue::CreateMap(&CelMapExample2()));
result->push_back(CelValue::CreateCelTypeView("type2"));
return result.release();
}();
return *examples;
}
class CelValueEqualImplTypesTest
: public testing::TestWithParam<std::tuple<CelValue, CelValue, bool>> {
public:
CelValueEqualImplTypesTest() = default;
const CelValue& lhs() { return std::get<0>(GetParam()); }
const CelValue& rhs() { return std::get<1>(GetParam()); }
bool should_be_equal() { return std::get<2>(GetParam()); }
};
std::string CelValueEqualTestName(
const testing::TestParamInfo<std::tuple<CelValue, CelValue, bool>>&
test_case) {
return absl::StrCat(CelValue::TypeName(std::get<0>(test_case.param).type()),
CelValue::TypeName(std::get<1>(test_case.param).type()),
(std::get<2>(test_case.param)) ? "Equal" : "Inequal");
}
TEST_P(CelValueEqualImplTypesTest, Basic) {
absl::optional<bool> result = CelValueEqualImpl(lhs(), rhs());
if (lhs().IsNull() || rhs().IsNull()) {
if (lhs().IsNull() && rhs().IsNull()) {
EXPECT_THAT(result, Optional(true));
} else {
EXPECT_THAT(result, Optional(false));
}
} else if (lhs().type() == rhs().type() ||
(IsNumeric(lhs().type()) && IsNumeric(rhs().type()))) {
EXPECT_THAT(result, Optional(should_be_equal()));
} else {
EXPECT_THAT(result, Optional(false));
}
}
INSTANTIATE_TEST_SUITE_P(EqualityBetweenTypes, CelValueEqualImplTypesTest,
Combine(ValuesIn(ValueExamples1()),
ValuesIn(ValueExamples1()), Values(true)),
&CelValueEqualTestName);
INSTANTIATE_TEST_SUITE_P(InequalityBetweenTypes, CelValueEqualImplTypesTest,
Combine(ValuesIn(ValueExamples1()),
ValuesIn(ValueExamples2()), Values(false)),
&CelValueEqualTestName);
struct NumericInequalityTestCase {
std::string name;
CelValue a;
CelValue b;
};
const std::vector<NumericInequalityTestCase>& NumericValuesNotEqualExample() {
static std::vector<NumericInequalityTestCase>* examples = []() {
google::protobuf::Arena arena;
auto result = std::make_unique<std::vector<NumericInequalityTestCase>>();
result->push_back({"NegativeIntAndUint", CelValue::CreateInt64(-1),
CelValue::CreateUint64(2)});
result->push_back(
{"IntAndLargeUint", CelValue::CreateInt64(1),
CelValue::CreateUint64(
static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) + 1)});
result->push_back(
{"IntAndLargeDouble", CelValue::CreateInt64(2),
CelValue::CreateDouble(
static_cast<double>(std::numeric_limits<int64_t>::max()) + 1025)});
result->push_back(
{"IntAndSmallDouble", CelValue::CreateInt64(2),
CelValue::CreateDouble(
static_cast<double>(std::numeric_limits<int64_t>::lowest()) -
1025)});
result->push_back(
{"UintAndLargeDouble", CelValue::CreateUint64(2),
CelValue::CreateDouble(
static_cast<double>(std::numeric_limits<uint64_t>::max()) +
2049)});
result->push_back({"NegativeDoubleAndUint", CelValue::CreateDouble(-2.0),
CelValue::CreateUint64(123)});
result->push_back({"NanAndDouble", CelValue::CreateDouble(NAN),
CelValue::CreateDouble(1.0)});
result->push_back({"NanAndNan", CelValue::CreateDouble(NAN),
CelValue::CreateDouble(NAN)});
result->push_back({"DoubleAndNan", CelValue::CreateDouble(1.0),
CelValue::CreateDouble(NAN)});
result->push_back(
{"IntAndNan", CelValue::CreateInt64(1), CelValue::CreateDouble(NAN)});
result->push_back(
{"NanAndInt", CelValue::CreateDouble(NAN), CelValue::CreateInt64(1)});
result->push_back(
{"UintAndNan", CelValue::CreateUint64(1), CelValue::CreateDouble(NAN)});
result->push_back(
{"NanAndUint", CelValue::CreateDouble(NAN), CelValue::CreateUint64(1)});
return result.release();
}();
return *examples;
}
using NumericInequalityTest = testing::TestWithParam<NumericInequalityTestCase>;
TEST_P(NumericInequalityTest, NumericValues) {
NumericInequalityTestCase test_case = GetParam();
absl::optional<bool> result = CelValueEqualImpl(test_case.a, test_case.b);
EXPECT_TRUE(result.has_value());
EXPECT_EQ(*result, false);
}
INSTANTIATE_TEST_SUITE_P(
InequalityBetweenNumericTypesTest, NumericInequalityTest,
ValuesIn(NumericValuesNotEqualExample()),
[](const testing::TestParamInfo<NumericInequalityTest::ParamType>& info) {
return info.param.name;
});
TEST(CelValueEqualImplTest, LossyNumericEquality) {
absl::optional<bool> result = CelValueEqualImpl(
CelValue::CreateDouble(
static_cast<double>(std::numeric_limits<int64_t>::max()) - 1),
CelValue::CreateInt64(std::numeric_limits<int64_t>::max()));
EXPECT_TRUE(result.has_value());
EXPECT_TRUE(*result);
}
TEST(CelValueEqualImplTest, ListMixedTypesInequal) {
ContainerBackedListImpl lhs({CelValue::CreateInt64(1)});
ContainerBackedListImpl rhs({CelValue::CreateStringView("abc")});
EXPECT_THAT(
CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)),
Optional(false));
}
TEST(CelValueEqualImplTest, NestedList) {
ContainerBackedListImpl inner_lhs({CelValue::CreateInt64(1)});
ContainerBackedListImpl lhs({CelValue::CreateList(&inner_lhs)});
ContainerBackedListImpl inner_rhs({CelValue::CreateNull()});
ContainerBackedListImpl rhs({CelValue::CreateList(&inner_rhs)});
EXPECT_THAT(
CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)),
Optional(false));
}
TEST(CelValueEqualImplTest, MapMixedValueTypesInequal) {
std::vector<std::pair<CelValue, CelValue>> lhs_data{
{CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}};
std::vector<std::pair<CelValue, CelValue>> rhs_data{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)}};
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs,
CreateContainerBackedMap(absl::MakeSpan(lhs_data)));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs,
CreateContainerBackedMap(absl::MakeSpan(rhs_data)));
EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()),
CelValue::CreateMap(rhs.get())),
Optional(false));
}
TEST(CelValueEqualImplTest, MapMixedKeyTypesEqual) {
std::vector<std::pair<CelValue, CelValue>> lhs_data{
{CelValue::CreateUint64(1), CelValue::CreateStringView("abc")}};
std::vector<std::pair<CelValue, CelValue>> rhs_data{
{CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}};
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs,
CreateContainerBackedMap(absl::MakeSpan(lhs_data)));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs,
CreateContainerBackedMap(absl::MakeSpan(rhs_data)));
EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()),
CelValue::CreateMap(rhs.get())),
Optional(true));
}
TEST(CelValueEqualImplTest, MapMixedKeyTypesInequal) {
std::vector<std::pair<CelValue, CelValue>> lhs_data{
{CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}};
std::vector<std::pair<CelValue, CelValue>> rhs_data{
{CelValue::CreateInt64(2), CelValue::CreateInt64(2)}};
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs,
CreateContainerBackedMap(absl::MakeSpan(lhs_data)));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs,
CreateContainerBackedMap(absl::MakeSpan(rhs_data)));
EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()),
CelValue::CreateMap(rhs.get())),
Optional(false));
}
TEST(CelValueEqualImplTest, NestedMaps) {
std::vector<std::pair<CelValue, CelValue>> inner_lhs_data{
{CelValue::CreateInt64(2), CelValue::CreateStringView("abc")}};
ASSERT_OK_AND_ASSIGN(
std::unique_ptr<CelMap> inner_lhs,
CreateContainerBackedMap(absl::MakeSpan(inner_lhs_data)));
std::vector<std::pair<CelValue, CelValue>> lhs_data{
{CelValue::CreateInt64(1), CelValue::CreateMap(inner_lhs.get())}};
std::vector<std::pair<CelValue, CelValue>> inner_rhs_data{
{CelValue::CreateInt64(2), CelValue::CreateNull()}};
ASSERT_OK_AND_ASSIGN(
std::unique_ptr<CelMap> inner_rhs,
CreateContainerBackedMap(absl::MakeSpan(inner_rhs_data)));
std::vector<std::pair<CelValue, CelValue>> rhs_data{
{CelValue::CreateInt64(1), CelValue::CreateMap(inner_rhs.get())}};
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs,
CreateContainerBackedMap(absl::MakeSpan(lhs_data)));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs,
CreateContainerBackedMap(absl::MakeSpan(rhs_data)));
EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()),
CelValue::CreateMap(rhs.get())),
Optional(false));
}
TEST(CelValueEqualImplTest, ProtoEqualityDifferingTypenameInequal) {
google::protobuf::Arena arena;
TestMessage example;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
int32_value: 1
uint32_value: 2
string_value: "test"
)",
&example));
CelValue lhs = CelProtoWrapper::CreateMessage(&example, &arena);
CelValue rhs = CelValue::CreateMessageWrapper(
MessageWrapper(&example, TrivialTypeInfo::GetInstance()));
EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false));
}
TEST(CelValueEqualImplTest, ProtoEqualityNoAccessorInequal) {
google::protobuf::Arena arena;
TestMessage example;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
int32_value: 1
uint32_value: 2
string_value: "test"
)",
&example));
CelValue lhs = CelValue::CreateMessageWrapper(
MessageWrapper(&example, TrivialTypeInfo::GetInstance()));
CelValue rhs = CelValue::CreateMessageWrapper(
MessageWrapper(&example, TrivialTypeInfo::GetInstance()));
EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false));
}
TEST(CelValueEqualImplTest, ProtoEqualityAny) {
google::protobuf::Arena arena;
TestMessage packed_value;
ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"(
int32_value: 1
uint32_value: 2
string_value: "test"
)",
&packed_value));
TestMessage lhs;
lhs.mutable_any_value()->PackFrom(packed_value);
TestMessage rhs;
rhs.mutable_any_value()->PackFrom(packed_value);
EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena),
CelProtoWrapper::CreateMessage(&rhs, &arena)),
Optional(true));
lhs.mutable_any_value()->clear_type_url();
rhs.mutable_any_value()->clear_type_url();
EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena),
CelProtoWrapper::CreateMessage(&rhs, &arena)),
Optional(true));
}
bool AddDepsToPool(const google::protobuf::FileDescriptor* descriptor,
google::protobuf::DescriptorPool& pool) {
for (int i = 0; i < descriptor->dependency_count(); i++) {
if (!AddDepsToPool(descriptor->dependency(i), pool)) {
return false;
}
}
google::protobuf::FileDescriptorProto descriptor_proto;
descriptor->CopyTo(&descriptor_proto);
return pool.BuildFile(descriptor_proto) != nullptr;
}
TEST(CelValueEqualImplTest, DynamicDescriptorAndGeneratedInequal) {
google::protobuf::DescriptorPool pool;
google::protobuf::DynamicMessageFactory factory;
google::protobuf::Arena arena;
factory.SetDelegateToGeneratedFactory(false);
ASSERT_TRUE(AddDepsToPool(TestMessage::descriptor()->file(), pool));
TestMessage example_message;
ASSERT_TRUE(
google::protobuf::TextFormat::ParseFromString(R"pb(
int64_value: 12345
bool_list: false
bool_list: true
message_value { float_value: 1.0 }
)pb",
&example_message));
std::unique_ptr<google::protobuf::Message> example_dynamic_message(
factory
.GetPrototype(pool.FindMessageTypeByName(
TestMessage::descriptor()->full_name()))
->New());
ASSERT_TRUE(example_dynamic_message->ParseFromString(
example_message.SerializeAsString()));
EXPECT_THAT(CelValueEqualImpl(
CelProtoWrapper::CreateMessage(&example_message, &arena),
CelProtoWrapper::CreateMessage(example_dynamic_message.get(),
&arena)),
Optional(false));
}
TEST(CelValueEqualImplTest, DynamicMessageAndMessageEqual) {
google::protobuf::DynamicMessageFactory factory;
google::protobuf::Arena arena;
factory.SetDelegateToGeneratedFactory(false);
TestMessage example_message;
ASSERT_TRUE(
google::protobuf::TextFormat::ParseFromString(R"pb(
int64_value: 12345
bool_list: false
bool_list: true
message_value { float_value: 1.0 }
)pb",
&example_message));
std::unique_ptr<google::protobuf::Message> example_dynamic_message(
factory.GetPrototype(TestMessage::descriptor())->New());
ASSERT_TRUE(example_dynamic_message->ParseFromString(
example_message.SerializeAsString()));
EXPECT_THAT(CelValueEqualImpl(
CelProtoWrapper::CreateMessage(&example_message, &arena),
CelProtoWrapper::CreateMessage(example_dynamic_message.get(),
&arena)),
Optional(true));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/internal/cel_value_equal.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/internal/cel_value_equal_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
34bddcca-fda3-446f-8e5e-0bd32648a7c4 | cpp | tensorflow/tensorflow | math_grad | tensorflow/c/experimental/gradients/math_grad.cc | tensorflow/c/experimental/gradients/math_grad_test.cc | #include "tensorflow/c/experimental/gradients/math_grad.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/gradients.h"
#include "tensorflow/c/experimental/ops/array_ops.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/experimental/ops/nn_ops.h"
using std::vector;
using tensorflow::ops::AddV2;
using tensorflow::ops::Div;
using tensorflow::ops::DivNoNan;
using tensorflow::ops::MatMul;
using tensorflow::ops::Mul;
using tensorflow::ops::Neg;
using tensorflow::ops::OnesLike;
using tensorflow::ops::SqrtGrad;
namespace tensorflow {
namespace gradients {
namespace {
static Status SafeConj(AbstractContext* ctx, AbstractTensorHandle* const input,
AbstractTensorHandle** output, const char* name) {
auto dtype = input->DataType();
if (DataTypeIsFloating(BaseType(dtype)) ||
DataTypeIsInteger(BaseType(dtype))) {
return tensorflow::ops::Identity(ctx, input, output, name);
} else if (!DataTypeIsComplex(BaseType(dtype)) &&
BaseType(dtype) != DT_VARIANT) {
return errors::InvalidArgument(
"Expected numeric or variant tensor, got dtype ", dtype);
}
return tensorflow::ops::Conj(ctx, input, output, name);
}
class AddGradientFunction : public GradientFunction {
public:
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
DCHECK(grad_outputs[0]);
grad_inputs[0] = grad_outputs[0];
grad_inputs[1] = grad_outputs[0];
grad_inputs[0]->Ref();
grad_inputs[1]->Ref();
return absl::OkStatus();
}
~AddGradientFunction() override {}
};
class ExpGradientFunction : public GradientFunction {
public:
explicit ExpGradientFunction(AbstractTensorHandle* exp) : exp_(exp) {
exp->Ref();
}
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
AbstractTensorHandle* conj_output;
std::string name = "Conj_Exp_Grad";
TF_RETURN_IF_ERROR(SafeConj(ctx, exp_.get(), &conj_output, name.c_str()));
AbstractTensorHandlePtr conj_output_releaser(conj_output);
name = "Mul_Exp_Grad";
TF_RETURN_IF_ERROR(
Mul(ctx, conj_output, grad_outputs[0], &grad_inputs[0], name.c_str()));
return absl::OkStatus();
}
~ExpGradientFunction() override {}
private:
AbstractTensorHandlePtr exp_;
};
class SqrtGradientFunction : public GradientFunction {
public:
explicit SqrtGradientFunction(AbstractTensorHandle* sqrt) : sqrt_(sqrt) {
sqrt->Ref();
}
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
std::string name = "Sqrt_Grad";
TF_RETURN_IF_ERROR(SqrtGrad(ctx, sqrt_.get(), grad_outputs[0],
&grad_inputs[0], name.c_str()));
return absl::OkStatus();
}
~SqrtGradientFunction() override {}
private:
AbstractTensorHandlePtr sqrt_;
};
class MatMulGradientFunction : public GradientFunction {
public:
explicit MatMulGradientFunction(vector<AbstractTensorHandle*> f_inputs,
AttrBuilder f_attrs)
: forward_inputs_(f_inputs), forward_attrs_(f_attrs) {
for (auto input : forward_inputs_) {
if (input) {
input->Ref();
}
}
}
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
AbstractTensorHandle* upstream_grad = grad_outputs[0];
bool t_a;
TF_RETURN_IF_ERROR(forward_attrs_.Get("transpose_a", &t_a));
bool t_b;
TF_RETURN_IF_ERROR(forward_attrs_.Get("transpose_b", &t_b));
AbstractTensorHandle* conj_output;
std::string name = "Conj_A_MatMul_Grad";
TF_RETURN_IF_ERROR(
SafeConj(ctx, forward_inputs_[0], &conj_output, name.c_str()));
AbstractTensorHandlePtr A(conj_output);
name = "Conj_B_MatMul_Grad";
TF_RETURN_IF_ERROR(
SafeConj(ctx, forward_inputs_[1], &conj_output, name.c_str()));
AbstractTensorHandlePtr B(conj_output);
AbstractTensorHandle* matmul_A_output;
AbstractTensorHandle* matmul_B_output;
std::string name_grad_A = "MatMul_Grad_A";
std::string name_grad_B = "MatMul_Grad_B";
if (!t_a && !t_b) {
TF_RETURN_IF_ERROR(MatMul(ctx, upstream_grad, B.get(), &matmul_A_output,
false,
true, name_grad_A.c_str()));
TF_RETURN_IF_ERROR(MatMul(ctx, A.get(), upstream_grad, &matmul_B_output,
true,
false, name_grad_B.c_str()));
} else if (!t_a && t_b) {
TF_RETURN_IF_ERROR(MatMul(ctx, upstream_grad, B.get(), &matmul_A_output,
false,
false, name_grad_A.c_str()));
TF_RETURN_IF_ERROR(MatMul(ctx, upstream_grad, A.get(), &matmul_B_output,
true,
false, name_grad_B.c_str()));
} else if (t_a && !t_b) {
TF_RETURN_IF_ERROR(MatMul(ctx, B.get(), upstream_grad, &matmul_A_output,
false,
true, name_grad_A.c_str()));
TF_RETURN_IF_ERROR(MatMul(ctx, A.get(), upstream_grad, &matmul_B_output,
false,
false, name_grad_B.c_str()));
} else {
TF_RETURN_IF_ERROR(MatMul(ctx, B.get(), upstream_grad, &matmul_A_output,
true,
true, name_grad_A.c_str()));
TF_RETURN_IF_ERROR(MatMul(ctx, upstream_grad, A.get(), &matmul_B_output,
true,
true, name_grad_B.c_str()));
}
grad_inputs[0] = matmul_A_output;
grad_inputs[1] = matmul_B_output;
return absl::OkStatus();
}
~MatMulGradientFunction() override {
for (auto input : forward_inputs_) {
if (input) {
input->Unref();
}
}
}
private:
vector<AbstractTensorHandle*> forward_inputs_;
AttrBuilder forward_attrs_;
};
class NegGradientFunction : public GradientFunction {
public:
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
std::string name = "Neg_Grad";
TF_RETURN_IF_ERROR(
ops::Neg(ctx, grad_outputs[0], &grad_inputs[0], name.c_str()));
return absl::OkStatus();
}
~NegGradientFunction() override {}
};
class SubGradientFunction : public GradientFunction {
public:
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
DCHECK(grad_outputs[0]);
grad_inputs[0] = grad_outputs[0];
grad_inputs[0]->Ref();
std::string name = "Neg_Sub_Grad_B";
TF_RETURN_IF_ERROR(
ops::Neg(ctx, grad_outputs[0], &grad_inputs[1], name.c_str()));
return absl::OkStatus();
}
~SubGradientFunction() override {}
};
class MulGradientFunction : public GradientFunction {
public:
explicit MulGradientFunction(vector<AbstractTensorHandle*> f_inputs)
: forward_inputs_(f_inputs) {
for (auto input : forward_inputs_) {
if (input) {
input->Ref();
}
}
}
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
AbstractTensorHandle* upstream_grad = grad_outputs[0];
std::string name = "Mul_Grad_A";
TF_RETURN_IF_ERROR(Mul(ctx, upstream_grad, forward_inputs_[1],
&grad_inputs[0], name.c_str()));
name = "Mul_Grad_B";
TF_RETURN_IF_ERROR(Mul(ctx, forward_inputs_[0], upstream_grad,
&grad_inputs[1], name.c_str()));
return absl::OkStatus();
}
~MulGradientFunction() override {
for (auto input : forward_inputs_) {
if (input) {
input->Unref();
}
}
}
private:
vector<AbstractTensorHandle*> forward_inputs_;
};
class Log1pGradientFunction : public GradientFunction {
public:
explicit Log1pGradientFunction(vector<AbstractTensorHandle*> f_inputs)
: forward_inputs_(f_inputs) {
for (auto input : forward_inputs_) {
if (input) {
input->Ref();
}
}
}
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
AbstractTensorHandle* upstream_grad = grad_outputs[0];
AbstractTensorHandle* X = forward_inputs_[0];
AbstractTensorHandle* temp_output;
std::string name = "Conj_Log1p_Grad_X";
TF_RETURN_IF_ERROR(SafeConj(ctx, X, &temp_output, name.c_str()));
AbstractTensorHandlePtr Conj_X(temp_output);
name = "OnesLike_Log1p_Grad_X";
TF_RETURN_IF_ERROR(OnesLike(ctx, Conj_X.get(), &temp_output, name.c_str()));
AbstractTensorHandlePtr Ones_X(temp_output);
name = "Add_Log1p_Grad_X";
TF_RETURN_IF_ERROR(
AddV2(ctx, Ones_X.get(), Conj_X.get(), &temp_output, name.c_str()));
AbstractTensorHandlePtr Conj_XP1(temp_output);
name = "Div_Log1p_Grad_X";
TF_RETURN_IF_ERROR(
Div(ctx, upstream_grad, Conj_XP1.get(), &grad_inputs[0], name.c_str()));
return absl::OkStatus();
}
~Log1pGradientFunction() override {
for (auto input : forward_inputs_) {
if (input) {
input->Unref();
}
}
}
private:
vector<AbstractTensorHandle*> forward_inputs_;
};
class DivNoNanGradientFunction : public GradientFunction {
public:
explicit DivNoNanGradientFunction(vector<AbstractTensorHandle*> f_inputs,
vector<AbstractTensorHandle*> f_outputs)
: forward_inputs_(f_inputs), forward_outputs_(f_outputs) {
for (auto input : forward_inputs_) {
if (input) {
input->Ref();
}
}
for (auto output : forward_outputs_) {
if (output) {
output->Ref();
}
}
}
Status Compute(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> grad_outputs,
absl::Span<AbstractTensorHandle*> grad_inputs) override {
AbstractTensorHandle* upstream_grad = grad_outputs[0];
AbstractTensorHandle* Y = forward_inputs_[1];
AbstractTensorHandle* Z = forward_outputs_[0];
std::string name = "Div_Grad_X";
TF_RETURN_IF_ERROR(
DivNoNan(ctx, upstream_grad, Y, &grad_inputs[0], name.c_str()));
AbstractTensorHandle* temp_output;
name = "Neg_Div_Grad_Y";
TF_RETURN_IF_ERROR(Neg(ctx, upstream_grad, &temp_output,
name.c_str()));
AbstractTensorHandlePtr MinusU(temp_output);
name = "Mul_Div_Grad_Y";
TF_RETURN_IF_ERROR(Mul(ctx, MinusU.get(), Z, &temp_output,
name.c_str()));
AbstractTensorHandlePtr UZ(temp_output);
name = "Div_Grad_Y";
TF_RETURN_IF_ERROR(DivNoNan(ctx, UZ.get(), Y, &grad_inputs[1],
name.c_str()));
return absl::OkStatus();
}
~DivNoNanGradientFunction() override {
for (auto input : forward_inputs_) {
if (input) {
input->Unref();
}
}
for (auto output : forward_outputs_) {
if (output) {
output->Unref();
}
}
}
private:
vector<AbstractTensorHandle*> forward_inputs_;
vector<AbstractTensorHandle*> forward_outputs_;
};
}
GradientFunction* AddRegisterer(const ForwardOperation& op) {
return new AddGradientFunction;
}
GradientFunction* ExpRegisterer(const ForwardOperation& op) {
return new ExpGradientFunction(op.outputs[0]);
}
GradientFunction* MatMulRegisterer(const ForwardOperation& op) {
return new MatMulGradientFunction(op.inputs, op.attrs);
}
GradientFunction* SqrtRegisterer(const ForwardOperation& op) {
return new SqrtGradientFunction(op.outputs[0]);
}
GradientFunction* NegRegisterer(const ForwardOperation& op) {
return new NegGradientFunction;
}
GradientFunction* SubRegisterer(const ForwardOperation& op) {
return new SubGradientFunction;
}
GradientFunction* MulRegisterer(const ForwardOperation& op) {
return new MulGradientFunction(op.inputs);
}
GradientFunction* Log1pRegisterer(const ForwardOperation& op) {
return new Log1pGradientFunction(op.inputs);
}
GradientFunction* DivNoNanRegisterer(const ForwardOperation& op) {
return new DivNoNanGradientFunction(op.inputs, op.outputs);
}
}
} | #include "tensorflow/c/experimental/gradients/math_grad.h"
#include "tensorflow/c/eager/c_api_test_util.h"
#include "tensorflow/c/eager/c_api_unified_experimental_internal.h"
#include "tensorflow/c/eager/unified_api_testutil.h"
#include "tensorflow/c/experimental/gradients/grad_test_helper.h"
#include "tensorflow/c/experimental/gradients/tape/tape_context.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/core/platform/tensor_float_32_utils.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace gradients {
namespace internal {
namespace {
using tensorflow::TF_StatusPtr;
Status AddModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::AddV2(ctx, inputs[0], inputs[1], &outputs[0], "Add");
}
Status ExpModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Exp(ctx, inputs[0], &outputs[0], "Exp");
}
Status SqrtModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Sqrt(ctx, inputs[0], &outputs[0], "Sqrt");
}
Status NegModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Neg(ctx, inputs[0], &outputs[0], "Neg");
}
Status SubModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Sub(ctx, inputs[0], inputs[1], &outputs[0], "Sub");
}
Status MulModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Mul(ctx, inputs[0], inputs[1], &outputs[0], "Mul");
}
Status Log1pModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Log1p(ctx, inputs[0], &outputs[0], "Log1p");
}
Status DivNoNanModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::DivNoNan(ctx, inputs[0], inputs[1], &outputs[0], "DivNoNan");
}
class CppGradients
: public ::testing::TestWithParam<std::tuple<const char*, bool, bool>> {
protected:
void SetUp() override {
TF_StatusPtr status(TF_NewStatus());
TF_SetTracingImplementation(std::get<0>(GetParam()), status.get());
status_ = StatusFromTF_Status(status.get());
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
{
AbstractContext* ctx_raw = nullptr;
status_ =
BuildImmediateExecutionContext(std::get<1>(GetParam()), &ctx_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
immediate_execution_ctx_.reset(ctx_raw);
}
enable_tensor_float_32_execution(false);
}
AbstractContextPtr immediate_execution_ctx_;
GradientRegistry registry_;
Status status_;
public:
bool UseMlir() const { return strcmp(std::get<0>(GetParam()), "mlir") == 0; }
bool UseFunction() const { return std::get<2>(GetParam()); }
};
TEST_P(CppGradients, TestAddGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
AbstractTensorHandlePtr y;
{
AbstractTensorHandle* y_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &y_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
y.reset(y_raw);
}
status_ = registry_.Register("AddV2", AddRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
AddModel, BuildGradModel(AddModel, registry_),
immediate_execution_ctx_.get(), {x.get(), y.get()}, UseFunction()));
}
TEST_P(CppGradients, TestExpGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
status_ = registry_.Register("Exp", ExpRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
ExpModel, BuildGradModel(ExpModel, registry_),
immediate_execution_ctx_.get(), {x.get()}, UseFunction()));
}
TEST_P(CppGradients, TestMatMulGrad) {
GTEST_SKIP();
float A_vals[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f};
int64_t A_dims[] = {3, 3};
AbstractTensorHandlePtr A;
{
AbstractTensorHandle* A_raw;
status_ = TestTensorHandleWithDims<float, TF_FLOAT>(
immediate_execution_ctx_.get(), A_vals, A_dims, 2, &A_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
A.reset(A_raw);
}
float B_vals[] = {9.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f};
int64_t B_dims[] = {3, 3};
AbstractTensorHandlePtr B;
{
AbstractTensorHandle* B_raw;
status_ = TestTensorHandleWithDims<float, TF_FLOAT>(
immediate_execution_ctx_.get(), B_vals, B_dims, 2, &B_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
B.reset(B_raw);
}
status_ = registry_.Register("MatMul", MatMulRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
for (bool transpose_a : {false, true}) {
for (bool transpose_b : {false, true}) {
Model MatMulModel =
[transpose_a, transpose_b](
AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) -> Status {
return ops::MatMul(ctx, inputs[0], inputs[1], &outputs[0], transpose_a,
transpose_b, "MatMul");
};
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
MatMulModel, BuildGradModel(MatMulModel, registry_),
immediate_execution_ctx_.get(), {A.get(), B.get()}, UseFunction()));
}
}
}
TEST_P(CppGradients, TestMatMulGradManual) {
float A_vals[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f};
int64_t A_dims[] = {3, 3};
AbstractTensorHandlePtr A;
{
AbstractTensorHandle* A_raw;
status_ = TestTensorHandleWithDims<float, TF_FLOAT>(
immediate_execution_ctx_.get(), A_vals, A_dims, 2, &A_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
A.reset(A_raw);
}
float B_vals[] = {9.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f};
int64_t B_dims[] = {3, 3};
AbstractTensorHandlePtr B;
{
AbstractTensorHandle* B_raw;
status_ = TestTensorHandleWithDims<float, TF_FLOAT>(
immediate_execution_ctx_.get(), B_vals, B_dims, 2, &B_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
B.reset(B_raw);
}
status_ = registry_.Register("MatMul", MatMulRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
bool transpose_a_vals[] = {false, false, true, true};
bool transpose_b_vals[] = {false, true, false, true};
float dA_vals[4][9] = {{24, 15, 6, 24, 15, 6, 24, 15, 6},
{18, 15, 12, 18, 15, 12, 18, 15, 12},
{24, 24, 24, 15, 15, 15, 6, 6, 6},
{18, 18, 18, 15, 15, 15, 12, 12, 12}};
float dB_vals[4][9] = {{12, 12, 12, 15, 15, 15, 18, 18, 18},
{12, 15, 18, 12, 15, 18, 12, 15, 18},
{6, 6, 6, 15, 15, 15, 24, 24, 24},
{6, 15, 24, 6, 15, 24, 6, 15, 24}};
for (int i{}; i < 4; ++i) {
bool transpose_a = transpose_a_vals[i];
bool transpose_b = transpose_b_vals[i];
Model MatMulModel =
[transpose_a, transpose_b](
AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) -> Status {
return ops::MatMul(ctx, inputs[0], inputs[1], &outputs[0], transpose_a,
transpose_b, "MatMul");
};
Model MatMulGradModel = BuildGradModel(MatMulModel, registry_);
std::vector<AbstractTensorHandle*> outputs(2);
status_ =
RunModel(MatMulGradModel, immediate_execution_ctx_.get(),
{A.get(), B.get()}, absl::MakeSpan(outputs), UseFunction());
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CheckTensorValue(outputs[0], dA_vals[i],
{3, 3},
0));
ASSERT_NO_FATAL_FAILURE(CheckTensorValue(outputs[1], dB_vals[i],
{3, 3},
0));
outputs[0]->Unref();
outputs[1]->Unref();
}
}
TEST_P(CppGradients, TestSqrtGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
status_ = registry_.Register("Sqrt", SqrtRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
SqrtModel, BuildGradModel(SqrtModel, registry_),
immediate_execution_ctx_.get(), {x.get()}, UseFunction()));
}
TEST_P(CppGradients, TestNegGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
status_ = registry_.Register("Neg", NegRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
NegModel, BuildGradModel(NegModel, registry_),
immediate_execution_ctx_.get(), {x.get()}, UseFunction()));
}
TEST_P(CppGradients, TestSubGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
AbstractTensorHandlePtr y;
{
AbstractTensorHandle* y_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &y_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
y.reset(y_raw);
}
status_ = registry_.Register("Sub", SubRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
SubModel, BuildGradModel(SubModel, registry_),
immediate_execution_ctx_.get(), {x.get(), y.get()}, UseFunction()));
}
TEST_P(CppGradients, TestMulGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
AbstractTensorHandlePtr y;
{
AbstractTensorHandle* y_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &y_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
y.reset(y_raw);
}
status_ = registry_.Register("Mul", MulRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
MulModel, BuildGradModel(MulModel, registry_),
immediate_execution_ctx_.get(), {x.get(), y.get()}, UseFunction()));
}
TEST_P(CppGradients, TestLog1pGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
status_ = registry_.Register("Log1p", Log1pRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
Log1pModel, BuildGradModel(Log1pModel, registry_),
immediate_execution_ctx_.get(), {x.get()}, UseFunction()));
}
TEST_P(CppGradients, TestDivNoNanGrad) {
status_ = registry_.Register("DivNoNan", DivNoNanRegisterer);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
auto DivNoNanGradModel = BuildGradModel(DivNoNanModel, registry_);
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
x.reset(x_raw);
}
AbstractTensorHandlePtr y;
{
AbstractTensorHandle* y_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 2.0f, &y_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
y.reset(y_raw);
}
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
DivNoNanModel, DivNoNanGradModel, immediate_execution_ctx_.get(),
{x.get(), y.get()}, UseFunction()));
AbstractTensorHandlePtr z;
{
AbstractTensorHandle* z_raw = nullptr;
status_ = TestScalarTensorHandle<float, TF_FLOAT>(
immediate_execution_ctx_.get(), 0.0f, &z_raw);
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
z.reset(z_raw);
}
std::vector<AbstractTensorHandle*> outputs(2);
status_ =
RunModel(DivNoNanGradModel, immediate_execution_ctx_.get(),
{x.get(), z.get()}, absl::MakeSpan(outputs), UseFunction());
ASSERT_EQ(errors::OK, status_.code()) << status_.message();
ASSERT_NO_FATAL_FAILURE(CheckTensorValue(outputs[0], {0.0f}, {},
0));
ASSERT_NO_FATAL_FAILURE(CheckTensorValue(outputs[1], {0.0f}, {},
0));
outputs[0]->Unref();
outputs[1]->Unref();
}
#ifdef PLATFORM_GOOGLE
INSTANTIATE_TEST_SUITE_P(
UnifiedCAPI, CppGradients,
::testing::Combine(::testing::Values("graphdef", "mlir"),
::testing::Values(false),
::testing::Values(true, false)));
#else
INSTANTIATE_TEST_SUITE_P(
UnifiedCAPI, CppGradients,
::testing::Combine(::testing::Values("graphdef", "mlir"),
::testing::Values(false),
::testing::Values(true, false)));
#endif
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/c/experimental/gradients/math_grad.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/c/experimental/gradients/math_grad_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
b10bbd84-8d23-498a-992f-f9d31a286f23 | cpp | tensorflow/tensorflow | zero_sized_hlo_elimination | third_party/xla/xla/service/zero_sized_hlo_elimination.cc | third_party/xla/xla/service/zero_sized_hlo_elimination_test.cc | #include "xla/service/zero_sized_hlo_elimination.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/layout_util.h"
#include "xla/literal.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "tsl/platform/errors.h"
namespace xla {
absl::StatusOr<bool> ZeroSizedHloElimination::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
bool changed = false;
for (HloComputation* comp :
module->MakeNonfusionComputations(execution_threads)) {
for (HloInstruction* instruction : comp->MakeInstructionPostOrder()) {
if (instruction->HasSideEffect() || !instruction->shape().IsArray() ||
instruction->opcode() == HloOpcode::kConstant) {
continue;
}
if (comp->IsSafelyRemovable(instruction) &&
ShapeUtil::IsZeroElementArray(instruction->shape()) &&
instruction->shape().is_static()) {
Shape shape = instruction->shape();
if (!LayoutUtil::HasLayout(shape)) {
LayoutUtil::SetToDefaultLayout(&shape);
}
TF_RETURN_IF_ERROR(comp->ReplaceWithNewInstruction(
instruction,
HloInstruction::CreateConstant(Literal::CreateFromShape(shape))));
changed = true;
}
}
}
return changed;
}
} | #include "xla/service/zero_sized_hlo_elimination.h"
#include <memory>
#include <vector>
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/literal_util.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/test.h"
#include "xla/tests/hlo_test_base.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
class ZeroSizedHloEliminationTest : public HloTestBase {
protected:
ZeroSizedHloEliminationTest()
: HloTestBase(),
builder_("zero_sized_computation"),
zero_sized_param_(
builder_.AddInstruction(HloInstruction::CreateParameter(
0, ShapeUtil::MakeShape(F32, {3, 0}), "zero sized param"))) {}
absl::StatusOr<bool> RunZeroSizedElimination() {
auto module = CreateNewVerifiedModule("zero_sized_elimination_test_module");
module->AddEntryComputation(builder_.Build());
return ZeroSizedHloElimination{}.Run(module.get());
}
HloComputation::Builder builder_;
HloInstruction* zero_sized_param_;
};
TEST_F(ZeroSizedHloEliminationTest, EliminatedZeroSizedOp) {
builder_.AddInstruction(HloInstruction::CreateUnary(
zero_sized_param_->shape(), HloOpcode::kTanh, zero_sized_param_));
TF_ASSERT_OK_AND_ASSIGN(bool changed, RunZeroSizedElimination());
EXPECT_TRUE(changed);
}
TEST_F(ZeroSizedHloEliminationTest, DoesNotEliminateParameter) {
TF_ASSERT_OK_AND_ASSIGN(bool changed, RunZeroSizedElimination());
EXPECT_FALSE(changed);
}
TEST_F(ZeroSizedHloEliminationTest, DoesNotEliminateSideEffects) {
auto token = builder_.AddInstruction(HloInstruction::CreateToken());
auto send = builder_.AddInstruction(
HloInstruction::CreateSend(zero_sized_param_, token, 0));
builder_.AddInstruction(HloInstruction::CreateSendDone(send));
TF_ASSERT_OK_AND_ASSIGN(bool changed, RunZeroSizedElimination());
EXPECT_FALSE(changed);
}
TEST_F(ZeroSizedHloEliminationTest, DoesNotEliminateConstant) {
builder_.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR1({})));
TF_ASSERT_OK_AND_ASSIGN(bool changed, RunZeroSizedElimination());
EXPECT_FALSE(changed);
}
TEST_F(ZeroSizedHloEliminationTest, ZeroSizedInstructionWithoutLayoutFolded) {
Shape op_shape = ShapeUtil::MakeShape(F32, {4, 0});
op_shape.clear_layout();
HloInstruction* param1 = builder_.AddInstruction(
HloInstruction::CreateParameter(1, op_shape, "zero sized param 1"));
HloInstruction* param2 = builder_.AddInstruction(
HloInstruction::CreateParameter(2, op_shape, "zero sized param 2"));
builder_.AddInstruction(
HloInstruction::CreateBinary(op_shape, HloOpcode::kAdd, param1, param2));
TF_ASSERT_OK_AND_ASSIGN(bool changed, RunZeroSizedElimination());
EXPECT_TRUE(changed);
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/zero_sized_hlo_elimination.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/zero_sized_hlo_elimination_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
b174aca1-29c4-4460-986b-0277ad8a2da7 | cpp | tensorflow/tensorflow | dequantize_op | tensorflow/compiler/tf2xla/kernels/dequantize_op.cc | tensorflow/core/kernels/dequantize_op_test.cc | #include <array>
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "xla/hlo/builder/lib/constants.h"
#include "xla/hlo/builder/lib/matrix.h"
#include "xla/hlo/builder/xla_builder.h"
#include "tensorflow/core/framework/numeric_types.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/types.pb.h"
namespace tensorflow {
namespace {
constexpr std::array<DataType, 2> kQuantizedType = {{DT_QINT8, DT_QUINT8}};
template <typename T>
float get_fullrange() {
return static_cast<float>(std::numeric_limits<T>::max()) -
std::numeric_limits<T>::min();
}
class DequantizeOp : public XlaOpKernel {
public:
explicit DequantizeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
string mode_string;
int axis;
bool narrow_range;
OP_REQUIRES_OK(ctx, ctx->GetAttr("mode", &mode_string));
OP_REQUIRES(
ctx, (mode_string == "MIN_COMBINED"),
errors::InvalidArgument("Mode string must be 'MIN_COMBINED' is " +
mode_string + "'"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range));
OP_REQUIRES(ctx, narrow_range == false,
errors::InvalidArgument("narrow_range must be false"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis));
OP_REQUIRES(ctx, axis == -1,
errors::InvalidArgument("axis must be -1' is ", axis));
OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_));
}
~DequantizeOp() override = default;
void Compile(XlaOpKernelContext* ctx) override {
DataType input_type = ctx->input_type(0);
xla::XlaOp input = ctx->Input(0);
xla::XlaOp output = xla::ConvertElementType(input, xla::F32);
xla::XlaOp min_range = xla::ConvertElementType(ctx->Input(1), xla::F32);
xla::XlaOp max_range = xla::ConvertElementType(ctx->Input(2), xla::F32);
xla::XlaOp full_range;
xla::XlaOp half_range;
if (input_type == DT_QINT8) {
full_range = ScalarLike(output, get_fullrange<qint8>());
half_range =
(full_range + ScalarLike(output, 1.0f)) / ScalarLike(output, 2.0f);
} else {
OP_REQUIRES(ctx, input_type == DT_QUINT8,
errors::InvalidArgument(
"Only support DT_QINT8 or DT_QUINT8, got ", input_type));
full_range = ScalarLike(output, get_fullrange<quint8>());
half_range = ScalarLike(output, 0.0f);
}
xla::XlaOp scale = (max_range - min_range) / full_range;
output = xla::Add(xla::Mul(xla::Add(output, half_range), scale), min_range);
if (dtype_ == DT_BFLOAT16) {
output = xla::ConvertElementType(output, xla::BF16);
}
ctx->SetOutput(0, output);
}
private:
DataType dtype_;
};
REGISTER_XLA_OP(Name("Dequantize").TypeConstraint("T", kQuantizedType),
DequantizeOp);
}
} | #include <functional>
#include <memory>
#include <random>
#include <vector>
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
namespace {
class DequantizeOpTest : public OpsTestBase {
protected:
template <typename T>
void ComputeDequantizeMinCombinedUsingEigen(const Tensor& input,
float min_range, float max_range,
Tensor* output) {
float half_range =
!std::is_signed<T>::value
? 0.0f
: (static_cast<float>(std::numeric_limits<T>::max()) -
std::numeric_limits<T>::min() + 1) /
2.0f;
const float scale_factor =
(max_range - min_range) /
(static_cast<float>(std::numeric_limits<T>::max()) -
std::numeric_limits<T>::min());
output->flat<float>() =
((input.flat<T>().template cast<int>().template cast<float>() +
half_range) *
scale_factor) +
min_range;
}
template <typename T>
void RunDequantizeMinCombinedTest(float min_range, float max_range,
const string& op_name) {
TF_ASSERT_OK(NodeDefBuilder("dequantize_op", op_name)
.Input(FakeInput(DataTypeToEnum<T>::v()))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Attr("T", DataTypeToEnum<T>::v())
.Attr("mode", "MIN_COMBINED")
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
std::vector<T> input;
for (int64_t i = std::numeric_limits<T>::min();
i < std::numeric_limits<T>::max(); ++i) {
input.push_back(static_cast<T>(i));
}
TensorShape shape({static_cast<int64_t>(input.size())});
AddInputFromArray<T>(shape, input);
AddInputFromArray<float>(TensorShape({}), {min_range});
AddInputFromArray<float>(TensorShape({}), {max_range});
TF_ASSERT_OK(RunOpKernel());
Tensor expected(allocator(), DT_FLOAT, shape);
ComputeDequantizeMinCombinedUsingEigen<T>(GetInput(0), min_range, max_range,
&expected);
test::ExpectTensorEqual<float>(expected, *GetOutput(0));
}
template <typename T>
void RunDequantizeBfloat16MinCombinedTest(float min_range, float max_range) {
TF_ASSERT_OK(NodeDefBuilder("dequantize_op_bfloat16", "Dequantize")
.Input(FakeInput(DataTypeToEnum<T>::v()))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Attr("T", DataTypeToEnum<T>::v())
.Attr("mode", "MIN_COMBINED")
.Attr("dtype", DT_BFLOAT16)
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
std::vector<T> input;
for (int64_t i = std::numeric_limits<T>::min();
i < std::numeric_limits<T>::max(); ++i) {
input.push_back(static_cast<T>(i));
}
TensorShape shape({static_cast<int64_t>(input.size())});
AddInputFromArray<T>(shape, input);
AddInputFromArray<float>(TensorShape({}), {min_range});
AddInputFromArray<float>(TensorShape({}), {max_range});
TF_ASSERT_OK(RunOpKernel());
Tensor expected_float32(allocator(), DT_FLOAT, shape);
ComputeDequantizeMinCombinedUsingEigen<T>(GetInput(0), min_range, max_range,
&expected_float32);
Tensor expected(allocator(), DT_BFLOAT16, shape);
expected.flat<bfloat16>() = expected_float32.flat<float>().cast<bfloat16>();
test::ExpectTensorEqual<bfloat16>(expected, *GetOutput(0));
}
template <typename T>
std::vector<T> ScalePerSliceAlongAxis(std::vector<int64_t> dims, int axis,
const std::vector<T>& data) {
uint32 seed = 123;
std::minstd_rand rng(seed);
int64_t out_size = 1;
for (int dim : dims) {
out_size *= dim;
}
int minor_size = 1;
for (int i = axis + 1; i < dims.size(); ++i) {
minor_size *= dims[i];
}
std::vector<T> out(out_size);
int num_slices = (axis == -1) ? 1 : dims[axis];
for (int out_idx = 0; out_idx < out_size; ++out_idx) {
int in_idx = rng() % data.size();
T multiplier = ((out_idx / minor_size) % num_slices) + 1;
out[out_idx] = data[in_idx] * multiplier;
}
return out;
}
template <typename T>
void RunDequantizeScaledTest(float min_range, float max_range, int axis,
const std::vector<T>& values,
const std::vector<float>& expected) {
const std::vector<int64_t> dims = {2, 3, 4, 5};
int num_slices = (axis == -1) ? 1 : dims[axis];
TF_ASSERT_OK(NodeDefBuilder("dequantize_op", "Dequantize")
.Input(FakeInput(DataTypeToEnum<T>::v()))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Attr("T", DataTypeToEnum<T>::v())
.Attr("mode", "SCALED")
.Attr("axis", axis)
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
AddInputFromArray<T>(TensorShape(dims),
ScalePerSliceAlongAxis(dims, -1, values));
std::vector<float> min_ranges(num_slices), max_ranges(num_slices);
for (int slice_idx = 0; slice_idx < num_slices; ++slice_idx) {
min_ranges[slice_idx] = (slice_idx + 1) * min_range;
max_ranges[slice_idx] = (slice_idx + 1) * max_range;
}
AddInputFromArray<float>(TensorShape({num_slices}), min_ranges);
AddInputFromArray<float>(TensorShape({num_slices}), max_ranges);
TF_ASSERT_OK(RunOpKernel());
Tensor expected_tensor(allocator(), DT_FLOAT, TensorShape(dims));
test::FillValues<float>(&expected_tensor,
ScalePerSliceAlongAxis(dims, axis, expected));
test::ExpectClose(expected_tensor, *GetOutput(0));
}
};
struct ParameterizedDequantizeOpTest
: public OpsTestBase,
public ::testing::WithParamInterface<int> {};
TEST_F(DequantizeOpTest, DequantizeMinCombinedQuint8) {
RunDequantizeMinCombinedTest<quint8>(0, 255.0f, "Dequantize");
}
TEST_F(DequantizeOpTest, DequantizeMinCombinedQint8) {
RunDequantizeMinCombinedTest<qint8>(0, 255.0f, "Dequantize");
}
TEST_F(DequantizeOpTest, DequantizeMinCombinedQint16) {
RunDequantizeMinCombinedTest<qint16>(0, 255.0f, "Dequantize");
}
TEST_F(DequantizeOpTest, DequantizeMinCombinedQuint16) {
RunDequantizeMinCombinedTest<quint16>(0, 255.0f, "Dequantize");
}
TEST_F(DequantizeOpTest, DequantizeBfloat16MinCombinedQuint8) {
RunDequantizeBfloat16MinCombinedTest<quint8>(0, 255.0f);
}
TEST_F(DequantizeOpTest, DequantizeBfloat16MinCombinedQint8) {
RunDequantizeBfloat16MinCombinedTest<qint8>(0, 255.0f);
}
TEST_F(DequantizeOpTest, DequantizeBfloat16MinCombinedQint16) {
RunDequantizeBfloat16MinCombinedTest<qint16>(0, 255.0f);
}
TEST_F(DequantizeOpTest, DequantizeBfloat16MinCombinedQuint16) {
RunDequantizeBfloat16MinCombinedTest<quint16>(0, 255.0f);
}
TEST_F(DequantizeOpTest, DequantizeScaledQuint8Zero) {
RunDequantizeScaledTest<quint8>(-255.0f, 127.0f, -1, {0}, {0.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQuint8CheckIgnoresNegative) {
RunDequantizeScaledTest<quint8>(-512.0f, 255.0f, -1, {255}, {255.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQuint8ScaleDown) {
RunDequantizeScaledTest<quint8>(-1.0f, 2.0f, -1, {255}, {2.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQuint8ScaleUp) {
RunDequantizeScaledTest<quint8>(200.0f, 400.0f, -1, {255}, {400.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQint8Zero) {
RunDequantizeScaledTest<qint8>(-255.0f, 127.0f, -1, {0}, {0.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQint8ScaleIdentity) {
RunDequantizeScaledTest<qint8>(-10.0f, 127.0f, -1, {-127}, {-127.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQint8ScaleDown) {
RunDequantizeScaledTest<qint8>(-2.0f, 1.0f, -1, {-128}, {-2.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQint8ScaleUp) {
RunDequantizeScaledTest<qint8>(-1.0f, 300.0f, -1, {42}, {99.212601});
}
TEST_F(DequantizeOpTest, DequantizeScaledQint8Axis1) {
RunDequantizeScaledTest<qint8>(-12.8f, 12.7f, 1, {-20, -10, 0, 1, 10, 20},
{-2.0, -1.0, 0.0, 0.1, 1.0, 2.0});
}
TEST_F(DequantizeOpTest, DequantizeScaledQint8Axis3) {
RunDequantizeScaledTest<qint8>(-12.8f, 12.7f, 3, {-20, -10, 0, 1, 10, 20},
{-2.0, -1.0, 0.0, 0.1, 1.0, 2.0});
}
template <typename T>
static void BM_DequantizeMinCombinedCpu(::testing::benchmark::State& state) {
auto root = Scope::NewRootScope().ExitOnError();
const int64_t num_values = 1500 * 250;
std::vector<T> inputs;
inputs.reserve(num_values);
for (int i = 0; i < num_values; ++i) inputs.push_back(i);
ops::Dequantize give_me_a_name(root, test::AsTensor<T>(inputs),
test::AsScalar<float>(-1.5f),
test::AsScalar<float>(20.5f),
ops::Dequantize::Attrs().Mode("MIN_COMBINED"));
TF_CHECK_OK(root.status());
Graph* g = new Graph(OpRegistry::Global());
TF_CHECK_OK(root.ToGraph(g));
test::Benchmark("cpu", g, false).Run(state);
state.SetBytesProcessed(state.iterations() * num_values *
(sizeof(float) + sizeof(T)));
state.SetItemsProcessed(state.iterations());
}
void BM_DequantizeMinCombinedCpuQuint16(::testing::benchmark::State& state) {
BM_DequantizeMinCombinedCpu<quint16>(state);
}
void BM_DequantizeMinCombinedCpuQint16(::testing::benchmark::State& state) {
BM_DequantizeMinCombinedCpu<qint16>(state);
}
void BM_DequantizeMinCombinedCpuQuint8(::testing::benchmark::State& state) {
BM_DequantizeMinCombinedCpu<quint8>(state);
}
void BM_DequantizeMinCombinedCpuQint8(::testing::benchmark::State& state) {
BM_DequantizeMinCombinedCpu<qint8>(state);
}
BENCHMARK(BM_DequantizeMinCombinedCpuQuint16);
BENCHMARK(BM_DequantizeMinCombinedCpuQint16);
BENCHMARK(BM_DequantizeMinCombinedCpuQuint8);
BENCHMARK(BM_DequantizeMinCombinedCpuQint8);
template <typename T>
static void BM_DequantizeBfloat16MinCombinedCpu(
::testing::benchmark::State& state) {
auto root = Scope::NewRootScope().ExitOnError();
const int64_t num_values = 1500 * 250;
std::vector<T> inputs;
inputs.reserve(num_values);
for (int i = 0; i < num_values; ++i) inputs.push_back(i);
ops::Dequantize give_me_a_name(root, test::AsTensor<T>(inputs),
test::AsScalar<float>(-1.5f),
test::AsScalar<float>(20.5f),
ops::Dequantize::Attrs().Dtype(DT_BFLOAT16));
TF_CHECK_OK(root.status());
Graph* g = new Graph(OpRegistry::Global());
TF_CHECK_OK(root.ToGraph(g));
test::Benchmark("cpu", g, false).Run(state);
state.SetBytesProcessed(state.iterations() * num_values *
(sizeof(bfloat16) + sizeof(T)));
state.SetItemsProcessed(state.iterations());
}
void BM_DequantizeBfloat16MinCombinedCpuQuint16(
::testing::benchmark::State& state) {
BM_DequantizeBfloat16MinCombinedCpu<quint16>(state);
}
void BM_DequantizeBfloat16MinCombinedCpuQint16(
::testing::benchmark::State& state) {
BM_DequantizeBfloat16MinCombinedCpu<qint16>(state);
}
void BM_DequantizeBfloat16MinCombinedCpuQuint8(
::testing::benchmark::State& state) {
BM_DequantizeBfloat16MinCombinedCpu<quint8>(state);
}
void BM_DequantizeBfloat16MinCombinedCpuQint8(
::testing::benchmark::State& state) {
BM_DequantizeBfloat16MinCombinedCpu<qint8>(state);
}
BENCHMARK(BM_DequantizeBfloat16MinCombinedCpuQuint16);
BENCHMARK(BM_DequantizeBfloat16MinCombinedCpuQint16);
BENCHMARK(BM_DequantizeBfloat16MinCombinedCpuQuint8);
BENCHMARK(BM_DequantizeBfloat16MinCombinedCpuQint8);
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/kernels/dequantize_op.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/kernels/dequantize_op_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
ff4abb2c-ab85-4700-8461-1d3ad21f9d18 | cpp | tensorflow/tensorflow | xla_compiler | tensorflow/compiler/tf2xla/xla_compiler.cc | tensorflow/compiler/tf2xla/xla_compiler_test.cc | #include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include <algorithm>
#include <array>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "tensorflow/compiler/mlir/tf2xla/mlir_bridge_rollout_policy.h"
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/types/variant.h"
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/jit/shape_inference.h"
#include "tensorflow/compiler/jit/xla_compile_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/attribute_utils.h"
#include "tensorflow/compiler/mlir/tf2xla/api/v1/compile_mlir_util.h"
#include "tensorflow/compiler/mlir/utils/array_container_utils.h"
#include "tensorflow/compiler/tf2xla/graph_compiler.h"
#include "tensorflow/compiler/tf2xla/layout_util.h"
#include "tensorflow/compiler/tf2xla/rearrange_function_argument.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/sharding_util.h"
#include "tensorflow/compiler/tf2xla/side_effect_util.h"
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_compilation_device.h"
#include "tensorflow/compiler/tf2xla/xla_context.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "xla/client/client_library.h"
#include "xla/hlo/builder/xla_builder.h"
#include "xla/hlo/builder/xla_computation.h"
#include "xla/protobuf_util.h"
#include "xla/service/hlo.pb.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/executor.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/common_runtime/graph_optimizer.h"
#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/graph_debug_info.pb.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
#include "tensorflow/core/tpu/tpu_defs.h"
#include "tensorflow/core/util/debug_data_dumper.h"
#include "tensorflow/core/util/dump_graph.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/tensor_float_32_utils.h"
namespace tensorflow {
namespace {
constexpr char kSingleOpComponent[] = "TF2XLA_XLA_COMPILER_COMPILE_SINGLE_OP";
constexpr char kCompileFunctionComponent[] =
"TF2XLA_XLA_COMPILER_COMPILE_FUNCTION";
Status CheckSignature(const DataTypeVector& types,
absl::Span<const XlaCompiler::Argument> args) {
if (args.size() != types.size()) {
return errors::Internal("Compilation arguments have ", args.size(),
" elements while function has ", types.size());
}
for (int i = 0, end = types.size(); i < end; ++i) {
if (types[i] != args[i].type && types[i] != DT_RESOURCE &&
types[i] != DT_VARIANT) {
return errors::Internal(
"Argument ", i, " has declared type ", DataTypeString(args[i].type),
" but function parameter has type ", DataTypeString(types[i]));
}
}
return absl::OkStatus();
}
absl::StatusOr<
std::pair<std::map<int, xla::OpSharding>, std::map<int, xla::OpSharding>>>
ComputeArgAndRetvalShardings(const Graph& graph) {
auto get_sharding_for_node =
[](const Node* n) -> absl::StatusOr<std::optional<xla::OpSharding>> {
TF_ASSIGN_OR_RETURN(
auto sharding,
ParseShardingFromDevice(*n, std::numeric_limits<int32>::max(),
false));
return sharding;
};
std::map<int, xla::OpSharding> arg_shardings;
std::map<int, xla::OpSharding> retval_shardings;
for (const Node* n : graph.nodes()) {
if (n->IsArg()) {
TF_ASSIGN_OR_RETURN(auto sharding, get_sharding_for_node(n));
if (!sharding.has_value()) continue;
int index;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index));
TF_RET_CHECK(index >= 0) << "Negative _Arg index";
arg_shardings[index] = std::move(*sharding);
} else if (n->IsRetval()) {
TF_ASSIGN_OR_RETURN(auto sharding, get_sharding_for_node(n));
if (!sharding.has_value()) continue;
int index;
TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index));
TF_RET_CHECK(index >= 0) << "Negative _Retval index";
retval_shardings[index] = std::move(*sharding);
}
}
return std::make_pair(std::move(arg_shardings), std::move(retval_shardings));
}
Status ExecuteGraph(XlaContext* xla_context, std::unique_ptr<Graph> graph,
XlaCompilationDevice* device, FunctionLibraryRuntime* flib,
int64_t step_id) {
xla_context->Ref();
Status status;
auto step_container = std::make_unique<ScopedStepContainer>(
step_id, [&status, device](const string& name) {
status = device->resource_manager()->Cleanup(name);
});
TF_RETURN_IF_ERROR(step_container->Create(device->resource_manager(),
XlaContext::kXlaContextResourceName,
xla_context));
GraphCompiler graph_compiler(device, graph.get(), flib, step_container.get());
TF_RETURN_IF_ERROR(graph_compiler.Compile());
step_container.reset();
return status;
}
Status BuildComputation(
const std::vector<XlaCompiler::Argument>& args,
const std::vector<XlaExpression>& retvals,
const std::map<int, xla::OpSharding>& arg_shardings,
const std::map<int, xla::OpSharding>& retval_shardings,
const std::vector<std::unique_ptr<XlaResource>>& resources,
std::unique_ptr<xla::XlaOp> token_output,
const XlaShapeLayoutHelpers::ShapeDeterminationFns& shape_determination_fns,
bool is_entry_computation, bool return_updated_values_for_all_resources,
bool always_return_tuple, bool use_tuple_arg, bool alias_resource_update,
xla::XlaBuilder* builder, xla::XlaComputation* computation,
int* num_computation_outputs, int* num_nonconst_outputs,
std::vector<XlaCompiler::OutputDescription>* outputs,
std::vector<XlaCompiler::ResourceUpdate>* resource_updates,
xla::Shape* output_shape, absl::Span<int const> input_mapping) {
xla::OpMetadata retval_metadata;
retval_metadata.set_op_name("XLA_Retvals");
builder->SetOpMetadata(retval_metadata);
VLOG(1) << "Building new computation";
auto cleanup = gtl::MakeCleanup([builder]() { builder->ClearOpMetadata(); });
auto identity_op = [builder](xla::XlaOp op,
const std::optional<xla::OpSharding>& sharding) {
xla::XlaScopedShardingAssignment assign_sharding(builder, sharding);
return xla::Copy(op);
};
std::vector<xla::XlaOp> elems;
elems.reserve(retvals.size());
std::unordered_map<int, xla::OpSharding> retval_index_and_sharding;
for (int i = 0, end = retvals.size(); i < end; ++i) {
XlaCompiler::OutputDescription& output = (*outputs)[i];
const XlaExpression& retval = retvals[i];
output.type = retval.dtype();
switch (retval.kind()) {
case XlaExpression::Kind::kConstant:
output.is_constant = true;
output.constant_value = *retval.constant_value();
output.shape = output.constant_value.shape();
break;
case XlaExpression::Kind::kTensorList: {
output.is_tensor_list = true;
xla::XlaOp value = retval.handle();
elems.push_back(value);
break;
}
case XlaExpression::Kind::kXlaOp: {
output.is_constant = false;
TF_ASSIGN_OR_RETURN(output.shape, retval.GetShape());
xla::XlaOp value = retval.handle();
auto it = retval_shardings.find(i);
std::optional<xla::OpSharding> sharding =
it == retval_shardings.end() ? std::optional<xla::OpSharding>()
: it->second;
if (it != retval_shardings.end()) {
retval_index_and_sharding[elems.size()] = it->second;
}
if (shape_determination_fns.shape_representation_fn) {
TF_ASSIGN_OR_RETURN(auto original_shape, builder->GetShape(value));
TF_ASSIGN_OR_RETURN(value,
ReshapeWithCorrectRepresentationAndSharding(
builder, value, original_shape,
shape_determination_fns, sharding,
false));
}
if (it != retval_shardings.end()) {
value = identity_op(value, sharding);
}
elems.push_back(value);
break;
}
case XlaExpression::Kind::kResource:
output.is_constant = false;
output.input_index = retval.resource()->arg_num();
output.shape = retval.resource()->shape();
break;
case XlaExpression::Kind::kInvalid:
return errors::InvalidArgument(
"Invalid expression returned by computation. "
"This probably means a return value was not set.");
}
}
*num_nonconst_outputs = elems.size();
std::vector<const XlaResource*> arg_resources;
arg_resources.reserve(resources.size());
for (const auto& resource : resources) {
if (resource->arg_num() >= 0) {
arg_resources.push_back(resource.get());
}
}
std::sort(arg_resources.begin(), arg_resources.end(),
[](const XlaResource* a, const XlaResource* b) {
return a->arg_num() < b->arg_num();
});
absl::flat_hash_map<int, int> argument_to_xla_arg;
for (int xla_arg = 0; xla_arg < input_mapping.size(); xla_arg++) {
argument_to_xla_arg[input_mapping[xla_arg]] = xla_arg;
}
std::vector<xla::XlaBuilder::InputOutputAlias> aliases;
for (const XlaResource* resource : arg_resources) {
DCHECK_LT(resource->arg_num(), args.size());
const XlaCompiler::Argument& arg = args[resource->arg_num()];
auto it = arg_shardings.find(resource->arg_num());
bool modified = !resource->value().IsIdenticalTo(resource->initial_value());
for (const auto& grad : resource->tensor_array_gradients()) {
modified =
modified ||
!grad.second->value().IsIdenticalTo(grad.second->initial_value()) ||
arg.tensor_array_gradients.count(grad.first) == 0;
}
if (return_updated_values_for_all_resources || modified ||
arg.requires_broadcast) {
resource_updates->emplace_back();
XlaCompiler::ResourceUpdate& update = resource_updates->back();
update.input_index = resource->arg_num();
update.type = resource->type();
update.shape = resource->shape();
update.modified = modified;
int param_num = use_tuple_arg ? 0 : update.input_index;
if (is_entry_computation &&
arg.resource_kind != XlaResource::kTensorArray &&
alias_resource_update && argument_to_xla_arg.count(param_num)) {
xla::ShapeIndex param_index =
use_tuple_arg ? xla::ShapeIndex({update.input_index})
: xla::ShapeIndex{};
int xla_param_num = argument_to_xla_arg[param_num];
int64_t output_index_num = elems.size();
xla::ShapeIndex output_index = xla::ShapeIndex({output_index_num});
VLOG(3) << "Storing alias: " << output_index.ToString() << ": ("
<< xla_param_num << ", " << param_index.ToString() << ")";
aliases.push_back({output_index, xla_param_num, param_index});
}
for (const auto& grad : resource->tensor_array_gradients()) {
update.tensor_array_gradients_accessed.insert(grad.first);
}
xla::XlaOp handle;
TF_RETURN_IF_ERROR(resource->Pack(&handle, builder));
auto sharding = it == arg_shardings.end()
? std::optional<xla::OpSharding>()
: it->second;
if (shape_determination_fns.layout_preference_fn &&
shape_determination_fns.shape_representation_fn) {
TF_ASSIGN_OR_RETURN(auto original_shape, builder->GetShape(handle));
TF_ASSIGN_OR_RETURN(
handle, ReshapeWithCorrectRepresentationAndSharding(
builder, handle, original_shape,
shape_determination_fns, sharding, arg.fast_mem));
}
if (it != arg_shardings.end()) {
retval_index_and_sharding[elems.size()] = it->second;
}
handle = identity_op(handle, sharding);
elems.push_back(handle);
}
}
if (token_output) {
elems.push_back(*token_output);
}
*num_computation_outputs = elems.size();
xla::XlaOp tuple;
if (retval_index_and_sharding.empty() || !is_entry_computation) {
tuple = xla::Tuple(builder, elems);
} else {
std::vector<xla::Shape> elem_shapes;
for (const auto& elem : elems) {
TF_ASSIGN_OR_RETURN(xla::Shape elem_shape,
elem.builder()->GetShape(elem));
elem_shapes.push_back(elem_shape);
}
xla::Shape shape = xla::ShapeUtil::MakeTupleShape(elem_shapes);
std::vector<xla::HloSharding> sharding_elems;
for (int i = 0, end = elems.size(); i < end; i++) {
const auto& iter = retval_index_and_sharding.find(i);
TF_RET_CHECK(iter != retval_index_and_sharding.end());
const xla::OpSharding& sub_op_sharding = iter->second;
TF_ASSIGN_OR_RETURN(xla::HloSharding sub_sharding,
xla::HloSharding::FromProto(sub_op_sharding));
if (elem_shapes[i].IsTuple()) {
const std::vector<xla::HloSharding> sub_sharding_elems =
sub_sharding.tuple_elements();
const int64_t sub_sharding_elems_size = sub_sharding_elems.size();
TF_RET_CHECK(sub_sharding_elems_size ==
xla::ShapeUtil::GetLeafCount(elem_shapes[i]));
for (const auto& sub_sharding_elem : sub_sharding_elems) {
sharding_elems.push_back(sub_sharding_elem);
}
} else {
sharding_elems.push_back(sub_sharding);
}
}
xla::HloSharding modified_sharding =
xla::HloSharding::Tuple(shape, sharding_elems);
xla::OpSharding op_sharding = modified_sharding.ToProto();
xla::XlaScopedShardingAssignment assign_sharding(builder, op_sharding);
tuple = xla::Tuple(builder, elems);
}
bool returns_tuple = always_return_tuple || elems.size() != 1;
VLOG(3) << "Computation returns a tuple=" << returns_tuple;
if (!returns_tuple) {
xla::GetTupleElement(tuple, 0);
for (xla::XlaBuilder::InputOutputAlias& alias : aliases) {
if (alias.output_index == xla::ShapeIndex({0})) {
VLOG(3) << "For aliased parameter " << alias.param_number << ": "
<< alias.param_index.ToString()
<< " normalizing output_index from {0} to {}, as a scalar is "
"returned from the cluster";
alias.output_index = xla::ShapeIndex({});
}
}
}
for (xla::XlaBuilder::InputOutputAlias& alias : aliases) {
builder->SetUpAlias(alias.output_index, alias.param_number,
alias.param_index);
}
TF_ASSIGN_OR_RETURN(*computation, builder->Build());
TF_ASSIGN_OR_RETURN(auto program_shape, computation->GetProgramShape());
*output_shape = program_shape.result();
return absl::OkStatus();
}
}
string XlaCompiler::Argument::HumanString() const {
string common;
if (!name.empty()) {
common = absl::StrCat(" name=", name);
}
absl::StrAppend(&common, " type=", DataTypeString(type),
" shape=", ShapeHumanString());
absl::StrAppend(
&common, " is_same_data_across_replicas=", is_same_data_across_replicas);
switch (kind) {
case kInvalid:
return "invalid";
case kConstant:
return absl::StrCat("kind=constant", common,
" value=", constant_value.DebugString());
case kConstantResource:
return absl::StrCat("kind=constant-resource", common,
" value=", constant_value.DebugString());
case kResource: {
string output = absl::StrCat(
"kind=resource", common,
" resource_kind=", XlaResource::KindToString(resource_kind),
" initialized=", initialized, " is_fast_mem=", fast_mem);
if (max_array_size >= 0) {
absl::StrAppend(&output, " max_array_size=", max_array_size);
}
if (!tensor_array_gradients.empty()) {
absl::StrAppend(&output, " tensor_array_gradients=",
absl::StrJoin(tensor_array_gradients, ","));
}
return output;
}
case kParameter:
return absl::StrCat("kind=parameter", common);
case kTensorList:
return absl::StrCat("kind=tensorlist", common);
case kToken:
return absl::StrCat("token", common);
}
}
std::vector<int64_t> XlaCompiler::Argument::DimensionSizes() const {
if (absl::holds_alternative<TensorShape>(shape)) {
return xla::InlinedVectorToVector(std::get<TensorShape>(shape).dim_sizes());
} else {
return xla::SpanToVector(std::get<xla::Shape>(shape).dimensions());
}
}
absl::InlinedVector<int64_t, 4>
XlaCompiler::Argument::DimensionSizesAsInlinedVector() const {
if (absl::holds_alternative<TensorShape>(shape)) {
return std::get<TensorShape>(shape).dim_sizes();
} else {
auto v = std::get<xla::Shape>(shape).dimensions();
return absl::InlinedVector<int64_t, 4>(v.begin(), v.end());
}
}
string XlaCompiler::Argument::ShapeHumanString() const {
if (absl::holds_alternative<TensorShape>(shape)) {
return std::get<TensorShape>(shape).DebugString();
} else {
return std::get<xla::Shape>(shape).DebugString();
}
}
XlaCompiler::XlaCompiler(XlaCompiler::Options options)
: options_(options),
initialization_status_(absl::OkStatus()),
next_step_id_(1),
device_(new XlaCompilationDevice(SessionOptions(), options_.device_type)),
device_mgr_(absl::WrapUnique(device_)) {
CHECK(!options_.device_type.type_string().empty());
if (options_.populate_resource_manager) {
initialization_status_ =
(*options_.populate_resource_manager)(device_->resource_manager());
}
local_flib_def_.reset(new FunctionLibraryDefinition(OpRegistry::Global(),
FunctionDefLibrary()));
local_pflr_.reset(new ProcessFunctionLibraryRuntime(
&device_mgr_, Env::Default(), nullptr,
options.graph_def_version, local_flib_def_.get(), OptimizerOptions()));
pflr_.reset(new ProcessFunctionLibraryRuntime(
&device_mgr_, Env::Default(), nullptr,
options.graph_def_version, options.flib_def, OptimizerOptions()));
local_flib_runtime_ = local_pflr_->GetFLR(device_->name());
flib_runtime_ = pflr_->GetFLR(device_->name());
XlaShapeLayoutHelpers::ShapeDeterminationFns& shape_determination_fns =
options_.shape_determination_fns;
if (!shape_determination_fns.shape_representation_fn) {
shape_determination_fns.shape_representation_fn =
IdentityShapeRepresentationFn();
}
if (!shape_determination_fns.layout_preference_fn) {
shape_determination_fns.layout_preference_fn = UseNoPreferenceLayoutFn();
}
}
XlaCompiler::~XlaCompiler() = default;
int64_t XlaCompiler::NextStepId() { return next_step_id_++; }
uint64 XlaCompiler::SignatureHash::operator()(
const std::pair<string, std::vector<Argument>>& signature) const {
return std::hash<string>()(signature.first);
}
static Status GetFunctionBody(const NameAttrList& function,
FunctionLibraryRuntime* flib_runtime,
const FunctionBody** fbody) {
FunctionLibraryRuntime::Handle handle;
TF_RETURN_IF_ERROR(flib_runtime->Instantiate(
function.name(), AttrSlice(&function.attr()), &handle));
*fbody = flib_runtime->GetFunctionBody(handle);
TF_RET_CHECK(*fbody);
return absl::OkStatus();
}
Status XlaCompiler::FindFunctionBody(const NameAttrList& function,
const FunctionBody** fbody,
const ConfigProto** config_proto) {
auto status = GetFunctionBody(function, local_flib_runtime_, fbody);
if (!status.ok()) {
if (!absl::IsNotFound(status)) {
return status;
}
TF_RETURN_WITH_CONTEXT_IF_ERROR(
GetFunctionBody(function, flib_runtime_, fbody),
"Local lookup failed with: ", status.message());
if (config_proto) {
*config_proto = flib_runtime_->config_proto();
}
VLOG(4) << "Function " << function.name() << " in flib_runtime_";
} else {
if (config_proto) {
*config_proto = local_flib_runtime_->config_proto();
}
VLOG(4) << "Function " << function.name() << " in local_flib_runtime_";
}
return absl::OkStatus();
}
std::unique_ptr<Graph> XlaCompiler::GetGraph(const FunctionBody* fbody) {
std::unique_ptr<Graph> graph(new Graph(options_.flib_def));
CopyGraph(*fbody->graph, graph.get());
bool is_inside_mustcompile = false;
TryGetNodeAttr(AttrSlice(&fbody->record->fdef().attr()), kXlaMustCompileAttr,
&is_inside_mustcompile);
auto flags = GetBuildXlaOpsPassFlags();
OptimizerOptions opts;
opts.set_opt_level(OptimizerOptions::L0);
opts.set_do_common_subexpression_elimination(false);
opts.set_do_function_inlining(true);
opts.set_do_constant_folding(!flags->tf_xla_disable_constant_folding);
GraphOptimizer optimizer(opts);
auto cf_consider_fn = [](const Node* n) {
for (const auto& output_arg : n->op_def().output_arg()) {
if (output_arg.type() == DT_VARIANT) {
return false;
}
}
const auto& ts = n->type_string();
if (ts == "Shape" || ts == "ShapeN" || ts == "Size") {
return false;
}
return true;
};
GraphOptimizer::Options graph_optimizer_options;
graph_optimizer_options.cf_consider_fn = cf_consider_fn;
graph_optimizer_options.inline_multi_device_functions = true;
graph_optimizer_options.inline_impl_selection_group_functions = true;
graph_optimizer_options.inline_with_single_device_body_placer = true;
graph_optimizer_options.ignore_noinline = is_inside_mustcompile;
{
GraphShapeInfo shape_info;
InferShapes(graph.get(), {},
flib_runtime_->GetFunctionLibraryDefinition(), &shape_info)
.IgnoreError();
auto node_name_index = graph->BuildNodeNameIndex();
std::unordered_map<string, std::vector<PartialTensorShape>> shape_map;
for (const auto& node_shape_info : shape_info) {
const string& node_name = node_shape_info.first;
const std::vector<InferredShape>& output_shapes = node_shape_info.second;
const auto& node_iter = node_name_index.find(node_name);
if (node_iter != node_name_index.end()) {
auto& partial_shapes = shape_map[node_name];
for (const auto& inferred_shape : output_shapes) {
partial_shapes.push_back(inferred_shape.shape);
}
}
}
graph_optimizer_options.shape_map = &shape_map;
optimizer.Optimize(flib_runtime_, flib_runtime_->env(),
nullptr, &graph, graph_optimizer_options);
}
GraphShapeInfo shape_info;
InferShapes(graph.get(), {},
flib_runtime_->GetFunctionLibraryDefinition(), &shape_info)
.IgnoreError();
auto node_name_index = graph->BuildNodeNameIndex();
std::unordered_map<string, std::vector<PartialTensorShape>> shape_map;
for (const auto& node_shape_info : shape_info) {
const string& node_name = node_shape_info.first;
const std::vector<InferredShape>& output_shapes = node_shape_info.second;
const auto& node_iter = node_name_index.find(node_name);
if (node_iter != node_name_index.end()) {
auto& partial_shapes = shape_map[node_name];
for (const auto& inferred_shape : output_shapes) {
partial_shapes.push_back(inferred_shape.shape);
}
}
}
graph_optimizer_options.shape_map = &shape_map;
optimizer.Optimize(flib_runtime_, flib_runtime_->env(),
nullptr, &graph, graph_optimizer_options);
return graph;
}
std::vector<std::string> GetValidControlRets(
absl::Span<Node* const> orig_control_ret_nodes, const Graph& graph) {
absl::flat_hash_map<string, int> control_ret_nodes_map;
for (int i = 0; i < orig_control_ret_nodes.size(); ++i) {
const Node* n = orig_control_ret_nodes[i];
control_ret_nodes_map[n->name()] = i;
}
std::vector<bool> is_valid_control_ret(orig_control_ret_nodes.size(), false);
int num_valid_control_rets = 0;
for (const Node* n : graph.nodes()) {
auto iter = control_ret_nodes_map.find(n->name());
if (iter != control_ret_nodes_map.end()) {
++num_valid_control_rets;
is_valid_control_ret[iter->second] = true;
}
}
std::vector<std::string> valid_control_rets;
valid_control_rets.reserve(num_valid_control_rets);
for (int i = 0; i < orig_control_ret_nodes.size(); ++i) {
if (is_valid_control_ret[i]) {
valid_control_rets.push_back(orig_control_ret_nodes[i]->name());
}
}
return valid_control_rets;
}
Status XlaCompiler::CompileSingleOp(
const XlaCompiler::CompileOptions& compile_options,
const XlaCompiler::SingleOpCompileArgument& single_op_compile_argument,
absl::Span<const Argument> args, XlaCompiler::CompilationResult* result) {
const NodeDef& node_def = single_op_compile_argument.node_def;
TF_ASSIGN_OR_RETURN(
auto graph,
CreateSingleOpGraph(node_def, args,
single_op_compile_argument.output_dtypes));
*result = {};
Status status = ADD_SOURCE_LOCATION(CompileGraph(
compile_options, node_def.name(), std::move(graph), args, result));
if (status.ok()) {
tensorflow::metrics::IncrementPhase2XlaCompilerCounter(
tensorflow::metrics::Phase2XlaCompilerMetric::
kCompileSingleOpXlaBuilderSuccess);
} else {
tensorflow::metrics::IncrementPhase2XlaCompilerCounter(
tensorflow::metrics::Phase2XlaCompilerMetric::
kCompileSingleOpXlaBuilderFailure);
tsl::error_logging::Log(mlir::TF::kBridgeComponent, kSingleOpComponent,
status.ToString())
.IgnoreError();
}
return status;
}
Status XlaCompiler::CompileFunction(
const XlaCompiler::CompileOptions& options,
const NameAttrList& fn_name_attrs,
absl::Span<const XlaCompiler::Argument> args,
XlaCompiler::CompilationResult* result) {
string function_id =
Canonicalize(fn_name_attrs.name(), AttrSlice(&fn_name_attrs.attr()));
VLOG(1) << "XlaCompiler::CompileFunction " << function_id;
const std::vector<XlaCompiler::Argument> arg_vector(args.begin(), args.end());
auto it = cache_.find({function_id, arg_vector});
if (it != cache_.end()) {
*result = it->second;
return absl::OkStatus();
}
const FunctionBody* fbody;
const ConfigProto* config = nullptr;
TF_RETURN_IF_ERROR(FindFunctionBody(fn_name_attrs, &fbody, &config));
std::optional<ConfigProto> config_proto;
if (config) {
config_proto = *config;
}
TF_RETURN_WITH_CONTEXT_IF_ERROR(
CheckSignature(fbody->arg_types, args),
"Signature check failure while compiling: ", fn_name_attrs.name());
for (int i = 0, end = args.size(); i < end; i++) {
DataType dtype;
TF_RETURN_IF_ERROR(GetNodeAttr(fbody->arg_nodes[i]->def(), "T", &dtype));
if (dtype == DT_RESOURCE || dtype == DT_VARIANT) {
continue;
}
if (absl::holds_alternative<xla::Shape>(args[i].shape)) {
xla::Shape xla_shape = std::get<xla::Shape>(args[i].shape);
TensorShape tensor_shape;
if (XLAShapeToTensorShape(xla_shape, &tensor_shape).ok() &&
xla_shape.is_static()) {
fbody->arg_nodes[i]->ClearAttr("_output_shapes");
fbody->arg_nodes[i]->AddAttr("_output_shapes",
std::vector<TensorShape>{tensor_shape});
}
} else {
TensorShape tensor_shape = std::get<TensorShape>(args[i].shape);
fbody->arg_nodes[i]->ClearAttr("_output_shapes");
fbody->arg_nodes[i]->AddAttr("_output_shapes",
std::vector<TensorShape>{tensor_shape});
}
}
std::unique_ptr<Graph> graph = GetGraph(fbody);
for (Node* n : graph->nodes()) {
if (n->IsArg()) {
TF_RETURN_IF_ERROR(SetNodeShardingFromNeighbors(n, true));
}
}
for (Node* n : graph->nodes()) {
if (n->IsRetval()) {
TF_RETURN_IF_ERROR(SetNodeShardingFromNeighbors(n, false));
}
}
if (VLOG_IS_ON(2)) {
VLOG(2) << "XlaCompiler::CompileFunction: "
<< DumpGraphToFile(
absl::StrCat("xla_compile_function_", function_id), *graph);
}
VLOG(1) << "====================================================";
VLOG(1) << "CompileFunction with XlaBuilder";
auto status =
CompileGraph(options, function_id, std::move(graph), args, result);
if (!status.ok()) {
tensorflow::metrics::IncrementPhase2XlaCompilerCounter(
tensorflow::metrics::Phase2XlaCompilerMetric::
kCompileFunctionXlaBuilderFailure);
::tsl::errors::AppendToMessage(
&status, "tf2xla conversion failed while converting ",
std::move(function_id),
". Run with TF_DUMP_GRAPH_PREFIX=/path/to/dump/dir and "
"--vmodule=xla_compiler=2 to obtain a dump of the compiled "
"functions.");
tsl::error_logging::Log(mlir::TF::kBridgeComponent,
kCompileFunctionComponent, status.ToString())
.IgnoreError();
return status;
}
tensorflow::metrics::IncrementPhase2XlaCompilerCounter(
tensorflow::metrics::Phase2XlaCompilerMetric::
kCompileFunctionXlaBuilderSuccess);
VLOG(1) << "====================================================";
cache_[{function_id, arg_vector}] = *result;
return absl::OkStatus();
}
Status XlaCompiler::XLAShapeForArgument(
const XlaCompiler::Argument& arg, bool is_entry_computation,
const std::optional<xla::HloSharding>& arg_sharding,
xla::Shape* xla_shape) const {
switch (arg.kind) {
case XlaCompiler::Argument::kConstant:
LOG(FATAL) << "Unreachable case";
case XlaCompiler::Argument::kParameter: {
if (is_entry_computation) {
TensorShape shape;
if (std::holds_alternative<TensorShape>(arg.shape)) {
shape = std::get<TensorShape>(arg.shape);
} else {
TF_RETURN_IF_ERROR(
XLAShapeToTensorShape(std::get<xla::Shape>(arg.shape), &shape));
}
auto layout_preference =
options_.shape_determination_fns.layout_preference_fn(
shape, arg.type, arg.kind);
TF_ASSIGN_OR_RETURN(
*xla_shape,
options_.shape_determination_fns.shape_representation_fn(
shape, arg.type,
false, layout_preference));
TF_RETURN_IF_ERROR(RewriteLayoutWithShardedShape(
arg_sharding, false,
options_.shape_determination_fns, xla_shape));
if (std::holds_alternative<xla::Shape>(arg.shape) &&
std::get<xla::Shape>(arg.shape).is_dynamic()) {
xla::Shape dynamic_shape = std::get<xla::Shape>(arg.shape);
for (int i = 0; i < xla_shape->dimensions_size(); ++i) {
xla_shape->set_dynamic_dimension(
i, dynamic_shape.is_dynamic_dimension(i));
}
}
} else {
if (std::holds_alternative<xla::Shape>(arg.shape)) {
*xla_shape = std::get<xla::Shape>(arg.shape);
} else {
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(
arg.type, std::get<TensorShape>(arg.shape), xla_shape));
}
}
return absl::OkStatus();
}
case XlaCompiler::Argument::kTensorList: {
TF_RET_CHECK(absl::holds_alternative<xla::Shape>(arg.shape));
*xla_shape = std::get<xla::Shape>(arg.shape);
return absl::OkStatus();
}
case XlaCompiler::Argument::kConstantResource:
case XlaCompiler::Argument::kResource: {
TF_RET_CHECK(arg.initialized);
switch (arg.resource_kind) {
case XlaResource::kVariable: {
TF_RET_CHECK(absl::holds_alternative<TensorShape>(arg.shape));
auto layout_preference =
options_.shape_determination_fns.layout_preference_fn(
std::get<TensorShape>(arg.shape), arg.type, arg.kind);
TF_ASSIGN_OR_RETURN(
*xla_shape,
options_.shape_determination_fns.shape_representation_fn(
std::get<TensorShape>(arg.shape), arg.type,
arg.fast_mem, layout_preference));
TF_RETURN_IF_ERROR(RewriteLayoutWithShardedShape(
arg_sharding, arg.fast_mem, options_.shape_determination_fns,
xla_shape));
return absl::OkStatus();
}
case XlaResource::kTensorArray: {
if (arg.max_array_size < 0) {
return errors::InvalidArgument(
"Negative max_array_size in XLAShapeForArgument");
}
TF_RET_CHECK(absl::holds_alternative<TensorShape>(arg.shape));
TensorShape shape;
TF_RETURN_IF_ERROR(shape.AddDimWithStatus(arg.max_array_size));
shape.AppendShape(std::get<TensorShape>(arg.shape));
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(arg.type, shape, xla_shape));
if (!arg.tensor_array_gradients.empty()) {
std::vector<xla::Shape> tuple_shape(
arg.tensor_array_gradients.size() + 1, *xla_shape);
*xla_shape = xla::ShapeUtil::MakeTupleShape(tuple_shape);
}
return absl::OkStatus();
}
case XlaResource::kStack: {
if (arg.max_array_size < 0) {
return errors::InvalidArgument(
"Negative max_array_size in XLAShapeForArgument");
}
TF_RET_CHECK(absl::holds_alternative<TensorShape>(arg.shape));
TensorShape shape;
TF_RETURN_IF_ERROR(shape.AddDimWithStatus(arg.max_array_size));
shape.AppendShape(std::get<TensorShape>(arg.shape));
xla::Shape buffer_shape;
TF_RETURN_IF_ERROR(
TensorShapeToXLAShape(arg.type, shape, &buffer_shape));
*xla_shape = xla::ShapeUtil::MakeTupleShape(
{buffer_shape, xla::ShapeUtil::MakeShape(xla::S32, {})});
return absl::OkStatus();
}
case XlaResource::kInvalid:
return errors::Internal(
"Invalid resource type in XLAShapeForArgument()");
}
}
case XlaCompiler::Argument::kToken: {
*xla_shape = xla::ShapeUtil::MakeTokenShape();
return absl::OkStatus();
}
case XlaCompiler::Argument::kInvalid:
return errors::Internal("Invalid argument type in XLAShapeForArgument()");
}
}
void XlaCompiler::PopulateArgumentFromResource(const XlaResource& resource,
Argument* arg) {
arg->initialized = resource.initialized();
arg->kind = XlaCompiler::Argument::kResource;
arg->resource_kind = resource.kind();
arg->type = resource.type();
arg->shape = resource.shape();
arg->max_array_size = resource.max_array_size();
for (const auto& gradient : resource.tensor_array_gradients()) {
arg->tensor_array_gradients.insert(gradient.first);
}
arg->name = resource.name();
}
XlaCompiler::SingleOpCompileArgument::SingleOpCompileArgument(
const OpKernelContext& ctx) {
std::vector<DataType> output_dtypes(ctx.num_outputs());
for (int i = 0; i < output_dtypes.size(); ++i) {
output_dtypes[i] = ctx.expected_output_dtype(i);
}
this->output_dtypes = output_dtypes;
this->node_def = ctx.op_kernel().def();
auto* config_proto = ctx.function_library()->config_proto();
if (config_proto != nullptr) {
this->config_proto = *config_proto;
}
}
Status XlaCompiler::BuildArguments(
const Graph& graph, const std::vector<XlaCompiler::Argument>& args,
bool use_tuple_arg, xla::XlaBuilder* builder, XlaContext* context,
const std::map<int, xla::OpSharding>& arg_shardings,
std::vector<XlaExpression>* arg_expressions,
std::vector<int>* input_to_args, std::vector<xla::Shape>* input_shapes,
bool is_entry_computation) {
arg_expressions->resize(args.size());
input_to_args->clear();
input_to_args->reserve(args.size());
for (std::vector<XlaCompiler::Argument>::size_type i = 0; i < args.size();
++i) {
const XlaCompiler::Argument& arg = args[i];
XlaExpression& arg_expression = (*arg_expressions)[i];
switch (arg.kind) {
case XlaCompiler::Argument::kConstantResource:
case XlaCompiler::Argument::kResource: {
TF_RET_CHECK(arg.resource_kind != XlaResource::kInvalid);
TF_RET_CHECK(absl::holds_alternative<TensorShape>(arg.shape));
XlaResource* resource =
context->AddResource(std::make_unique<XlaResource>(
arg.resource_kind, i, arg.name, arg.type,
std::get<TensorShape>(arg.shape), xla::XlaOp(),
arg.max_array_size,
arg.tensor_array_gradients,
true,
arg.definition_stack_trace));
arg_expression =
arg.kind == XlaCompiler::Argument::kResource
? XlaExpression::Resource(resource)
: XlaExpression::ConstantResource(arg.constant_value, resource);
if (arg.initialized) {
input_to_args->push_back(i);
}
break;
}
case XlaCompiler::Argument::kParameter:
case XlaCompiler::Argument::kTensorList:
case XlaCompiler::Argument::kToken: {
input_to_args->push_back(i);
break;
}
case XlaCompiler::Argument::kConstant:
arg_expression = XlaExpression::Constant(arg.constant_value);
break;
case XlaCompiler::Argument::kInvalid:
return errors::Internal(
"Unreachable case in BuildArguments() while filling constant args");
}
}
if (input_to_args->empty() && !use_tuple_arg) {
return absl::OkStatus();
}
std::vector<int> arg_to_inputs(args.size(), -1);
for (int i = 0, end = input_to_args->size(); i < end; i++) {
arg_to_inputs[input_to_args->at(i)] = i;
}
std::vector<xla::Shape> arg_shapes(input_to_args->size());
for (std::vector<int>::size_type i = 0; i < input_to_args->size(); ++i) {
auto arg_sharding = arg_shardings.find((*input_to_args)[i]);
std::optional<xla::HloSharding> sharding;
if (arg_sharding != arg_shardings.end()) {
TF_ASSIGN_OR_RETURN(auto hlo_sharding,
xla::HloSharding::FromProto(arg_sharding->second));
sharding = hlo_sharding;
}
TF_RETURN_IF_ERROR(XLAShapeForArgument(args[(*input_to_args)[i]],
is_entry_computation, sharding,
&arg_shapes[i]));
}
if (use_tuple_arg) {
input_shapes->push_back(xla::ShapeUtil::MakeTupleShape(arg_shapes));
} else {
*input_shapes = arg_shapes;
}
xla::OpMetadata arg_metadata;
arg_metadata.set_op_name("XLA_Args");
builder->SetOpMetadata(arg_metadata);
std::vector<xla::XlaOp> arg_handles(input_to_args->size());
if (use_tuple_arg) {
xla::XlaOp tuple;
if (is_entry_computation) {
xla::OpSharding tuple_sharding;
tuple_sharding.set_type(xla::OpSharding::TUPLE);
for (int64_t parameter : *input_to_args) {
auto it = arg_shardings.find(parameter);
*tuple_sharding.add_tuple_shardings() =
it == arg_shardings.end() ? xla::sharding_builder::AssignDevice(0)
: it->second;
}
std::vector<bool> is_same_across_replicas;
for (int i = 0, end = input_to_args->size(); i < end; ++i) {
is_same_across_replicas.insert(
is_same_across_replicas.end(),
xla::ShapeUtil::GetLeafCount(arg_shapes[i]),
args[input_to_args->at(i)].is_same_data_across_replicas);
}
xla::XlaScopedShardingAssignment assign_tuple_sharding(
builder, input_to_args->empty() ? std::optional<xla::OpSharding>()
: tuple_sharding);
tuple = xla::Parameter(builder, 0, (*input_shapes)[0], "arg_tuple",
is_same_across_replicas);
} else {
tuple = xla::Parameter(builder, 0, (*input_shapes)[0], "arg_tuple");
}
for (std::vector<int>::size_type i = 0; i < input_to_args->size(); ++i) {
auto it = arg_shardings.find(i);
xla::XlaScopedShardingAssignment assign_sharding(
builder, it == arg_shardings.end() ? std::optional<xla::OpSharding>()
: it->second);
auto& arg = args[input_to_args->at(i)];
xla::OpMetadata arg_metadata;
arg_metadata.set_op_name(arg.node_name);
builder->SetOneShotOpMetadata(arg_metadata);
arg_handles[i] = xla::GetTupleElement(tuple, i);
}
} else {
for (std::vector<int>::size_type i = 0; i < input_to_args->size(); ++i) {
auto it = arg_shardings.find(i);
xla::XlaScopedShardingAssignment assign_sharding(
builder, it == arg_shardings.end() ? std::optional<xla::OpSharding>()
: it->second);
if (is_entry_computation) {
std::vector<bool> is_same_across_replicas(
xla::ShapeUtil::GetLeafCount((*input_shapes)[i]),
args[input_to_args->at(i)].is_same_data_across_replicas);
arg_handles[i] =
xla::Parameter(builder, i, (*input_shapes)[i],
absl::StrCat("arg", i), is_same_across_replicas);
} else {
arg_handles[i] = xla::Parameter(builder, i, (*input_shapes)[i],
absl::StrCat("arg", i));
}
}
}
builder->ClearOpMetadata();
VLOG(2) << "XLA computation inputs:";
for (std::vector<int>::size_type i = 0; i < input_to_args->size(); ++i) {
const XlaCompiler::Argument& arg = args[input_to_args->at(i)];
VLOG(2) << " XLA arg " << i
<< " shape: " << xla::ShapeUtil::HumanString(arg_shapes[i])
<< " name: " << arg.name << " TF arg " << input_to_args->at(i)
<< " node name: " << arg.node_name
<< (arg_shardings.find(i) == arg_shardings.end()
? ""
: absl::StrCat(" sharding: ",
arg_shardings.at(i).DebugString()));
XlaExpression& arg_expression = (*arg_expressions)[input_to_args->at(i)];
switch (arg.kind) {
case XlaCompiler::Argument::kConstantResource:
case XlaCompiler::Argument::kResource: {
TF_RET_CHECK(arg.initialized);
XlaResource* resource = arg_expression.resource();
TF_RETURN_IF_ERROR(resource->SetFromPack(arg.tensor_array_gradients,
arg_handles[i], builder));
VLOG(2) << " resource: num_gradients: "
<< arg.tensor_array_gradients.size();
break;
}
case XlaCompiler::Argument::kParameter:
if (is_entry_computation) {
arg_expression = XlaExpression::XlaOp(
xla::Reshape(arg_handles[i], arg.DimensionSizes()), arg.type);
} else {
arg_expression = XlaExpression::XlaOp(arg_handles[i], arg.type);
if (arg.value_bound) {
TF_RET_CHECK(arg.value_dynamism);
arg_expression.set_value_bound(arg.value_bound.value());
arg_expression.set_value_dynamism(arg.value_dynamism.value());
}
}
break;
case XlaCompiler::Argument::kTensorList: {
arg_expression = XlaExpression::TensorList(arg_handles[i]);
break;
}
case XlaCompiler::Argument::kToken: {
arg_expression = XlaExpression::XlaOp(arg_handles[i], arg.type);
break;
}
case XlaCompiler::Argument::kConstant:
case XlaCompiler::Argument::kInvalid:
return errors::Internal(
"Unreachable case in BuildArguments() while filling handles");
}
}
return absl::OkStatus();
}
namespace {
Status ValidateFunctionDef(const FunctionDef* fdef,
const FunctionLibraryDefinition& flib_def) {
for (const NodeDef& node : fdef->node_def()) {
const string& op = node.op();
if (op == FunctionLibraryDefinition::kGradientOp || flib_def.Find(op)) {
continue;
}
const OpDef* op_def;
TF_RETURN_IF_ERROR(OpRegistry::Global()->LookUpOpDef(op, &op_def));
}
return absl::OkStatus();
}
Status GetPotentialFunctionName(const Node& node, const string** name) {
if (node.IsPartitionedCall()) {
const AttrValue* attr_value;
TF_RETURN_IF_ERROR(
node.attrs().Find(FunctionLibraryDefinition::kFuncAttr, &attr_value));
if (!attr_value->has_func()) {
return errors::InvalidArgument(
"The attribute value for attribute 'f' in node ", node.DebugString(),
" does not have 'func' field set");
}
*name = &attr_value->func().name();
return absl::OkStatus();
}
*name = &node.type_string();
return absl::OkStatus();
}
Status ValidateGraph(const Graph* graph,
const FunctionLibraryDefinition& flib_def,
const DeviceType& device_type, const string& name) {
XlaOpRegistry::RegisterCompilationKernels();
auto maybe_error = [&](const Node* node, const Status& s) -> Status {
if (!s.ok()) {
std::string errmsg = absl::StrCat(
"Detected unsupported operations when trying to compile graph ", name,
" on ", device_type.type_string(), ": ", node->def().op(), " (",
s.message(), ")", FormatNodeForError(*node));
if (absl::StrContains(device_type.type_string(), "TPU")) {
absl::StrAppend(&errmsg,
"\nOne approach is to outside compile the unsupported "
"ops to run on CPUs by enabling soft placement "
"`tf.config.set_soft_device_placement(True)`."
" This has a potential performance penalty.\n");
}
if (std::shared_ptr<AbstractStackTrace> stack_trace =
node->GetStackTrace()) {
absl::StrAppend(
&errmsg, "\nThe op is created at: \n",
stack_trace->ToString({true,
true,
true}));
}
return errors::InvalidArgument(errmsg);
}
return absl::OkStatus();
};
for (const Node* node : graph->nodes()) {
if (node->type_string() == FunctionLibraryDefinition::kGradientOp) {
continue;
}
const string* function_name;
TF_RETURN_IF_ERROR(GetPotentialFunctionName(*node, &function_name));
const FunctionDef* fdef = flib_def.Find(*function_name);
Status s;
if (fdef) {
s = ValidateFunctionDef(fdef, flib_def);
TF_RETURN_IF_ERROR(maybe_error(node, s));
continue;
}
const OpDef* op_def;
s = OpRegistry::Global()->LookUpOpDef(node->def().op(), &op_def);
TF_RETURN_IF_ERROR(maybe_error(node, s));
TF_RETURN_IF_ERROR(ValidateNodeDef(node->def(), *op_def));
s = FindKernelDef(device_type, node->def(), nullptr, nullptr);
TF_RETURN_IF_ERROR(maybe_error(node, s));
}
return absl::OkStatus();
}
void ConvertConstantsToExpressions(xla::XlaBuilder* builder,
absl::Span<XlaExpression> expressions) {
for (XlaExpression& expression : expressions) {
if (expression.kind() == XlaExpression::Kind::kConstant) {
expression =
XlaExpression::XlaOp(expression.AsXlaOp(builder), expression.dtype());
}
}
}
}
class DummyStackTrace : public AbstractStackTrace {
absl::Span<StackFrame const> ToFrames() const override { return frames_; }
std::vector<StackFrame> ToUncachedFrames() const override { return frames_; }
StackFrame LastUserFrame() const override { return frames_.back(); }
std::vector<StackFrame> GetUserFrames(int ) const override {
return frames_;
}
std::string ToString(const TracePrintingOptions& opts) const override {
auto frame = LastUserFrame();
return absl::StrCat(frame.file_name, ":", frame.line_number, ":",
frame.function_name);
}
std::vector<StackFrame> frames_{
StackFrame({"dummy_file_name", 10, "dummy_function_name"})};
};
namespace {
void IncreasePrecisionsToAvoidTF32(xla::HloModuleProto& module) {
static constexpr std::array<absl::string_view, 2> kOpsPossiblyUsingTF32 = {
"dot", "convolution"};
xla::PrecisionConfig precision_config;
precision_config.add_operand_precision(xla::PrecisionConfig::HIGHEST);
precision_config.add_operand_precision(xla::PrecisionConfig::HIGHEST);
for (xla::HloComputationProto& computation : *module.mutable_computations()) {
for (xla::HloInstructionProto& instruction :
*computation.mutable_instructions()) {
if (absl::c_find(kOpsPossiblyUsingTF32, instruction.opcode()) !=
kOpsPossiblyUsingTF32.end()) {
*instruction.mutable_precision_config() = precision_config;
}
}
}
}
}
Status XlaCompiler::CompileGraph(const XlaCompiler::CompileOptions& options,
string const& name,
std::unique_ptr<Graph> graph,
absl::Span<const XlaCompiler::Argument> args,
CompilationResult* result) {
VLOG(1) << "Executing graph symbolically to populate XlaBuilder.: " << name;
if (VLOG_IS_ON(2) || DEBUG_DATA_DUMPER()->ShouldDump(name, kDebugGroupMain)) {
VLOG(2) << "XlaCompiler::CompileGraph: "
<< DumpGraphToFile(absl::StrCat("xla_compile_graph_", name), *graph,
flib_runtime_->GetFunctionLibraryDefinition());
}
DummyStackTrace stack_trace;
for (auto node : graph->nodes()) {
if (node->GetStackTrace() == nullptr) {
node->SetStackTrace(std::make_shared<DummyStackTrace>(stack_trace));
}
}
TF_RETURN_IF_ERROR(PropagateConstIntoFunctionalNodes(
graph.get(), options_.flib_def, local_flib_def_.get()));
TF_RETURN_IF_ERROR(RearrangeFunctionArguments(
[this](const NameAttrList& function, const FunctionBody** fbody) {
return FindFunctionBody(function, fbody);
},
graph.get(), local_flib_def_.get(),
pflr_->GetFunctionLibraryDefinition()));
TF_RETURN_IF_ERROR(initialization_status_);
TF_RETURN_IF_ERROR(ValidateGraph(graph.get(), *options_.flib_def,
options_.device_type, name));
auto builder = std::make_unique<xla::XlaBuilder>(name);
XlaContext* context = new XlaContext(this, builder.get(), graph.get());
core::ScopedUnref context_unref(context);
std::vector<XlaCompiler::Argument> real_args(args.begin(), args.end());
int token_input_index = -1;
std::unique_ptr<xla::XlaOp> token_output;
if (options.add_token_input_output) {
token_input_index = real_args.size();
XlaCompiler::Argument token_arg;
token_arg.kind = XlaCompiler::Argument::kToken;
real_args.push_back(token_arg);
}
std::map<int, xla::OpSharding> arg_shardings;
std::map<int, xla::OpSharding> retval_shardings;
TF_ASSIGN_OR_RETURN(std::tie(arg_shardings, retval_shardings),
ComputeArgAndRetvalShardings(*graph));
std::vector<XlaExpression> arg_expressions;
TF_RETURN_IF_ERROR(BuildArguments(
*graph, real_args, options.use_tuple_arg, builder.get(), context,
arg_shardings, &arg_expressions, &result->input_mapping,
&result->xla_input_shapes, options.is_entry_computation));
context->set_args(std::move(arg_expressions));
PushNodeTokenMapping();
std::set<std::string> output_node_token_inputs;
if (token_input_index != -1) {
auto arg_expression = context->args()[token_input_index];
TF_RETURN_IF_ERROR(
SetNodeToken(kXlaTokenArgNodeName, arg_expression.handle()));
output_node_token_inputs = CalculateTokenInputsForOutputToken(*graph);
if (output_node_token_inputs.empty()) {
output_node_token_inputs.insert(kXlaTokenArgNodeName);
}
} else if (options.is_entry_computation) {
if (HasSideEffectingNodes(*graph)) {
TF_RETURN_IF_ERROR(
SetNodeToken(kXlaTokenArgNodeName, xla::CreateToken(builder.get())));
}
}
Status execute_status = ExecuteGraph(context, std::move(graph), device_,
flib_runtime_, NextStepId());
if (!execute_status.ok()) {
VLOG(1) << "Failed executing graph " << name;
return execute_status;
}
if (token_input_index != -1) {
std::vector<xla::XlaOp> token_inputs;
for (const auto& node_name : output_node_token_inputs) {
auto token_or = GetNodeToken(node_name);
TF_RETURN_IF_ERROR(token_or.status());
token_inputs.push_back(token_or.value());
}
token_output = std::make_unique<xla::XlaOp>(
xla::AfterAll(builder.get(), token_inputs));
}
TF_RETURN_IF_ERROR(PopNodeTokenMapping());
int num_nonconst_outputs;
int num_computation_outputs;
result->computation = std::make_shared<xla::XlaComputation>();
result->outputs.resize(context->retvals().size());
std::vector<XlaExpression> retvals = context->retvals();
ConvertConstantsToExpressions(builder.get(),
absl::Span<XlaExpression>(retvals));
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns{
UseNoPreferenceLayoutFn(), IdentityShapeRepresentationFn()};
TF_RETURN_IF_ERROR(BuildComputation(
real_args, retvals, arg_shardings, retval_shardings, context->resources(),
std::move(token_output),
options.is_entry_computation ? options_.shape_determination_fns
: shape_determination_fns,
options.is_entry_computation,
options.return_updated_values_for_all_resources,
options.always_return_tuple, options.use_tuple_arg,
options.alias_resource_update, builder.get(), result->computation.get(),
&num_computation_outputs, &num_nonconst_outputs, &result->outputs,
&result->resource_updates, &result->xla_output_shape,
result->input_mapping));
for (const auto& [key, send] : host_compute_sends_) {
auto* d2h = result->host_compute_metadata.add_device_to_host();
*d2h = send;
for (int i = 0; i < d2h->metadata_size(); ++i) {
const std::string channel_name =
GetDeviceToHostChannelName(d2h->key(), i);
xla::ChannelHandle handle;
TF_RETURN_IF_ERROR(GetDeviceToHostChannelHandle(channel_name, &handle));
d2h->mutable_metadata(i)->set_channel_id(handle.handle());
}
}
for (const auto& [key, recv] : host_compute_recvs_) {
auto* h2d = result->host_compute_metadata.add_host_to_device();
*h2d = recv;
for (int i = 0; i < h2d->metadata_size(); ++i) {
const std::string channel_name =
GetHostToDeviceChannelName(h2d->key(), i);
xla::ChannelHandle handle;
TF_RETURN_IF_ERROR(GetHostToDeviceChannelHandle(channel_name, &handle));
h2d->mutable_metadata(i)->set_channel_id(handle.handle());
}
}
if (!tsl::tensor_float_32_execution_enabled()) {
IncreasePrecisionsToAvoidTF32(*result->computation->mutable_proto());
}
VLOG(2) << "Outputs: total: " << context->retvals().size()
<< " nonconstant: " << num_nonconst_outputs;
VLOG(2) << "XLA output shape: "
<< xla::ShapeUtil::HumanStringWithLayout(result->xla_output_shape);
result->collective_info = context->GetCollectiveInfo();
return absl::OkStatus();
}
Status XlaCompiler::GetChannelHandle(const string& key,
xla::ChannelHandle* channel) {
auto result = channels_.emplace(key, xla::ChannelHandle());
if (result.second) {
TF_ASSIGN_OR_RETURN(result.first->second, client()->CreateChannelHandle());
}
*channel = result.first->second;
VLOG(1) << "Channel: " << key << " " << channel->DebugString();
return absl::OkStatus();
}
Status XlaCompiler::GetHostToDeviceChannelHandle(const string& key,
xla::ChannelHandle* channel) {
auto result = channels_.emplace(key, xla::ChannelHandle());
if (result.second) {
TF_ASSIGN_OR_RETURN(result.first->second,
client()->CreateHostToDeviceChannelHandle());
}
*channel = result.first->second;
VLOG(1) << "Host to device channel: " << key << " " << channel->DebugString();
return absl::OkStatus();
}
Status XlaCompiler::GetDeviceToHostChannelHandle(const string& key,
xla::ChannelHandle* channel) {
auto result = channels_.emplace(key, xla::ChannelHandle());
if (result.second) {
TF_ASSIGN_OR_RETURN(result.first->second,
client()->CreateDeviceToHostChannelHandle());
}
*channel = result.first->second;
VLOG(1) << "Device to host channel: " << key << " " << channel->DebugString();
return absl::OkStatus();
}
namespace {
void SetTransfer(const string& key, absl::Span<const DataType> types,
absl::Span<const TensorShape> shapes,
tf2xla::HostTransferMetadata* transfer) {
transfer->set_key(key);
CHECK(types.size() == shapes.size());
for (int i = 0, end = types.size(); i < end; ++i) {
tf2xla::TensorMetadata* metadata = transfer->add_metadata();
metadata->set_type(types[i]);
shapes[i].AsProto(metadata->mutable_shape());
}
}
}
Status XlaCompiler::SetDeviceToHostMetadata(
const string& key, absl::Span<const DataType> types,
absl::Span<const TensorShape> shapes) {
if (host_compute_sends_.find(key) != host_compute_sends_.end()) {
tf2xla::HostTransferMetadata& existing_transfer = host_compute_sends_[key];
tf2xla::HostTransferMetadata new_transfer;
SetTransfer(key, types, shapes, &new_transfer);
if (xla::protobuf_util::ProtobufEquals(existing_transfer, new_transfer)) {
return absl::OkStatus();
} else {
return errors::InvalidArgument(
"Duplicate calls to SetDeviceToHostMetadata with key ", key);
}
}
tf2xla::HostTransferMetadata& transfer = host_compute_sends_[key];
SetTransfer(key, types, shapes, &transfer);
return absl::OkStatus();
}
Status XlaCompiler::GetDeviceToHostShapes(
const string& key, std::vector<TensorShape>* shapes) const {
const auto iter = host_compute_sends_.find(key);
if (iter == host_compute_sends_.end()) {
return errors::InvalidArgument(
"No host compute send shapes registered for key ", key);
}
shapes->clear();
for (int i = 0; i < iter->second.metadata_size(); ++i) {
TensorShape shape(iter->second.metadata(i).shape());
shapes->push_back(shape);
}
return absl::OkStatus();
}
Status XlaCompiler::SetHostToDeviceMetadata(
const string& key, absl::Span<const DataType> types,
absl::Span<const TensorShape> shapes) {
if (host_compute_recvs_.find(key) != host_compute_recvs_.end()) {
tf2xla::HostTransferMetadata& existing_transfer = host_compute_recvs_[key];
tf2xla::HostTransferMetadata new_transfer;
SetTransfer(key, types, shapes, &new_transfer);
if (xla::protobuf_util::ProtobufEquals(existing_transfer, new_transfer)) {
return absl::OkStatus();
} else {
return errors::InvalidArgument(
"Duplicate calls to SetHostToDeviceMetadata with key ", key);
}
}
tf2xla::HostTransferMetadata& transfer = host_compute_recvs_[key];
SetTransfer(key, types, shapes, &transfer);
return absl::OkStatus();
}
Status XlaCompiler::GetHostComputeControlDependency(
const string& host_compute_name, xla::XlaOp* handle) {
const auto iter = host_compute_control_output_.find(host_compute_name);
if (iter == host_compute_control_output_.end()) {
return errors::InvalidArgument(
"No registered control handle for host compute Op '", host_compute_name,
"'");
} else {
*handle = iter->second;
}
return absl::OkStatus();
}
Status XlaCompiler::SetHostComputeControlDependency(
const string& host_compute_name, const xla::XlaOp handle) {
if (host_compute_control_output_.find(host_compute_name) !=
host_compute_control_output_.end()) {
return errors::InvalidArgument(
"Duplicate control handles registered for host compute Op ",
host_compute_name);
}
host_compute_control_output_[host_compute_name] = handle;
return absl::OkStatus();
}
void XlaCompiler::PushNodeTokenMapping() {
node_token_mapping_stack_.emplace(std::map<string, xla::XlaOp>{});
}
Status XlaCompiler::PopNodeTokenMapping() {
if (node_token_mapping_stack_.empty()) {
return errors::FailedPrecondition(
"Calling PopNodeTokenMapping() when node_token_mapping_stack_ is "
"empty.");
}
node_token_mapping_stack_.pop();
return absl::OkStatus();
}
Status XlaCompiler::SetNodeToken(const string& node_name, const xla::XlaOp op) {
if (node_token_mapping_stack_.empty()) {
return errors::FailedPrecondition(
"Calling SetNodeToken() when node_token_mapping_stack_ is "
"empty.");
}
auto insert_result = node_token_mapping_stack_.top().insert({node_name, op});
if (!insert_result.second) {
return errors::FailedPrecondition("Token mapping already exists for node ",
node_name);
}
return absl::OkStatus();
}
absl::StatusOr<xla::XlaOp> XlaCompiler::GetNodeToken(const string& node_name) {
if (node_token_mapping_stack_.empty()) {
return errors::FailedPrecondition(
"Calling GetNodeToken() when node_token_mapping_stack_ is "
"empty.");
}
auto iter = node_token_mapping_stack_.top().find(node_name);
if (iter == node_token_mapping_stack_.top().end()) {
return errors::FailedPrecondition("Cannot find token mapping for node ",
node_name);
}
return iter->second;
}
} | #include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "absl/strings/match.h"
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/data_flow_ops.h"
#include "tensorflow/cc/ops/function_ops.h"
#include "tensorflow/cc/ops/functional_ops.h"
#include "tensorflow/cc/ops/list_ops.h"
#include "tensorflow/cc/ops/math_ops.h"
#include "tensorflow/cc/ops/resource_variable_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/side_effect_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "xla/client/client_library.h"
#include "xla/client/local_client.h"
#include "xla/hlo/builder/xla_builder.h"
#include "xla/literal.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_proto_util.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/tests/literal_test_util.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/framework/graph_to_functiondef.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/version.h"
#include "tsl/platform/statusor.h"
namespace tensorflow {
class XlaCompilerTest : public ::testing::Test {
protected:
void SetUp() override {
client_ = xla::ClientLibrary::LocalClientOrDie();
XlaOpRegistry::RegisterCompilationKernels();
FunctionDefLibrary flib;
flib_def_.reset(new FunctionLibraryDefinition(OpRegistry::Global(), flib));
}
XlaCompiler::Options DefaultOptions() {
XlaCompiler::Options options;
options.device_type = DeviceType(DEVICE_CPU_XLA_JIT);
options.client = client_;
options.flib_def = flib_def_.get();
return options;
}
FunctionLibraryDefinition* LocalFlibDef(XlaCompiler* compiler) {
return compiler->local_flib_def_.get();
}
xla::Client* client_;
std::unique_ptr<FunctionLibraryDefinition> flib_def_;
};
namespace {
class DummyResourceForTest : public ResourceBase {
public:
string DebugString() const override { return "dummy"; }
void Increment() { ++value_; }
int Get() { return value_; }
private:
int value_ = 0;
};
class DummyReadResourceOp : public XlaOpKernel {
public:
explicit DummyReadResourceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
ResourceMgr* rm = ctx->op_kernel_context()->resource_manager();
OP_REQUIRES(ctx, rm, errors::Internal("No resource manager."));
DummyResourceForTest* dummy;
OP_REQUIRES_OK(ctx, rm->Lookup<DummyResourceForTest>(
rm->default_container(), "dummy", &dummy));
dummy->Increment();
dummy->Unref();
ctx->SetOutput(0, ctx->Input(0));
ctx->SetOutput(1, ctx->Input(0));
}
};
class DummyReadResourceCC {
public:
DummyReadResourceCC(const Scope& scope, const Input& value) {
if (!scope.ok()) return;
auto _value = ops::AsNodeOut(scope, value);
if (!scope.ok()) return;
Node* ret;
const auto unique_name = scope.GetUniqueNameForOp("DummyReadResource");
auto builder = NodeBuilder(unique_name, "DummyReadResource").Input(_value);
scope.UpdateBuilder(&builder);
scope.UpdateStatus(builder.Finalize(scope.graph(), &ret));
if (!scope.ok()) return;
scope.UpdateStatus(scope.DoShapeInference(ret));
if (!scope.ok()) return;
this->output1_ = Output(ret, 0);
this->output2_ = Output(ret, 1);
}
Output output1_;
Output output2_;
};
REGISTER_OP("DummyReadResource")
.Input("input: int32")
.Output("output1: int32")
.Output("output2: int32")
.SetShapeFn(shape_inference::UnknownShape)
.Doc(R"doc(
A dummy Op.
input: dummy input.
output1: dummy output.
output2: dummy output.
)doc");
REGISTER_XLA_OP(Name("DummyReadResource"), DummyReadResourceOp);
class DummyDuplicateOp : public XlaOpKernel {
public:
explicit DummyDuplicateOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
ctx->SetOutput(0, ctx->Input(0));
}
};
REGISTER_OP("DummyDuplicateOp")
.Input("input: int32")
.Output("output: int32")
.Doc(R"doc(
A dummy Op.
input: dummy input.
output: dummy output.
)doc");
REGISTER_XLA_OP(Name("DummyDuplicateOp").Device(DEVICE_CPU_XLA_JIT),
DummyDuplicateOp);
REGISTER_XLA_OP(Name("DummyDuplicateOp").Device(DEVICE_GPU_XLA_JIT),
DummyDuplicateOp);
TEST_F(XlaCompilerTest, EmptyReturnValues) {
XlaCompiler compiler(DefaultOptions());
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph),
{}, &result));
TF_ASSERT_OK(client_->Execute(*result.computation, {}).status());
}
TEST_F(XlaCompilerTest, Simple) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1);
auto c = ops::Add(scope.WithOpName("C"), a, b);
auto d = ops::_Retval(scope.WithOpName("D"), c, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
args[1].kind = XlaCompiler::Argument::kParameter;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42});
xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101});
std::unique_ptr<xla::GlobalData> param0_data =
client_->TransferToServer(param0_literal).value();
std::unique_ptr<xla::GlobalData> param1_data =
client_->TransferToServer(param1_literal).value();
std::unique_ptr<xla::GlobalData> actual =
client_
->Execute(*result.computation, {param0_data.get(), param1_data.get()})
.value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
xla::Literal expected0 = xla::LiteralUtil::CreateR1<int32>({4, 143});
xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
absl::StatusOr<std::unique_ptr<xla::HloModule>> LoadModuleFromHloProto(
const xla::HloModuleProto& module_proto) {
TF_ASSIGN_OR_RETURN(auto module_config,
xla::HloModule::CreateModuleConfigFromProto(
module_proto, xla::GetDebugOptionsFromFlags()));
return xla::CreateModuleFromProto(module_proto, module_config);
}
TEST_F(XlaCompilerTest, SimpleDynamicShapeParameter) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1);
auto c = ops::Add(scope.WithOpName("C"), a, b);
auto d = ops::_Retval(scope.WithOpName("D"), c, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape =
xla::ShapeUtil::MakeShape(xla::S32, {2},
{true});
args[1].kind = XlaCompiler::Argument::kParameter;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
auto hlo = result.computation->proto();
TF_ASSERT_OK_AND_ASSIGN(auto module, LoadModuleFromHloProto(hlo));
EXPECT_EQ(module->computation_count(), 1);
EXPECT_TRUE(module->mutable_computation(0)
->parameter_instruction(0)
->shape()
.is_dynamic());
}
TEST_F(XlaCompilerTest, OutOfOrderGraph) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1);
auto d = ops::_Retval(scope.WithOpName("D"), a, 0);
auto c = ops::Add(scope.WithOpName("C"), a, b);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
args[1].kind = XlaCompiler::Argument::kParameter;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompileOptions compile_options;
compile_options.always_return_tuple = false;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph),
args, &result));
xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42});
xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101});
std::unique_ptr<xla::GlobalData> param0_data =
client_->TransferToServer(param0_literal).value();
std::unique_ptr<xla::GlobalData> param1_data =
client_->TransferToServer(param1_literal).value();
std::unique_ptr<xla::GlobalData> actual =
client_
->Execute(*result.computation, {param0_data.get(), param1_data.get()})
.value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
EXPECT_TRUE(xla::LiteralTestUtil::Equal(param0_literal, actual_literal));
}
TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForUnwrittenResource) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0);
auto d = ops::_Retval(scope.WithOpName("D"), var, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kResource;
args[0].resource_kind = XlaResource::kVariable;
args[0].initialized = true;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 3});
auto options = DefaultOptions();
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns;
shape_determination_fns.shape_representation_fn =
[](const TensorShape& shape, DataType dt, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> absl::StatusOr<xla::Shape> {
xla::Shape xla_shape;
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape));
*xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1});
return xla_shape;
};
options.shape_determination_fns = shape_determination_fns;
XlaCompiler compiler(options);
XlaCompiler::CompilationResult result;
XlaCompiler::CompileOptions compile_options;
compile_options.return_updated_values_for_all_resources = true;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph),
args, &result));
xla::Shape transposed =
xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1});
EXPECT_EQ(result.xla_output_shape,
xla::ShapeUtil::MakeTupleShape({transposed}));
}
TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForFastMemVar) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0);
auto d = ops::_Retval(scope.WithOpName("D"), var, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kResource;
args[0].resource_kind = XlaResource::kVariable;
args[0].initialized = true;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 3});
args[0].fast_mem = true;
auto options = DefaultOptions();
int fast_mem_arg_count = 0;
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns;
shape_determination_fns.shape_representation_fn =
[&fast_mem_arg_count](
const TensorShape& shape, DataType dt, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> absl::StatusOr<xla::Shape> {
xla::Shape xla_shape;
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape));
*xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1});
if (use_fast_memory) {
fast_mem_arg_count++;
}
return xla_shape;
};
options.shape_determination_fns = shape_determination_fns;
XlaCompiler compiler(options);
XlaCompiler::CompilationResult result;
XlaCompiler::CompileOptions compile_options;
compile_options.return_updated_values_for_all_resources = true;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph),
args, &result));
EXPECT_EQ(fast_mem_arg_count, 2);
}
TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForRetVal) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1);
auto identity = ops::Identity(scope.WithOpName("VIdentity"), var);
auto write = ops::AssignAddVariableOp(scope, identity, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1));
auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 3});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2, 3});
auto options = DefaultOptions();
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns;
shape_determination_fns.shape_representation_fn =
[](const TensorShape& shape, DataType dt, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> absl::StatusOr<xla::Shape> {
xla::Shape xla_shape;
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape));
*xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1});
return xla_shape;
};
options.shape_determination_fns = shape_determination_fns;
XlaCompiler compiler(options);
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
xla::Shape transposed =
xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1});
EXPECT_EQ(result.xla_output_shape,
xla::ShapeUtil::MakeTupleShape({transposed, transposed}));
EXPECT_EQ(result.computation->GetProgramShape().value().result(),
xla::ShapeUtil::MakeTupleShape({transposed, transposed}));
}
TEST_F(XlaCompilerTest, TransposeVariables) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1);
auto identity = ops::Identity(scope.WithOpName("VIdentity"), var);
auto write = ops::AssignAddVariableOp(scope, identity, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
auto transposed_read = ops::Transpose(scope, read, {1, 0});
auto reshape = ops::Reshape(scope, transposed_read, {2, 3});
auto d = ops::_Retval(scope.WithOpName("D"), reshape, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 3});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2, 3});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "transpose",
std::move(graph), args, &result));
xla::Shape transposed =
xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {1, 0});
EXPECT_EQ(result.xla_output_shape,
xla::ShapeUtil::MakeTupleShape({transposed, transposed}));
}
TEST_F(XlaCompilerTest, UnrankedFakeParam) {
Scope scope = Scope::NewRootScope().ExitOnError();
PartialTensorShape shape;
auto a = ops::FakeParam(scope, DT_INT32, shape);
auto ret = ops::_Retval(scope.WithOpName("D"), a, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "compile",
std::move(graph), {}, &result));
EXPECT_EQ(result.xla_output_shape,
xla::ShapeUtil::MakeTupleShape(
{xla::ShapeUtil::MakeShape(xla::S32, {0})}));
}
TEST_F(XlaCompilerTest, MixedOrderArguments) {
for (bool swap_order : {false, true}) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto var =
ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, swap_order ? 0 : 1);
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, swap_order ? 1 : 0);
auto identity = ops::Identity(scope.WithOpName("VIdentity"), var);
auto write = ops::AssignAddVariableOp(scope, identity, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1));
auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
if (swap_order) {
std::swap(args[0], args[1]);
}
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompileOptions compile_options;
compile_options.always_return_tuple = false;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph),
args, &result));
EXPECT_THAT(result.input_mapping, ::testing::ElementsAre(0, 1));
}
}
TEST_F(XlaCompilerTest, HasSaneErrorOnNonCompileTimeConstantInputToReshape) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1);
auto c = ops::Reshape(scope.WithOpName("C"), a, b);
auto d = ops::_Retval(scope.WithOpName("D"), c, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
args[1].kind = XlaCompiler::Argument::kParameter;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
Status status =
compiler.CompileGraph(XlaCompiler::CompileOptions(), "reshape",
std::move(graph), args, &result);
EXPECT_FALSE(status.ok());
EXPECT_TRUE(absl::StrContains(status.message(), "depends on a parameter"))
<< status.message();
EXPECT_TRUE(absl::StrContains(status.message(), "{{node C}}"))
<< status.message();
EXPECT_TRUE(
absl::StrContains(status.message(), "must be a compile-time constant"))
<< status.message();
}
TEST_F(XlaCompilerTest, ConstantOutputs) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::Const<int32>(scope.WithOpName("B"), 7);
auto c = ops::Neg(scope.WithOpName("C"), a);
auto d = ops::_Retval(scope.WithOpName("D"), b, 0);
auto e = ops::_Retval(scope.WithOpName("E"), c, 1);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
XlaCompiler::Options options = DefaultOptions();
XlaCompiler compiler(options);
{
std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global()));
CopyGraph(*graph, graph_copy.get());
XlaCompiler::CompileOptions compile_options;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "constants",
std::move(graph_copy), args, &result));
ASSERT_EQ(2, result.outputs.size());
EXPECT_FALSE(result.outputs[0].is_constant);
EXPECT_FALSE(result.outputs[1].is_constant);
xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42});
std::unique_ptr<xla::GlobalData> param0_data =
client_->TransferToServer(param0_literal).value();
std::unique_ptr<xla::GlobalData> actual =
client_->Execute(*result.computation, {param0_data.get()}).value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
xla::Literal expected0 = xla::LiteralUtil::CreateR0<int32>(7);
xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({-7, -42});
xla::Literal expected =
xla::LiteralUtil::MakeTuple({&expected0, &expected1});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected, actual_literal));
}
}
TEST_F(XlaCompilerTest, ConstantOutputsOfFunctionalNode) {
const Tensor seven = test::AsScalar<int>(7);
FunctionDef fdef = FunctionDefHelper::Create(
"foo", {"a_0:int32"}, {"const:int32", "a:int32"}, {},
{
{{"Const"}, "Const", {}, {{"dtype", DT_INT32}, {"value", seven}}},
},
{{"a", "a_0"}, {"const", "Const:output:0"}});
(*fdef.mutable_attr())["_noinline"].set_b(true);
FunctionDefLibrary fdef_lib;
*(fdef_lib.add_function()) = fdef;
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
{
Scope scope = Scope::NewRootScope().ExitOnError();
TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(fdef_lib));
auto arg = ops::_Arg(scope.WithOpName("input_arg"), DT_INT32, 0);
NodeDef foo;
foo.set_name("foo");
foo.set_op("foo");
*foo.add_input() = "input_arg";
Status status;
scope.graph()->AddNode(foo, &status);
TF_ASSERT_OK(status);
NodeDef retval_1;
retval_1.set_name("retval_0");
retval_1.set_op(FunctionLibraryDefinition::kRetOp);
*retval_1.add_input() = "foo";
(*retval_1.mutable_attr())["T"].set_type(DT_INT32);
(*retval_1.mutable_attr())["index"].set_i(0);
scope.graph()->AddNode(retval_1, &status);
TF_ASSERT_OK(status);
NodeDef retval_2;
retval_2.set_name("retval_1");
retval_2.set_op(FunctionLibraryDefinition::kRetOp);
*retval_2.add_input() = "foo:1";
(*retval_2.mutable_attr())["T"].set_type(DT_INT32);
(*retval_2.mutable_attr())["index"].set_i(1);
scope.graph()->AddNode(retval_2, &status);
TF_ASSERT_OK(status);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
}
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({1});
XlaCompiler::Options options = DefaultOptions();
FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib);
options.flib_def = &flib_def;
XlaCompiler compiler(options);
XlaCompiler::CompileOptions compile_options;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "constants",
std::move(graph), args, &result));
ASSERT_EQ(2, result.outputs.size());
EXPECT_FALSE(result.outputs[1].is_constant);
}
TEST_F(XlaCompilerTest, ResourceManager) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = DummyReadResourceCC(scope.WithOpName("B"), a);
auto c = ops::Add(scope.WithOpName("C"), b.output2_, b.output1_);
auto d = ops::_Retval(scope.WithOpName("D"), c, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
DummyResourceForTest* resource = new DummyResourceForTest();
auto options = DefaultOptions();
std::function<Status(ResourceMgr*)> populate_function =
[resource](ResourceMgr* rm) {
resource->Ref();
return rm->Create(rm->default_container(), "dummy", resource);
};
options.populate_resource_manager = &populate_function;
XlaCompiler compiler(options);
EXPECT_EQ(0, resource->Get());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "dummy",
std::move(graph), args, &result));
EXPECT_EQ(1, resource->Get());
resource->Unref();
}
TEST_F(XlaCompilerTest, DeterministicCompilation) {
const int64_t test_count = 2;
std::vector<XlaCompiler::CompilationResult> results(test_count);
for (int64_t i = 0; i < test_count; ++i) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::Neg(scope.WithOpName("B"), a);
auto c = ops::Neg(scope.WithOpName("C"), a);
auto d = ops::Add(scope.WithOpName("D"), b, c);
auto e = ops::_Retval(scope.WithOpName("E"), d, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
auto options = DefaultOptions();
XlaCompiler compiler(options);
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "dummy",
std::move(graph), args, &results[i]));
}
for (int64_t i = 1; i < test_count; ++i) {
const auto& m1 = results[i - 1].computation->proto();
const auto& m2 = results[i].computation->proto();
ASSERT_EQ(m1.computations_size(), m2.computations_size());
for (int k = 0; k < m1.computations_size(); k++) {
const auto& c1 = m1.computations(k);
const auto& c2 = m2.computations(k);
ASSERT_EQ(c1.instructions_size(), c2.instructions_size());
for (int j = 0; j < c1.instructions_size(); j++) {
auto instr1 = c1.instructions(j);
auto instr2 = c2.instructions(j);
instr1.clear_name();
instr1.clear_id();
instr1.clear_operand_ids();
instr2.clear_name();
instr2.clear_id();
instr2.clear_operand_ids();
string str1, str2;
LOG(INFO) << "instr1 = " << instr1.DebugString();
LOG(INFO) << "instr2 = " << instr2.DebugString();
instr1.AppendPartialToString(&str1);
instr2.AppendPartialToString(&str2);
EXPECT_EQ(str1, str2);
}
}
}
}
TEST_F(XlaCompilerTest, CanPassTensorArraysToAndFromComputation) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0);
auto flow = ops::Const<float>(scope, {});
auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad1");
auto grad2 = ops::TensorArrayGrad(scope, arg, grad1.flow_out, "grad2");
auto index = ops::Const<int32>(scope, 1);
auto write = ops::TensorArrayWrite(scope, grad1.grad_handle, index, index,
grad2.flow_out);
auto read = ops::TensorArrayRead(scope, arg, index, write.flow_out, DT_INT32);
auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kResource;
args[0].resource_kind = XlaResource::kTensorArray;
args[0].initialized = true;
args[0].type = DT_INT32;
args[0].shape = TensorShape({});
args[0].max_array_size = 2;
args[0].tensor_array_gradients = {"grad2"};
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
ASSERT_EQ(1, result.resource_updates.size());
const XlaCompiler::ResourceUpdate& update = result.resource_updates[0];
EXPECT_EQ(0, update.input_index);
EXPECT_EQ(DT_INT32, update.type);
EXPECT_EQ((std::set<string>{"grad1", "grad2"}),
update.tensor_array_gradients_accessed);
xla::Literal input_base = xla::LiteralUtil::CreateR1<int32>({7, 42});
xla::Literal input_grad2 = xla::LiteralUtil::CreateR1<int32>({-3, 101});
xla::Literal input = xla::LiteralUtil::MakeTuple({&input_base, &input_grad2});
std::unique_ptr<xla::GlobalData> param0_data =
client_->TransferToServer(input).value();
std::unique_ptr<xla::GlobalData> actual =
client_->Execute(*result.computation, {param0_data.get()}).value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
xla::Literal output_read = xla::LiteralUtil::CreateR0<int32>(42);
xla::Literal output_base = xla::LiteralUtil::CreateR1<int32>({7, 42});
xla::Literal output_grad1 = xla::LiteralUtil::CreateR1<int32>({0, 1});
xla::Literal output_grad2 = xla::LiteralUtil::CreateR1<int32>({-3, 101});
xla::Literal output_resource =
xla::LiteralUtil::MakeTuple({&output_base, &output_grad1, &output_grad2});
xla::Literal expected_literal =
xla::LiteralUtil::MakeTuple({&output_read, &output_resource});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
TEST_F(XlaCompilerTest, UnwrittenTensorArrayGradientsAreNotComputationOutputs) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0);
auto flow = ops::Const<float>(scope, {});
auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad1");
auto index = ops::Const<int32>(scope, 1);
auto read = ops::TensorArrayRead(scope, arg, index, grad1.flow_out, DT_INT32);
auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kResource;
args[0].resource_kind = XlaResource::kTensorArray;
args[0].initialized = true;
args[0].type = DT_INT32;
args[0].shape = TensorShape({});
args[0].max_array_size = 2;
args[0].tensor_array_gradients = {"grad1"};
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
EXPECT_EQ(0, result.resource_updates.size());
}
TEST_F(XlaCompilerTest, NewTensorArrayGradientsAreComputationOutputs) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0);
auto flow = ops::Const<float>(scope, {});
auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad2");
auto index = ops::Const<int32>(scope, 1);
auto read = ops::TensorArrayRead(scope, arg, index, grad1.flow_out, DT_INT32);
auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kResource;
args[0].resource_kind = XlaResource::kTensorArray;
args[0].initialized = true;
args[0].type = DT_INT32;
args[0].shape = TensorShape({});
args[0].max_array_size = 2;
args[0].tensor_array_gradients = {"grad1"};
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
EXPECT_EQ(1, result.resource_updates.size());
}
TEST_F(XlaCompilerTest, UndefinedFunctionFails) {
XlaCompiler compiler(DefaultOptions());
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
XlaCompiler::CompilationResult result;
NameAttrList name_attr;
name_attr.set_name("Function_NotDefined_");
Status status =
compiler.CompileFunction(XlaCompiler::CompileOptions(), name_attr,
{}, &result);
EXPECT_FALSE(status.ok());
EXPECT_TRUE(absl::StrContains(status.message(), "is not defined."))
<< status.message();
}
FunctionDef FillFn() {
return FunctionDefHelper::Define(
"FillFn",
{"x: T", "dims: int32"},
{"y: T"},
{"T: {float, double, int32, int64}"},
{{{"y"}, "Fill", {"dims", "x"}, {{"T", "$T"}}}});
}
TEST_F(XlaCompilerTest, FunctionCallWithConstants) {
XlaCompiler compiler(DefaultOptions());
FunctionDefLibrary flib;
*flib.add_function() = FillFn();
TF_ASSERT_OK(flib_def_->AddFunctionDef(FillFn()));
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
Scope scope = Scope::NewRootScope().ExitOnError();
auto value = ops::Const<int32>(scope.WithOpName("value"), 1, {});
auto shape = ops::Const<int32>(scope.WithOpName("shape"), {5}, {1});
TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(flib));
NodeDef def;
TF_ASSERT_OK(NodeDefBuilder("fill", "FillFn", flib_def_.get())
.Input(value.name(), 0, DT_INT32)
.Input(shape.name(), 1, DT_INT32)
.Finalize(&def));
Status status;
Node* fill = scope.graph()->AddNode(def, &status);
TF_ASSERT_OK(status);
TF_ASSERT_OK(scope.DoShapeInference(fill));
scope.graph()->AddEdge(value.node(), 0, fill, 0);
scope.graph()->AddEdge(shape.node(), 0, fill, 1);
auto retval = ops::_Retval(scope.WithOpName("retval"), Output(fill), 0);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "fill",
std::move(graph), args, &result));
}
TEST_F(XlaCompilerTest, LocalFunctionWithWrongArgumentsFail) {
XlaCompiler compiler(DefaultOptions());
auto local_flib_def = LocalFlibDef(&compiler);
TF_ASSERT_OK(local_flib_def->AddFunctionDef(test::function::XTimesTwo()));
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
XlaCompiler::CompilationResult result;
NameAttrList name_attr;
name_attr.set_name("XTimesTwo");
Status status =
compiler.CompileFunction(XlaCompiler::CompileOptions(), name_attr,
{}, &result);
ASSERT_FALSE(status.ok());
EXPECT_TRUE(absl::StrContains(status.message(), "is not defined."))
<< status.message();
EXPECT_TRUE(absl::StrContains(status.message(), "Attr T is not found"))
<< status.message();
}
FunctionDef SliceFn() {
return FunctionDefHelper::Define(
"SliceFn",
{"x: T", "begin: Index", "size: Index"},
{"y: T"},
{"T: {float, double, int32, int64}", "Index: {int32,int64}"},
{{{"y"},
"Slice",
{"x", "begin", "size"},
{{"T", "$T"}, {"Index", "$Index"}}}});
}
TEST_F(XlaCompilerTest, SliceWithDynamicBegins) {
XlaCompiler compiler(DefaultOptions());
FunctionDefLibrary flib;
*flib.add_function() = SliceFn();
TF_ASSERT_OK(flib_def_->AddFunctionDef(SliceFn()));
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
Scope scope = Scope::NewRootScope().ExitOnError();
auto value = ops::Const<int32>(scope.WithOpName("shape"), {5}, {1});
auto begin = ops::_Arg(scope.WithOpName("arg"), DT_INT32, 0);
auto size = ops::Const<int32>(scope.WithOpName("value"), {1}, {1});
TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(flib));
NodeDef def;
TF_ASSERT_OK(NodeDefBuilder("slice", "SliceFn", flib_def_.get())
.Input(value.name(), 0, DT_INT32)
.Input(begin.node()->name(), 1, DT_INT32)
.Input(size.name(), 2, DT_INT32)
.Finalize(&def));
Status status;
Node* slice = scope.graph()->AddNode(def, &status);
TF_ASSERT_OK(status);
TF_ASSERT_OK(scope.DoShapeInference(slice));
scope.graph()->AddEdge(value.node(), 0, slice, 0);
scope.graph()->AddEdge(begin.node(), 0, slice, 1);
scope.graph()->AddEdge(size.node(), 0, slice, 2);
auto retval = ops::_Retval(scope.WithOpName("retval"), Output(slice), 0);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({1});
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "slice",
std::move(graph), args, &result));
}
void RunAndCheckVariablesComputation(
xla::Client* client, const XlaCompiler::CompilationResult& result) {
xla::Literal param0_literal = xla::LiteralUtil::CreateR1<int32>({7, 42});
xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101});
std::unique_ptr<xla::GlobalData> param0_data =
client->TransferToServer(param0_literal).value();
std::unique_ptr<xla::GlobalData> param1_data =
client->TransferToServer(param1_literal).value();
std::unique_ptr<xla::GlobalData> actual =
client
->Execute(*result.computation, {param0_data.get(), param1_data.get()})
.value();
xla::Literal actual_literal = client->Transfer(*actual).value();
xla::Literal expected0 = xla::LiteralUtil::CreateR1<int32>({5, 144});
xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({4, 143});
xla::Literal expected_literal =
xla::LiteralUtil::MakeTuple({&expected0, &expected1});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
TEST_F(XlaCompilerTest, Variables) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1);
auto identity = ops::Identity(scope.WithOpName("VIdentity"), var);
auto write = ops::AssignAddVariableOp(scope, identity, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1));
auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
RunAndCheckVariablesComputation(client_, result);
}
TEST_F(XlaCompilerTest, ResultLayoutSingle) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::_Retval(scope.WithOpName("RET"), a, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 3});
auto options = DefaultOptions();
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns;
shape_determination_fns.shape_representation_fn =
[](const TensorShape& shape, DataType type, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> absl::StatusOr<xla::Shape> {
xla::Shape xla_shape;
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(type, shape, &xla_shape));
*xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1});
return xla_shape;
};
options.shape_determination_fns = shape_determination_fns;
XlaCompiler compiler(options);
XlaCompiler::CompilationResult result;
auto compile_options = XlaCompiler::CompileOptions();
compile_options.always_return_tuple = false;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "id", std::move(graph),
args, &result));
EXPECT_TRUE(xla::ShapeUtil::Equal(
result.xla_output_shape,
xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1})));
EXPECT_EQ(result.computation->GetProgramShape().value().result(),
result.xla_output_shape);
}
TEST_F(XlaCompilerTest, ResultLayoutMultiple) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::_Retval(scope.WithOpName("RET1"), a, 0);
auto c = ops::_Retval(scope.WithOpName("RET2"), a, 1);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 3});
auto options = DefaultOptions();
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns;
shape_determination_fns.shape_representation_fn =
[](const TensorShape& shape, DataType type, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> absl::StatusOr<xla::Shape> {
xla::Shape xla_shape;
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(type, shape, &xla_shape));
*xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1});
return xla_shape;
};
shape_determination_fns.layout_preference_fn = UseNoPreferenceLayoutFn();
options.shape_determination_fns = shape_determination_fns;
XlaCompiler compiler(options);
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "id",
std::move(graph), args, &result));
xla::Shape result_shape =
xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1});
EXPECT_TRUE(xla::ShapeUtil::Equal(
result.xla_output_shape,
xla::ShapeUtil::MakeTupleShape({result_shape, result_shape})));
EXPECT_EQ(result.computation->GetProgramShape().value().result(),
result.xla_output_shape);
}
TEST_F(XlaCompilerTest, ReturnResourceHandleOnly) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0);
auto d = ops::_Retval(scope.WithOpName("D"), var, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kResource;
args[0].resource_kind = XlaResource::kVariable;
args[0].initialized = true;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
xla::Literal param1_literal = xla::LiteralUtil::CreateR1<int32>({-3, 101});
std::unique_ptr<xla::GlobalData> param1_data =
client_->TransferToServer(param1_literal).value();
std::unique_ptr<xla::GlobalData> actual =
client_->Execute(*result.computation, {param1_data.get()}).value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
TEST_F(XlaCompilerTest, ReturnResourceHandle) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1);
auto identity = ops::Identity(scope.WithOpName("VIdentity"), var);
auto write = ops::AssignAddVariableOp(scope, identity, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1));
auto r = ops::_Retval(scope.WithOpName("R"), var, 0);
auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 1);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
RunAndCheckVariablesComputation(client_, result);
}
absl::StatusOr<std::unique_ptr<Graph>> BuildTestGraph() {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1);
auto write = ops::AssignAddVariableOp(scope, var, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
auto read_plus_one = ops::Add(scope, read, ops::Const<int32>(scope, 1));
auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_RETURN_IF_ERROR(scope.ToGraph(graph.get()));
return std::move(graph);
}
TEST_F(XlaCompilerTest, VariableRepresentationShapeFunction) {
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Graph> graph, BuildTestGraph());
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 2});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2, 2});
XlaCompiler::Options options = DefaultOptions();
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns;
shape_determination_fns.shape_representation_fn =
[](const TensorShape& shape, DataType type, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> absl::StatusOr<xla::Shape> {
xla::PrimitiveType ptype;
TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(type, &ptype));
return xla::ShapeUtil::MakeShape(ptype, {shape.num_elements()});
};
options.shape_determination_fns = shape_determination_fns;
XlaCompiler compiler(options);
XlaCompiler::CompileOptions compile_options;
compile_options.is_entry_computation = false;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph),
args, &result));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::ProgramShape> program_shape,
client_->GetComputationShape(*result.computation));
ASSERT_EQ(program_shape->parameters_size(), 2);
EXPECT_TRUE(
xla::ShapeUtil::Compatible(program_shape->parameters(0),
xla::ShapeUtil::MakeShape(xla::S32, {2, 2})));
EXPECT_TRUE(xla::ShapeUtil::Compatible(
program_shape->parameters(1), xla::ShapeUtil::MakeShape(xla::S32, {4})));
EXPECT_TRUE(xla::ShapeUtil::Compatible(
program_shape->result(),
xla::ShapeUtil::MakeTupleShape(
{xla::ShapeUtil::MakeShape(xla::S32, {2, 2}),
xla::ShapeUtil::MakeShape(xla::S32, {4})})));
xla::Literal param0_literal =
xla::LiteralUtil::CreateR2<int32>({{4, 55}, {1, -3}});
xla::Literal param1_literal =
xla::LiteralUtil::CreateR1<int32>({22, 11, 33, 404});
std::unique_ptr<xla::GlobalData> param0_data =
client_->TransferToServer(param0_literal).value();
std::unique_ptr<xla::GlobalData> param1_data =
client_->TransferToServer(param1_literal).value();
std::unique_ptr<xla::GlobalData> actual =
client_
->Execute(*result.computation, {param0_data.get(), param1_data.get()})
.value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
xla::Literal expected0 =
xla::LiteralUtil::CreateR2<int32>({{27, 67}, {35, 402}});
xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({26, 66, 34, 401});
xla::Literal expected_literal =
xla::LiteralUtil::MakeTuple({&expected0, &expected1});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
TEST_F(XlaCompilerTest, ArgRetvalShapeRepresentationFunction) {
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Graph> graph, BuildTestGraph());
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 2});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2, 2});
XlaCompiler::Options options = DefaultOptions();
XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns;
shape_determination_fns.shape_representation_fn =
[](const TensorShape& shape, DataType type, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> absl::StatusOr<xla::Shape> {
xla::PrimitiveType ptype;
TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(type, &ptype));
return xla::ShapeUtil::MakeShape(ptype, {shape.num_elements()});
};
options.shape_determination_fns = shape_determination_fns;
XlaCompiler compiler(options);
XlaCompiler::CompileOptions compile_options;
compile_options.is_entry_computation = true;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph),
args, &result));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::ProgramShape> program_shape,
client_->GetComputationShape(*result.computation));
ASSERT_EQ(program_shape->parameters_size(), 2);
EXPECT_TRUE(xla::ShapeUtil::Compatible(
program_shape->parameters(0), xla::ShapeUtil::MakeShape(xla::S32, {4})));
EXPECT_TRUE(xla::ShapeUtil::Compatible(
program_shape->parameters(1), xla::ShapeUtil::MakeShape(xla::S32, {4})));
EXPECT_TRUE(xla::ShapeUtil::Compatible(
program_shape->result(),
xla::ShapeUtil::MakeTupleShape(
{xla::ShapeUtil::MakeShape(xla::S32, {4}),
xla::ShapeUtil::MakeShape(xla::S32, {4})})));
xla::Literal param0_literal =
xla::LiteralUtil::CreateR1<int32>({4, 55, 1, -3});
xla::Literal param1_literal =
xla::LiteralUtil::CreateR1<int32>({22, 11, 33, 404});
std::unique_ptr<xla::GlobalData> param0_data =
client_->TransferToServer(param0_literal).value();
std::unique_ptr<xla::GlobalData> param1_data =
client_->TransferToServer(param1_literal).value();
std::unique_ptr<xla::GlobalData> actual =
client_
->Execute(*result.computation, {param0_data.get(), param1_data.get()})
.value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
xla::Literal expected0 = xla::LiteralUtil::CreateR1<int32>({27, 67, 35, 402});
xla::Literal expected1 = xla::LiteralUtil::CreateR1<int32>({26, 66, 34, 401});
xla::Literal expected_literal =
xla::LiteralUtil::MakeTuple({&expected0, &expected1});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
TEST_F(XlaCompilerTest, FunctionWithInvalidOp) {
XlaCompiler compiler(DefaultOptions());
FunctionDefLibrary flib;
FunctionDef fn = FillFn();
NodeDef* node = fn.add_node_def();
node->set_name("Invalid");
node->set_op("InvalidOp");
node = fn.add_node_def();
node->set_name("Switch");
node->set_op("Switch");
*flib.add_function() = fn;
TF_ASSERT_OK(flib_def_->AddFunctionDef(fn));
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
Scope scope = Scope::NewRootScope().ExitOnError();
auto value = ops::Const<int32>(scope.WithOpName("value"), 1, {});
auto shape = ops::Const<int32>(scope.WithOpName("shape"), {5}, {1});
TF_ASSERT_OK(scope.graph()->AddFunctionLibrary(flib));
NodeDef def;
TF_ASSERT_OK(NodeDefBuilder("fill_fn", "FillFn", flib_def_.get())
.Input(value.name(), 0, DT_INT32)
.Input(shape.name(), 1, DT_INT32)
.Finalize(&def));
Status status;
Node* fill = scope.graph()->AddNode(def, &status);
TF_ASSERT_OK(status);
TF_ASSERT_OK(scope.DoShapeInference(fill));
scope.graph()->AddEdge(value.node(), 0, fill, 0);
scope.graph()->AddEdge(shape.node(), 0, fill, 1);
auto retval = ops::_Retval(scope.WithOpName("retval"), Output(fill), 0);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args;
XlaCompiler::CompilationResult result;
status = compiler.CompileGraph(XlaCompiler::CompileOptions(), "fill",
std::move(graph), args, &result);
ASSERT_FALSE(status.ok());
EXPECT_TRUE(absl::StrContains(status.message(), "InvalidOp"))
<< status.message();
EXPECT_TRUE(absl::StrContains(status.message(), "{{node fill_fn}}"))
<< status.message();
}
TEST_F(XlaCompilerTest, NodeWithInvalidDataType) {
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
NodeDef shape;
shape.set_name("Shape");
shape.set_op("Shape");
(*shape.mutable_attr())["T"].set_type(DT_INT32);
(*shape.mutable_attr())["out_type"].set_type(DT_BOOL);
Status status;
Node* shape_node = graph->AddNode(shape, &status);
TF_ASSERT_OK(status);
graph->AddControlEdge(graph->source_node(), shape_node);
std::vector<XlaCompiler::Argument> args;
XlaCompiler::CompilationResult result;
XlaCompiler compiler(DefaultOptions());
status = compiler.CompileGraph(XlaCompiler::CompileOptions(), "invalid_type",
std::move(graph), args, &result);
ASSERT_FALSE(status.ok());
EXPECT_TRUE(absl::StrContains(status.message(),
"is not in the list of allowed values"))
<< status.message();
EXPECT_TRUE(absl::StrContains(status.message(), "{{node Shape}}"))
<< status.message();
}
TEST_F(XlaCompilerTest, SingleOpWithoutInputs) {
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
NodeDef no_op;
no_op.set_name("NoOp");
no_op.set_op("NoOp");
Status status;
graph->AddNode(no_op, &status);
TF_ASSERT_OK(status);
std::vector<XlaCompiler::Argument> args;
XlaCompiler compiler(DefaultOptions());
{
std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global()));
CopyGraph(*graph, graph_copy.get());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "NoOp",
std::move(graph_copy), args, &result));
}
}
class DummySideEffectingOp : public XlaOpKernel {
public:
explicit DummySideEffectingOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
OP_REQUIRES_OK(ctx, ctx->compiler()->SetNodeToken(
name(), xla::CreateToken(ctx->builder())));
}
};
REGISTER_OP("DummySideEffectingOp");
REGISTER_XLA_OP(Name("DummySideEffectingOp"), DummySideEffectingOp);
TEST_F(XlaCompilerTest, TokenInputAndOutput) {
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
NodeDef side_effecting_op;
side_effecting_op.set_name("DummySideEffectingOp");
side_effecting_op.set_op("DummySideEffectingOp");
AddNodeAttr(kXlaTokenInputNodesAttrName,
std::vector<string>{kXlaTokenArgNodeName}, &side_effecting_op);
AddNodeAttr(kXlaOriginalOutsideCompilationNodeName, side_effecting_op.name(),
&side_effecting_op);
Status status;
graph->AddNode(side_effecting_op, &status);
TF_ASSERT_OK(status);
EXPECT_TRUE(FixupSourceAndSinkEdges(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kResource;
args[0].resource_kind = XlaResource::kVariable;
args[0].initialized = true;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2, 2});
{
XlaCompiler::CompileOptions options;
options.is_entry_computation = true;
options.add_token_input_output = false;
options.return_updated_values_for_all_resources = true;
XlaCompiler compiler(DefaultOptions());
std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global()));
CopyGraph(*graph, graph_copy.get());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(options, "NoOp", std::move(graph_copy),
args, &result));
EXPECT_EQ(result.xla_input_shapes.size(), 1);
EXPECT_TRUE(result.xla_output_shape.IsTuple());
EXPECT_EQ(xla::ShapeUtil::TupleElementCount(result.xla_output_shape), 1);
}
{
XlaCompiler::CompileOptions options;
options.is_entry_computation = false;
options.add_token_input_output = true;
options.return_updated_values_for_all_resources = true;
XlaCompiler compiler(DefaultOptions());
std::unique_ptr<Graph> graph_copy(new Graph(OpRegistry::Global()));
CopyGraph(*graph, graph_copy.get());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(options, "NoOp", std::move(graph_copy),
args, &result));
EXPECT_EQ(result.xla_input_shapes.size(), 2);
EXPECT_TRUE(result.xla_input_shapes[1].IsToken());
EXPECT_TRUE(result.xla_output_shape.IsTuple());
EXPECT_EQ(xla::ShapeUtil::TupleElementCount(result.xla_output_shape), 2);
EXPECT_TRUE(xla::ShapeUtil::GetTupleElementShape(result.xla_output_shape, 1)
.IsToken());
}
}
TEST_F(XlaCompilerTest, OpsWithTensorListInput) {
FunctionDefLibrary fdef_lib;
FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib);
{
Scope scope = Scope::NewRootScope().ExitOnError();
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0);
auto result = ops::Const<bool>(scope, {true}, {});
ops::_Retval(scope.WithOpName("ret"), result, 0);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
FunctionDef fdef;
TF_ASSERT_OK(GraphToFunctionDef(*graph, "cond", &fdef));
TF_ASSERT_OK(flib_def.AddFunctionDef(fdef));
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
auto arg = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0);
ops::_Retval(scope.WithOpName("ret"), arg, 0);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
FunctionDef fdef;
TF_ASSERT_OK(GraphToFunctionDef(*graph, "body", &fdef));
TF_ASSERT_OK(flib_def.AddFunctionDef(fdef));
}
Scope scope = Scope::NewRootScope().ExitOnError();
auto element_shape = ops::Const<int32>(scope, {1}, {1});
auto max_elements = ops::Const<int32>(scope, {10}, {});
auto arg = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0);
std::initializer_list<Output> out = {arg, arg};
auto add_n = ops::AddN(scope, out);
NameAttrList cond_fn, body_fn;
cond_fn.set_name("cond");
body_fn.set_name("body");
auto while_op =
ops::While(scope, std::initializer_list<Input>{arg}, cond_fn, body_fn);
auto ret0 = ops::_Retval(scope.WithOpName("ret0"), add_n, 0);
auto ret1 = ops::_Retval(scope.WithOpName("ret1"), while_op.output[0], 1);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kTensorList;
xla::Shape tensor_list_element_shape;
TF_ASSERT_OK(TensorShapeToXLAShape(DT_INT32, TensorShape{1},
&tensor_list_element_shape));
xla::Shape index_shape;
TF_ASSERT_OK(TensorShapeToXLAShape(DT_INT32, TensorShape{}, &index_shape));
std::vector<xla::Shape> shapes{tensor_list_element_shape, index_shape};
xla::Shape arg_shape = xla::ShapeUtil::MakeTupleShape(shapes);
args[0].shape = arg_shape;
XlaCompiler::Options options = DefaultOptions();
options.flib_def = &flib_def;
XlaCompiler compiler(options);
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add",
std::move(graph), args, &result));
ASSERT_EQ(result.outputs.size(), 2);
const XlaCompiler::OutputDescription& output0 = result.outputs[0];
ASSERT_TRUE(output0.is_tensor_list);
const XlaCompiler::OutputDescription& output1 = result.outputs[1];
ASSERT_TRUE(output1.is_tensor_list);
}
TEST_F(XlaCompilerTest, WhileWithResources) {
FunctionDefLibrary fdef_lib;
FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib);
{
Scope scope = Scope::NewRootScope().ExitOnError();
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1);
auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2);
auto less = ops::Less(scope, arg0, ops::Const<int32>(scope, 10));
(void)ops::_Retval(scope.WithOpName("ret"), less, 0);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
FunctionDef fdef;
TF_ASSERT_OK(GraphToFunctionDef(*graph, "cond", &fdef));
TF_ASSERT_OK(flib_def.AddFunctionDef(fdef));
}
{
Scope scope = Scope::NewRootScope().ExitOnError();
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1);
auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2);
auto read1 = ops::ReadVariableOp(scope.WithOpName("read1"), arg1, DT_INT32);
auto plus_read1 = ops::Add(scope, arg0, read1);
auto read2 = ops::ReadVariableOp(scope.WithOpName("read2"), arg2, DT_INT32);
auto minus_read2 = ops::Sub(scope, plus_read1, read2);
(void)ops::_Retval(scope.WithOpName("ret0"), minus_read2, 0);
(void)ops::_Retval(scope.WithOpName("ret1"), arg1, 1);
(void)ops::_Retval(scope.WithOpName("ret2"), arg2, 2);
TF_ASSERT_OK(scope.ToGraph(graph.get()));
FunctionDef fdef;
TF_ASSERT_OK(GraphToFunctionDef(*graph, "body", &fdef));
TF_ASSERT_OK(flib_def.AddFunctionDef(fdef));
}
Scope scope = Scope::NewRootScope().ExitOnError();
auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0);
auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1);
auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2);
NameAttrList cond_fn, body_fn;
cond_fn.set_name("cond");
body_fn.set_name("body");
auto while_op = ops::While(
scope, std::initializer_list<Input>{arg0, arg1, arg2}, cond_fn, body_fn);
(void)ops::_Retval(scope.WithOpName("ret0"), while_op.output[0], 0);
(void)ops::_Retval(scope.WithOpName("ret1"), while_op.output[1], 1);
(void)ops::_Retval(scope.WithOpName("ret2"), while_op.output[2], 2);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(3);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({});
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({});
args[2].kind = XlaCompiler::Argument::kResource;
args[2].resource_kind = XlaResource::kVariable;
args[2].initialized = true;
args[2].type = DT_INT32;
args[2].shape = TensorShape({});
XlaCompiler::Options options = DefaultOptions();
options.flib_def = &flib_def;
XlaCompiler compiler(options);
XlaCompiler::CompileOptions compile_options = XlaCompiler::CompileOptions();
compile_options.return_updated_values_for_all_resources = true;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "tested_while_with_vars",
std::move(graph), args, &result));
ASSERT_EQ(result.outputs.size(), 3);
const XlaCompiler::OutputDescription& output1 = result.outputs[1];
ASSERT_EQ(output1.input_index, 1);
const XlaCompiler::OutputDescription& output2 = result.outputs[2];
ASSERT_EQ(output2.input_index, 2);
xla::Literal literal0 = xla::LiteralUtil::CreateR0<int32>(0);
xla::Literal literal1 = xla::LiteralUtil::CreateR0<int32>(2);
xla::Literal literal2 = xla::LiteralUtil::CreateR0<int32>(1);
std::unique_ptr<xla::GlobalData> data0 =
client_->TransferToServer(literal0).value();
std::unique_ptr<xla::GlobalData> data1 =
client_->TransferToServer(literal1).value();
std::unique_ptr<xla::GlobalData> data2 =
client_->TransferToServer(literal2).value();
std::unique_ptr<xla::GlobalData> actual =
client_
->Execute(*result.computation,
{data0.get(), data1.get(), data2.get()})
.value();
xla::Literal actual_literal = client_->Transfer(*actual).value();
xla::Literal expected0 = xla::LiteralUtil::CreateR0<int32>(10);
xla::Literal expected1 = xla::LiteralUtil::CreateR0<int32>(2);
xla::Literal expected2 = xla::LiteralUtil::CreateR0<int32>(1);
xla::Literal expected_literal =
xla::LiteralUtil::MakeTuple({&expected0, &expected1, &expected2});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
TEST_F(XlaCompilerTest, SetShardingForReturnedTuple) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto b = ops::_Retval(scope.WithOpName("B"), a, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
auto node_name_index = graph->BuildNodeNameIndex();
Node* ret_node = node_name_index["B"];
ASSERT_NE(ret_node, nullptr);
xla::Array<int64_t> tile_assignment({2});
tile_assignment.FillIota(0);
xla::HloSharding sharding = xla::HloSharding::Tile(tile_assignment);
ret_node->AddAttr("_XlaSharding", sharding.ToProto().SerializeAsString());
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kParameter;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "test",
std::move(graph), args, &result));
const auto& hlo_module_proto = result.computation->proto();
ASSERT_EQ(hlo_module_proto.computations_size(), 1);
const auto& hlo_computation_proto = hlo_module_proto.computations(0);
std::optional<xla::HloInstructionProto> root_instruction_proto;
for (const auto& inst : hlo_computation_proto.instructions()) {
if (inst.id() == hlo_computation_proto.root_id()) {
root_instruction_proto = inst;
break;
}
}
ASSERT_TRUE(root_instruction_proto);
xla::Shape tuple_shape = xla::ShapeUtil::MakeTupleShape(
{xla::ShapeUtil::MakeShape(xla::S32, {2})});
xla::HloSharding tuple_sharding = xla::HloSharding::Tuple(
tuple_shape, std::vector<xla::HloSharding>{sharding});
EXPECT_EQ(root_instruction_proto->sharding().SerializeAsString(),
tuple_sharding.ToProto().SerializeAsString());
}
TEST_F(XlaCompilerTest, AliasResourceUpdates) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::Const<int32>(scope.WithOpName("A"), {1, 2});
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1);
auto write = ops::AssignAddVariableOp(scope, var, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
auto d = ops::_Retval(scope.WithOpName("D"), read, 0);
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(scope.ToGraph(graph.get()));
std::vector<XlaCompiler::Argument> args(2);
args[0].kind = XlaCompiler::Argument::kConstant;
args[0].type = DT_INT32;
args[0].shape = TensorShape({2});
args[0].constant_value = Tensor(DT_INT32, {1, 1});
args[0].initialized = true;
args[1].kind = XlaCompiler::Argument::kResource;
args[1].resource_kind = XlaResource::kVariable;
args[1].initialized = true;
args[1].type = DT_INT32;
args[1].shape = TensorShape({2});
XlaCompiler compiler(DefaultOptions());
XlaCompiler::CompileOptions compile_options;
compile_options.alias_resource_update = true;
XlaCompiler::CompilationResult result;
TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph),
args, &result));
const xla::HloInputOutputAliasProto& alias =
result.computation->proto().input_output_alias();
EXPECT_EQ(alias.entries_size(), 1);
EXPECT_EQ(alias.entries(0).parameter_number(), 0);
}
TEST_F(XlaCompilerTest, SetDeviceToHostMetadataExactDuplicate) {
XlaCompiler compiler(DefaultOptions());
const string& key = "comm_key";
std::vector<DataType> types{DT_INT32};
std::vector<TensorShape> shapes{TensorShape({2})};
TF_ASSERT_OK(compiler.SetDeviceToHostMetadata(key, types, shapes));
TF_ASSERT_OK(compiler.SetDeviceToHostMetadata(key, types, shapes));
}
TEST_F(XlaCompilerTest, SetDeviceToHostMetadataMismatchedDuplicate) {
XlaCompiler compiler(DefaultOptions());
const string& key = "comm_key";
std::vector<DataType> types{DT_INT32};
std::vector<TensorShape> shapes{TensorShape({2})};
std::vector<DataType> types2{DT_FLOAT};
std::vector<TensorShape> shapes2{TensorShape({1})};
TF_ASSERT_OK(compiler.SetDeviceToHostMetadata(key, types, shapes));
Status status = compiler.SetDeviceToHostMetadata(key, types2, shapes2);
EXPECT_EQ(status.code(), error::Code::INVALID_ARGUMENT);
}
TEST_F(XlaCompilerTest, SetHostToDeviceMetadataExactDuplicate) {
XlaCompiler compiler(DefaultOptions());
const string& key = "comm_key";
std::vector<DataType> types{DT_INT32};
std::vector<TensorShape> shapes{TensorShape({2})};
TF_ASSERT_OK(compiler.SetHostToDeviceMetadata(key, types, shapes));
TF_ASSERT_OK(compiler.SetHostToDeviceMetadata(key, types, shapes));
}
TEST_F(XlaCompilerTest, SetHostToDeviceMetadataMismatchedDuplicate) {
XlaCompiler compiler(DefaultOptions());
const string& key = "comm_key";
std::vector<DataType> types{DT_INT32};
std::vector<TensorShape> shapes{TensorShape({2})};
std::vector<DataType> types2{DT_FLOAT};
std::vector<TensorShape> shapes2{TensorShape({1})};
TF_ASSERT_OK(compiler.SetHostToDeviceMetadata(key, types, shapes));
Status status = compiler.SetHostToDeviceMetadata(key, types2, shapes2);
EXPECT_EQ(status.code(), error::Code::INVALID_ARGUMENT);
}
TEST_F(OpsTestBase, BuildSingleOpCompileArgument) {
TF_EXPECT_OK(NodeDefBuilder("identity_op", "Identity")
.Input(FakeInput(DT_FLOAT))
.Attr("T", DT_FLOAT)
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
AddInputFromArray<float>(TensorShape({1, 2}), {0, 1});
TF_EXPECT_OK(RunOpKernel());
XlaCompiler::SingleOpCompileArgument arg(*context_);
EXPECT_THAT(arg.output_dtypes, ::testing::ElementsAreArray({DT_FLOAT}));
EXPECT_EQ(arg.node_def.SerializeAsString(),
context_->op_kernel().def().SerializeAsString());
EXPECT_EQ(arg.config_proto.ByteSizeLong(), 0);
}
TEST_F(OpsTestBase, CompileSingleOp) {
TF_EXPECT_OK(NodeDefBuilder("identity_op", "Identity")
.Input(FakeInput(DT_FLOAT))
.Attr("T", DT_FLOAT)
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
AddInputFromArray<float>(TensorShape({1, 2}), {6.9, 4.2});
TF_EXPECT_OK(RunOpKernel());
XlaCompiler::SingleOpCompileArgument single_op_arg(*context_);
xla::Client* client = xla::ClientLibrary::LocalClientOrDie();
XlaOpRegistry::RegisterCompilationKernels();
FunctionDefLibrary flib;
std::unique_ptr<FunctionLibraryDefinition> flib_def(
new FunctionLibraryDefinition(OpRegistry::Global(), flib));
XlaCompiler::Options options;
options.device_type = DeviceType(DEVICE_CPU_XLA_JIT);
options.client = client;
options.flib_def = flib_def.get();
XlaCompiler compiler(options);
std::vector<XlaCompiler::Argument> args(1);
args[0].kind = XlaCompiler::Argument::kConstant;
args[0].type = DT_FLOAT;
args[0].shape = TensorShape({1, 2});
args[0].constant_value = GetInput(0);
args[0].initialized = true;
XlaCompiler::CompilationResult result;
TF_EXPECT_OK(compiler.CompileSingleOp(XlaCompiler::CompileOptions(),
single_op_arg, args, &result));
std::unique_ptr<xla::GlobalData> actual =
client->Execute(*result.computation, {}).value();
xla::Literal actual_literal = client->Transfer(*actual).value();
xla::Literal expected0 = xla::LiteralUtil::CreateR2<float>({{6.9, 4.2}});
xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0});
EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/xla_compiler.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/xla_compiler_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
9314abd7-8c5d-42d1-a964-8ca3231083e7 | cpp | tensorflow/tensorflow | unidirectional_sequence_rnn | tensorflow/lite/kernels/unidirectional_sequence_rnn.cc | tensorflow/lite/kernels/unidirectional_sequence_rnn_test.cc | #include <cstddef>
#include <cstdint>
#include "tensorflow/lite/core/c/builtin_op_data.h"
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/internal/kernel_utils.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace unidirectional_sequence_rnn {
namespace {
struct OpData {
int scratch_tensor_index;
bool compute_row_sums = false;
};
}
constexpr int kInputTensor = 0;
constexpr int kWeightsTensor = 1;
constexpr int kRecurrentWeightsTensor = 2;
constexpr int kBiasTensor = 3;
constexpr int kHiddenStateTensor = 4;
constexpr int kOutputTensor = 0;
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
auto* op_data = new OpData();
context->AddTensors(context, 6,
&op_data->scratch_tensor_index);
return op_data;
}
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<OpData*>(buffer);
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, node->inputs->size, 5);
TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const TfLiteTensor* input_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kWeightsTensor, &input_weights));
const TfLiteTensor* recurrent_weights;
TF_LITE_ENSURE_OK(
context,
GetInputSafe(context, node, kRecurrentWeightsTensor, &recurrent_weights));
const TfLiteTensor* bias;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBiasTensor, &bias));
const TfLiteTensor* hidden_state;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kHiddenStateTensor, &hidden_state));
auto* params = reinterpret_cast<TfLiteSequenceRNNParams*>(node->builtin_data);
const bool time_major = params->time_major;
const int batch_size =
(time_major) ? input->dims->data[1] : input->dims->data[0];
const int max_time =
(time_major) ? input->dims->data[0] : input->dims->data[1];
const int num_units = input_weights->dims->data[0];
TF_LITE_ENSURE_EQ(context, input->dims->data[2],
input_weights->dims->data[1]);
TF_LITE_ENSURE_EQ(context, input_weights->dims->data[0], bias->dims->data[0]);
TF_LITE_ENSURE_EQ(context, recurrent_weights->dims->data[0],
bias->dims->data[0]);
TF_LITE_ENSURE_EQ(context, recurrent_weights->dims->data[1],
bias->dims->data[0]);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
TF_LITE_ENSURE_TYPES_EQ(context, input_weights->type,
recurrent_weights->type);
TF_LITE_ENSURE_EQ(context, NumDimensions(hidden_state), 2);
TF_LITE_ENSURE_EQ(context, hidden_state->dims->data[0], batch_size);
TF_LITE_ENSURE_EQ(context, hidden_state->dims->data[1], num_units);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TfLiteIntArray* output_size_array = TfLiteIntArrayCreate(3);
output_size_array->data[0] = (time_major) ? max_time : batch_size;
output_size_array->data[1] = (time_major) ? batch_size : max_time;
output_size_array->data[2] = num_units;
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, output, output_size_array));
const bool is_hybrid = IsHybridOp(input, input_weights);
if (is_hybrid) {
auto* op_data = reinterpret_cast<OpData*>(node->user_data);
op_data->compute_row_sums = true;
TfLiteIntArrayFree(node->temporaries);
node->temporaries = TfLiteIntArrayCreate(6);
node->temporaries->data[0] = op_data->scratch_tensor_index;
TfLiteTensor* input_quantized;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, 0,
&input_quantized));
input_quantized->type = input_weights->type;
input_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {
TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,
input_quantized_size));
}
node->temporaries->data[1] = op_data->scratch_tensor_index + 1;
TfLiteTensor* hidden_state_quantized;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, 1,
&hidden_state_quantized));
hidden_state_quantized->type = input_weights->type;
hidden_state_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(hidden_state_quantized->dims,
hidden_state->dims)) {
TfLiteIntArray* hidden_state_quantized_size =
TfLiteIntArrayCopy(hidden_state->dims);
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, hidden_state_quantized,
hidden_state_quantized_size));
}
node->temporaries->data[2] = op_data->scratch_tensor_index + 2;
TfLiteTensor* scaling_factors;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, 2,
&scaling_factors));
scaling_factors->type = kTfLiteFloat32;
scaling_factors->allocation_type = kTfLiteArenaRw;
int scaling_dims[1] = {batch_size};
if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {
TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);
scaling_factors_size->data[0] = batch_size;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,
scaling_factors_size));
}
node->temporaries->data[3] = op_data->scratch_tensor_index + 3;
TfLiteTensor* accum_scratch;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, 3, &accum_scratch));
accum_scratch->type = kTfLiteInt32;
accum_scratch->allocation_type = kTfLiteArenaRw;
int accum_scratch_dims[2] = {num_units, batch_size};
if (!TfLiteIntArrayEqualsArray(accum_scratch->dims, 2,
accum_scratch_dims)) {
TfLiteIntArray* accum_scratch_size = TfLiteIntArrayCreate(2);
accum_scratch_size->data[0] = accum_scratch_dims[0];
accum_scratch_size->data[1] = accum_scratch_dims[1];
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, accum_scratch,
accum_scratch_size));
}
node->temporaries->data[4] = op_data->scratch_tensor_index + 4;
TfLiteTensor* zero_points;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, 4, &zero_points));
zero_points->type = kTfLiteInt32;
zero_points->allocation_type = kTfLiteArenaRw;
int zero_points_dims[1] = {batch_size};
if (!TfLiteIntArrayEqualsArray(zero_points->dims, 1, zero_points_dims)) {
TfLiteIntArray* zero_points_size = TfLiteIntArrayCreate(1);
zero_points_size->data[0] = batch_size;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, zero_points,
zero_points_size));
}
node->temporaries->data[5] = op_data->scratch_tensor_index + 5;
TfLiteTensor* row_sums;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, 5, &row_sums));
row_sums->type = kTfLiteInt32;
row_sums->allocation_type = kTfLiteArenaRwPersistent;
int row_sums_dims[2] = {2, num_units};
if (!TfLiteIntArrayEqualsArray(row_sums->dims, 2, row_sums_dims)) {
TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(2);
row_sums_size->data[0] = row_sums_dims[0];
row_sums_size->data[1] = row_sums_dims[1];
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, row_sums, row_sums_size));
}
}
return kTfLiteOk;
}
TfLiteStatus EvalFloat(const TfLiteTensor* input,
const TfLiteTensor* input_weights,
const TfLiteTensor* recurrent_weights,
const TfLiteTensor* bias,
const TfLiteSequenceRNNParams* params,
TfLiteTensor* hidden_state, TfLiteTensor* output) {
const float* bias_ptr = GetTensorData<float>(bias);
const bool time_major = params->time_major;
const int batch_size =
(time_major) ? input->dims->data[1] : input->dims->data[0];
const int max_time =
(time_major) ? input->dims->data[0] : input->dims->data[1];
const int num_units = input_weights->dims->data[0];
const int input_size = input->dims->data[2];
const float* input_weights_ptr = GetTensorData<float>(input_weights);
const float* recurrent_weights_ptr = GetTensorData<float>(recurrent_weights);
if (time_major) {
float* hidden_state_ptr_batch = GetTensorData<float>(hidden_state);
for (int s = 0; s < max_time; s++) {
const float* input_ptr_batch =
GetTensorData<float>(input) + s * input_size * batch_size;
float* output_ptr_batch =
GetTensorData<float>(output) + s * num_units * batch_size;
kernel_utils::RnnBatchStep(
input_ptr_batch, input_weights_ptr, recurrent_weights_ptr, bias_ptr,
input_size, num_units, batch_size, num_units, params->activation,
hidden_state_ptr_batch, output_ptr_batch);
}
} else {
for (int b = 0; b < batch_size; b++) {
float* hidden_state_ptr_batch =
GetTensorData<float>(hidden_state) + b * num_units;
for (int s = 0; s < max_time; s++) {
const float* input_ptr_batch = GetTensorData<float>(input) +
b * input_size * max_time +
s * input_size;
float* output_ptr_batch = GetTensorData<float>(output) +
b * num_units * max_time + s * num_units;
kernel_utils::RnnBatchStep(
input_ptr_batch, input_weights_ptr, recurrent_weights_ptr, bias_ptr,
input_size, num_units, 1, num_units,
params->activation, hidden_state_ptr_batch, output_ptr_batch);
}
}
}
return kTfLiteOk;
}
TfLiteStatus EvalHybrid(
const TfLiteTensor* input, const TfLiteTensor* input_weights,
const TfLiteTensor* recurrent_weights, const TfLiteTensor* bias,
const TfLiteSequenceRNNParams* params, TfLiteTensor* input_scratch,
TfLiteTensor* hidden_state_scratch, TfLiteTensor* scaling_factors,
TfLiteTensor* hidden_state, TfLiteTensor* output, TfLiteTensor* zero_points,
TfLiteTensor* accum_scratch, TfLiteTensor* row_sums,
bool* compute_row_sums) {
const bool time_major = params->time_major;
const int batch_size =
(time_major) ? input->dims->data[1] : input->dims->data[0];
const int max_time =
(time_major) ? input->dims->data[0] : input->dims->data[1];
const int num_units = input_weights->dims->data[0];
const int input_size = input->dims->data[2];
const float* bias_ptr = GetTensorData<float>(bias);
const int8_t* input_weights_ptr = GetTensorData<int8_t>(input_weights);
const int8_t* recurrent_weights_ptr =
GetTensorData<int8_t>(recurrent_weights);
int8_t* quantized_input_ptr = GetTensorData<int8_t>(input_scratch);
int8_t* quantized_hidden_state_ptr =
GetTensorData<int8_t>(hidden_state_scratch);
float input_weights_scale = input_weights->params.scale;
float recurrent_weights_scale = recurrent_weights->params.scale;
float* scaling_factors_ptr = GetTensorData<float>(scaling_factors);
int32_t* accum_scratch_ptr = GetTensorData<int32_t>(accum_scratch);
int32_t* zero_points_ptr = nullptr;
int32_t* row_sums_ptr = nullptr;
if (params->asymmetric_quantize_inputs) {
zero_points_ptr = GetTensorData<int32_t>(zero_points);
row_sums_ptr = GetTensorData<int32_t>(row_sums);
}
if (time_major) {
float* hidden_state_ptr_batch = GetTensorData<float>(hidden_state);
for (int s = 0; s < max_time; s++) {
const float* input_ptr_batch =
GetTensorData<float>(input) + s * input_size * batch_size;
float* output_ptr_batch =
GetTensorData<float>(output) + s * num_units * batch_size;
kernel_utils::RnnBatchStep(
input_ptr_batch, input_weights_ptr, input_weights_scale,
recurrent_weights_ptr, recurrent_weights_scale, bias_ptr, input_size,
num_units, batch_size, num_units, params->activation,
quantized_input_ptr, quantized_hidden_state_ptr, scaling_factors_ptr,
hidden_state_ptr_batch, output_ptr_batch,
params->asymmetric_quantize_inputs, zero_points_ptr,
accum_scratch_ptr, row_sums_ptr, compute_row_sums);
}
} else {
for (int b = 0; b < batch_size; b++) {
float* hidden_state_ptr_batch =
GetTensorData<float>(hidden_state) + b * num_units;
for (int s = 0; s < max_time; s++) {
const float* input_ptr_batch = GetTensorData<float>(input) +
b * input_size * max_time +
s * input_size;
float* output_ptr_batch = GetTensorData<float>(output) +
b * num_units * max_time + s * num_units;
kernel_utils::RnnBatchStep(
input_ptr_batch, input_weights_ptr, input_weights_scale,
recurrent_weights_ptr, recurrent_weights_scale, bias_ptr,
input_size, num_units, 1, num_units,
params->activation, quantized_input_ptr, quantized_hidden_state_ptr,
scaling_factors_ptr, hidden_state_ptr_batch, output_ptr_batch,
params->asymmetric_quantize_inputs, zero_points_ptr,
accum_scratch_ptr, row_sums_ptr, compute_row_sums);
}
}
}
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteSequenceRNNParams*>(node->builtin_data);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const TfLiteTensor* input_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kWeightsTensor, &input_weights));
const TfLiteTensor* recurrent_weights;
TF_LITE_ENSURE_OK(
context,
GetInputSafe(context, node, kRecurrentWeightsTensor, &recurrent_weights));
const TfLiteTensor* bias;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBiasTensor, &bias));
TfLiteTensor* hidden_state =
GetVariableInput(context, node, kHiddenStateTensor);
TF_LITE_ENSURE(context, hidden_state != nullptr);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
switch (input_weights->type) {
case kTfLiteFloat32:
return EvalFloat(input, input_weights, recurrent_weights, bias, params,
hidden_state, output);
case kTfLiteUInt8:
case kTfLiteInt8: {
auto* op_data = reinterpret_cast<OpData*>(node->user_data);
TfLiteTensor* input_quantized;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, 0, &input_quantized));
TfLiteTensor* hidden_state_quantized;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, 1, &hidden_state_quantized));
TfLiteTensor* scaling_factors;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, 2, &scaling_factors));
TfLiteTensor* accum_scratch;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, 3, &accum_scratch));
TfLiteTensor* zero_points;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, 4, &zero_points));
TfLiteTensor* row_sums;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, 5, &row_sums));
return EvalHybrid(input, input_weights, recurrent_weights, bias, params,
input_quantized, hidden_state_quantized,
scaling_factors, hidden_state, output, zero_points,
accum_scratch, row_sums, &op_data->compute_row_sums);
}
default:
TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.",
TfLiteTypeGetName(input_weights->type));
return kTfLiteError;
}
}
}
TfLiteRegistration* Register_UNIDIRECTIONAL_SEQUENCE_RNN() {
static TfLiteRegistration r = {
unidirectional_sequence_rnn::Init, unidirectional_sequence_rnn::Free,
unidirectional_sequence_rnn::Prepare, unidirectional_sequence_rnn::Eval};
return &r;
}
}
}
} | #include <initializer_list>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffers.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/schema/schema_generated.h"
namespace tflite {
namespace {
using ::testing::ElementsAreArray;
static float rnn_input[] = {
0.23689353, 0.285385, 0.037029743, -0.19858193, -0.27569133,
0.43773448, 0.60379338, 0.35562468, -0.69424844, -0.93421471,
-0.87287879, 0.37144363, -0.62476718, 0.23791671, 0.40060222,
0.1356622, -0.99774903, -0.98858172, -0.38952237, -0.47685933,
0.31073618, 0.71511042, -0.63767755, -0.31729108, 0.33468103,
0.75801885, 0.30660987, -0.37354088, 0.77002847, -0.62747043,
-0.68572164, 0.0069220066, 0.65791464, 0.35130811, 0.80834007,
-0.61777675, -0.21095741, 0.41213346, 0.73784804, 0.094794154,
0.47791874, 0.86496925, -0.53376222, 0.85315156, 0.10288584,
0.86684, -0.011186242, 0.10513687, 0.87825835, 0.59929144,
0.62827742, 0.18899453, 0.31440187, 0.99059987, 0.87170351,
-0.35091716, 0.74861872, 0.17831337, 0.2755419, 0.51864719,
0.55084288, 0.58982027, -0.47443086, 0.20875752, -0.058871567,
-0.66609079, 0.59098077, 0.73017097, 0.74604273, 0.32882881,
-0.17503482, 0.22396147, 0.19379807, 0.29120302, 0.077113032,
-0.70331609, 0.15804303, -0.93407321, 0.40182066, 0.036301374,
0.66521823, 0.0300982, -0.7747041, -0.02038002, 0.020698071,
-0.90300065, 0.62870288, -0.23068321, 0.27531278, -0.095755219,
-0.712036, -0.17384434, -0.50593495, -0.18646687, -0.96508682,
0.43519354, 0.14744234, 0.62589407, 0.1653645, -0.10651493,
-0.045277178, 0.99032974, -0.88255352, -0.85147917, 0.28153265,
0.19455957, -0.55479527, -0.56042433, 0.26048636, 0.84702539,
0.47587705, -0.074295521, -0.12287641, 0.70117295, 0.90532446,
0.89782166, 0.79817224, 0.53402734, -0.33286154, 0.073485017,
-0.56172788, -0.044897556, 0.89964068, -0.067662835, 0.76863563,
0.93455386, -0.6324693, -0.083922029};
static float rnn_golden_output[] = {
0.496726, 0, 0.965996, 0, 0.0584254, 0,
0, 0.12315, 0, 0, 0.612266, 0.456601,
0, 0.52286, 1.16099, 0.0291232,
0, 0, 0.524901, 0, 0, 0,
0, 1.02116, 0, 1.35762, 0, 0.356909,
0.436415, 0.0355727, 0, 0,
0, 0, 0, 0.262335, 0, 0,
0, 1.33992, 0, 2.9739, 0, 0,
1.31914, 2.66147, 0, 0,
0.942568, 0, 0, 0, 0.025507, 0,
0, 0, 0.321429, 0.569141, 1.25274, 1.57719,
0.8158, 1.21805, 0.586239, 0.25427,
1.04436, 0, 0.630725, 0, 0.133801, 0.210693,
0.363026, 0, 0.533426, 0, 1.25926, 0.722707,
0, 1.22031, 1.30117, 0.495867,
0.222187, 0, 0.72725, 0, 0.767003, 0,
0, 0.147835, 0, 0, 0, 0.608758,
0.469394, 0.00720298, 0.927537, 0,
0.856974, 0.424257, 0, 0, 0.937329, 0,
0, 0, 0.476425, 0, 0.566017, 0.418462,
0.141911, 0.996214, 1.13063, 0,
0.967899, 0, 0, 0, 0.0831304, 0,
0, 1.00378, 0, 0, 0, 1.44818,
1.01768, 0.943891, 0.502745, 0,
0.940135, 0, 0, 0, 0, 0,
0, 2.13243, 0, 0.71208, 0.123918, 1.53907,
1.30225, 1.59644, 0.70222, 0,
0.804329, 0, 0.430576, 0, 0.505872, 0.509603,
0.343448, 0, 0.107756, 0.614544, 1.44549, 1.52311,
0.0454298, 0.300267, 0.562784, 0.395095,
0.228154, 0, 0.675323, 0, 1.70536, 0.766217,
0, 0, 0, 0.735363, 0.0759267, 1.91017,
0.941888, 0, 0, 0,
0, 0, 1.5909, 0, 0, 0,
0, 0.5755, 0, 0.184687, 0, 1.56296,
0.625285, 0, 0, 0,
0, 0, 0.0857888, 0, 0, 0,
0, 0.488383, 0.252786, 0, 0, 0,
1.02817, 1.85665, 0, 0,
0.00981836, 0, 1.06371, 0, 0, 0,
0, 0, 0, 0.290445, 0.316406, 0,
0.304161, 1.25079, 0.0707152, 0,
0.986264, 0.309201, 0, 0, 0, 0,
0, 1.64896, 0.346248, 0, 0.918175, 0.78884,
0.524981, 1.92076, 2.07013, 0.333244,
0.415153, 0.210318, 0, 0, 0, 0,
0, 2.02616, 0, 0.728256, 0.84183, 0.0907453,
0.628881, 3.58099, 1.49974, 0};
static std::initializer_list<float> rnn_weights = {
0.461459, 0.153381, 0.529743, -0.00371218, 0.676267, -0.211346,
0.317493, 0.969689, -0.343251, 0.186423, 0.398151, 0.152399,
0.448504, 0.317662, 0.523556, -0.323514, 0.480877, 0.333113,
-0.757714, -0.674487, -0.643585, 0.217766, -0.0251462, 0.79512,
-0.595574, -0.422444, 0.371572, -0.452178, -0.556069, -0.482188,
-0.685456, -0.727851, 0.841829, 0.551535, -0.232336, 0.729158,
-0.00294906, -0.69754, 0.766073, -0.178424, 0.369513, -0.423241,
0.548547, -0.0152023, -0.757482, -0.85491, 0.251331, -0.989183,
0.306261, -0.340716, 0.886103, -0.0726757, -0.723523, -0.784303,
0.0354295, 0.566564, -0.485469, -0.620498, 0.832546, 0.697884,
-0.279115, 0.294415, -0.584313, 0.548772, 0.0648819, 0.968726,
0.723834, -0.0080452, -0.350386, -0.272803, 0.115121, -0.412644,
-0.824713, -0.992843, -0.592904, -0.417893, 0.863791, -0.423461,
-0.147601, -0.770664, -0.479006, 0.654782, 0.587314, -0.639158,
0.816969, -0.337228, 0.659878, 0.73107, 0.754768, -0.337042,
0.0960841, 0.368357, 0.244191, -0.817703, -0.211223, 0.442012,
0.37225, -0.623598, -0.405423, 0.455101, 0.673656, -0.145345,
-0.511346, -0.901675, -0.81252, -0.127006, 0.809865, -0.721884,
0.636255, 0.868989, -0.347973, -0.10179, -0.777449, 0.917274,
0.819286, 0.206218, -0.00785118, 0.167141, 0.45872, 0.972934,
-0.276798, 0.837861, 0.747958, -0.0151566, -0.330057, -0.469077,
0.277308, 0.415818};
static std::initializer_list<float> rnn_recurrent_weights = {
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0.1};
static std::initializer_list<float> rnn_bias = {
0.065691948, -0.69055247, 0.1107955, -0.97084129, -0.23957068, -0.23566568,
-0.389184, 0.47481549, -0.4791103, 0.29931796, 0.10463274, 0.83918178,
0.37197268, 0.61957061, 0.3956964, -0.37609905};
class UnidirectionalRNNOpModel : public SingleOpModel {
public:
UnidirectionalRNNOpModel(
int batches, int sequence_len, int units, int size, bool time_major,
const TensorType& weights = TensorType_FLOAT32,
const TensorType& recurrent_weights = TensorType_FLOAT32,
bool asymmetric_quantize_inputs = false)
: batches_(batches),
sequence_len_(sequence_len),
units_(units),
input_size_(size) {
input_ = AddInput(TensorType_FLOAT32);
weights_ = AddInput(weights);
recurrent_weights_ = AddInput(recurrent_weights);
bias_ = AddInput(TensorType_FLOAT32);
hidden_state_ = AddVariableInput(TensorType_FLOAT32);
output_ = AddOutput(TensorType_FLOAT32);
SetBuiltinOp(BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_RNN,
BuiltinOptions_SequenceRNNOptions,
CreateSequenceRNNOptions(builder_, time_major,
ActivationFunctionType_RELU,
asymmetric_quantize_inputs)
.Union());
if (time_major) {
BuildInterpreter({{sequence_len_, batches_, input_size_},
{units_, input_size_},
{units_, units_},
{units_},
{batches_, units}});
} else {
BuildInterpreter({{batches_, sequence_len_, input_size_},
{units_, input_size_},
{units_, units_},
{units_},
{batches_, units_}});
}
}
void SetBias(std::initializer_list<float> f) { PopulateTensor(bias_, f); }
void SetWeights(std::initializer_list<float> f) {
PopulateTensor(weights_, f);
}
void SetRecurrentWeights(std::initializer_list<float> f) {
PopulateTensor(recurrent_weights_, f);
}
void SetInput(std::initializer_list<float> data) {
PopulateTensor(input_, data);
}
void SetInput(int offset, float* begin, float* end) {
PopulateTensor(input_, offset, begin, end);
}
std::vector<float> GetOutput() { return ExtractVector<float>(output_); }
int input_size() { return input_size_; }
int num_units() { return units_; }
int num_batches() { return batches_; }
int sequence_len() { return sequence_len_; }
protected:
int input_;
int weights_;
int recurrent_weights_;
int bias_;
int hidden_state_;
int output_;
int batches_;
int sequence_len_;
int units_;
int input_size_;
};
class HybridUnidirectionalRNNOpModel : public UnidirectionalRNNOpModel {
public:
HybridUnidirectionalRNNOpModel(int batches, int sequence_len, int units,
int size, bool time_major,
TensorType tensor_type,
bool asymmetric_quantize_inputs)
: UnidirectionalRNNOpModel(batches, sequence_len, units, size, time_major,
tensor_type, tensor_type,
asymmetric_quantize_inputs) {
tensor_type_ = tensor_type;
}
void SetWeights(int weights_idx, const std::vector<float>& f) {
if (tensor_type_ == TensorType_UINT8) {
SymmetricQuantizeAndPopulate(weights_idx, f);
} else {
SignedSymmetricQuantizeAndPopulate(weights_idx, f);
}
}
void SetWeights(std::initializer_list<float> f) { SetWeights(weights_, f); }
void SetRecurrentWeights(std::initializer_list<float> f) {
SetWeights(recurrent_weights_, f);
}
protected:
TensorType tensor_type_;
};
TEST(UnidirectionalRNNOpTest, BlackBoxTest) {
UnidirectionalRNNOpModel rnn(2, 16,
16, 8, false);
rnn.SetWeights(rnn_weights);
rnn.SetBias(rnn_bias);
rnn.SetRecurrentWeights(rnn_recurrent_weights);
const int input_sequence_size = rnn.input_size() * rnn.sequence_len();
float* batch_start = rnn_input;
float* batch_end = batch_start + input_sequence_size;
rnn.SetInput(0, batch_start, batch_end);
rnn.SetInput(input_sequence_size, batch_start, batch_end);
ASSERT_EQ(rnn.Invoke(), kTfLiteOk);
float* golden_start = rnn_golden_output;
float* golden_end = golden_start + rnn.num_units() * rnn.sequence_len();
std::vector<float> expected;
expected.insert(expected.end(), golden_start, golden_end);
expected.insert(expected.end(), golden_start, golden_end);
EXPECT_THAT(rnn.GetOutput(), ElementsAreArray(ArrayFloatNear(expected)));
}
class HybridUnidirectionalRNNOpModelOpTest
: public ::testing::TestWithParam<bool> {};
TEST_P(HybridUnidirectionalRNNOpModelOpTest, BlackBoxTestUint8) {
HybridUnidirectionalRNNOpModel rnn(2, 16,
16, 8,
false, TensorType_UINT8,
GetParam());
rnn.SetWeights(rnn_weights);
rnn.SetBias(rnn_bias);
rnn.SetRecurrentWeights(rnn_recurrent_weights);
const int input_sequence_size = rnn.input_size() * rnn.sequence_len();
float* batch_start = rnn_input;
float* batch_end = batch_start + input_sequence_size;
rnn.SetInput(0, batch_start, batch_end);
rnn.SetInput(input_sequence_size, batch_start, batch_end);
ASSERT_EQ(rnn.Invoke(), kTfLiteOk);
float* golden_start = rnn_golden_output;
float* golden_end = golden_start + rnn.num_units() * rnn.sequence_len();
std::vector<float> expected;
expected.insert(expected.end(), golden_start, golden_end);
expected.insert(expected.end(), golden_start, golden_end);
EXPECT_THAT(rnn.GetOutput(), ElementsAreArray(ArrayFloatNear(
expected, 0.013)));
}
TEST_P(HybridUnidirectionalRNNOpModelOpTest, BlackBoxTestInt8) {
HybridUnidirectionalRNNOpModel rnn(2, 16,
16, 8,
false, TensorType_INT8,
GetParam());
rnn.SetWeights(rnn_weights);
rnn.SetBias(rnn_bias);
rnn.SetRecurrentWeights(rnn_recurrent_weights);
const int input_sequence_size = rnn.input_size() * rnn.sequence_len();
float* batch_start = rnn_input;
float* batch_end = batch_start + input_sequence_size;
rnn.SetInput(0, batch_start, batch_end);
rnn.SetInput(input_sequence_size, batch_start, batch_end);
ASSERT_EQ(rnn.Invoke(), kTfLiteOk);
float* golden_start = rnn_golden_output;
float* golden_end = golden_start + rnn.num_units() * rnn.sequence_len();
std::vector<float> expected;
expected.insert(expected.end(), golden_start, golden_end);
expected.insert(expected.end(), golden_start, golden_end);
EXPECT_THAT(rnn.GetOutput(), ElementsAreArray(ArrayFloatNear(
expected, 0.013)));
}
TEST(UnidirectionalRNNOpTest, TimeMajorBlackBoxTest) {
UnidirectionalRNNOpModel rnn(2, 16,
16, 8,
true);
rnn.SetWeights(rnn_weights);
rnn.SetBias(rnn_bias);
rnn.SetRecurrentWeights(rnn_recurrent_weights);
for (int i = 0; i < rnn.sequence_len(); i++) {
float* batch_start = rnn_input + i * rnn.input_size();
float* batch_end = batch_start + rnn.input_size();
rnn.SetInput(2 * i * rnn.input_size(), batch_start, batch_end);
rnn.SetInput((2 * i + 1) * rnn.input_size(), batch_start, batch_end);
}
ASSERT_EQ(rnn.Invoke(), kTfLiteOk);
std::vector<float> expected;
for (int i = 0; i < rnn.sequence_len(); i++) {
float* golden_batch_start = rnn_golden_output + i * rnn.num_units();
float* golden_batch_end = golden_batch_start + rnn.num_units();
expected.insert(expected.end(), golden_batch_start, golden_batch_end);
expected.insert(expected.end(), golden_batch_start, golden_batch_end);
}
EXPECT_THAT(rnn.GetOutput(), ElementsAreArray(ArrayFloatNear(expected)));
}
TEST_P(HybridUnidirectionalRNNOpModelOpTest, TimeMajorBlackBoxTestUint8) {
HybridUnidirectionalRNNOpModel rnn(2, 16,
16, 8,
true, TensorType_UINT8,
GetParam());
rnn.SetWeights(rnn_weights);
rnn.SetBias(rnn_bias);
rnn.SetRecurrentWeights(rnn_recurrent_weights);
for (int i = 0; i < rnn.sequence_len(); i++) {
float* batch_start = rnn_input + i * rnn.input_size();
float* batch_end = batch_start + rnn.input_size();
rnn.SetInput(2 * i * rnn.input_size(), batch_start, batch_end);
rnn.SetInput((2 * i + 1) * rnn.input_size(), batch_start, batch_end);
}
ASSERT_EQ(rnn.Invoke(), kTfLiteOk);
std::vector<float> expected;
for (int i = 0; i < rnn.sequence_len(); i++) {
float* golden_batch_start = rnn_golden_output + i * rnn.num_units();
float* golden_batch_end = golden_batch_start + rnn.num_units();
expected.insert(expected.end(), golden_batch_start, golden_batch_end);
expected.insert(expected.end(), golden_batch_start, golden_batch_end);
}
EXPECT_THAT(rnn.GetOutput(), ElementsAreArray(ArrayFloatNear(
expected, 0.013)));
}
TEST_P(HybridUnidirectionalRNNOpModelOpTest, TimeMajorBlackBoxTestInt8) {
HybridUnidirectionalRNNOpModel rnn(2, 16,
16, 8,
true, TensorType_INT8,
GetParam());
rnn.SetWeights(rnn_weights);
rnn.SetBias(rnn_bias);
rnn.SetRecurrentWeights(rnn_recurrent_weights);
for (int i = 0; i < rnn.sequence_len(); i++) {
float* batch_start = rnn_input + i * rnn.input_size();
float* batch_end = batch_start + rnn.input_size();
rnn.SetInput(2 * i * rnn.input_size(), batch_start, batch_end);
rnn.SetInput((2 * i + 1) * rnn.input_size(), batch_start, batch_end);
}
ASSERT_EQ(rnn.Invoke(), kTfLiteOk);
std::vector<float> expected;
for (int i = 0; i < rnn.sequence_len(); i++) {
float* golden_batch_start = rnn_golden_output + i * rnn.num_units();
float* golden_batch_end = golden_batch_start + rnn.num_units();
expected.insert(expected.end(), golden_batch_start, golden_batch_end);
expected.insert(expected.end(), golden_batch_start, golden_batch_end);
}
EXPECT_THAT(rnn.GetOutput(), ElementsAreArray(ArrayFloatNear(
expected, 0.013)));
}
INSTANTIATE_TEST_SUITE_P(HybridUnidirectionalRNNOpModelOpTest,
HybridUnidirectionalRNNOpModelOpTest,
::testing::ValuesIn({true, false}));
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/unidirectional_sequence_rnn.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/unidirectional_sequence_rnn_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
3ebea19d-f62a-4d53-8079-fcaa3d63901f | cpp | tensorflow/tensorflow | bidirectional_sequence_lstm | tensorflow/lite/kernels/bidirectional_sequence_lstm.cc | tensorflow/lite/kernels/bidirectional_sequence_lstm_test.cc | #include <math.h>
#include <algorithm>
#include <cstddef>
#include "tensorflow/lite/core/c/builtin_op_data.h"
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/cpu_backend_context.h"
#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/kernels/internal/kernel_utils.h"
#include "tensorflow/lite/kernels/internal/tensor_utils.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/lstm_eval.h"
#include "tensorflow/lite/kernels/op_macros.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace bidirectional_sequence_lstm {
constexpr int kInputTensor = 0;
constexpr int kFwInputToInputWeightsTensor = 1;
constexpr int kFwInputToForgetWeightsTensor = 2;
constexpr int kFwInputToCellWeightsTensor = 3;
constexpr int kFwInputToOutputWeightsTensor = 4;
constexpr int kFwRecurrentToInputWeightsTensor = 5;
constexpr int kFwRecurrentToForgetWeightsTensor = 6;
constexpr int kFwRecurrentToCellWeightsTensor = 7;
constexpr int kFwRecurrentToOutputWeightsTensor = 8;
constexpr int kFwCellToInputWeightsTensor = 9;
constexpr int kFwCellToForgetWeightsTensor = 10;
constexpr int kFwCellToOutputWeightsTensor = 11;
constexpr int kFwInputGateBiasTensor = 12;
constexpr int kFwForgetGateBiasTensor = 13;
constexpr int kFwCellGateBiasTensor = 14;
constexpr int kFwOutputGateBiasTensor = 15;
constexpr int kFwProjectionWeightsTensor = 16;
constexpr int kFwProjectionBiasTensor = 17;
constexpr int kBwInputToInputWeightsTensor = 18;
constexpr int kBwInputToForgetWeightsTensor = 19;
constexpr int kBwInputToCellWeightsTensor = 20;
constexpr int kBwInputToOutputWeightsTensor = 21;
constexpr int kBwRecurrentToInputWeightsTensor = 22;
constexpr int kBwRecurrentToForgetWeightsTensor = 23;
constexpr int kBwRecurrentToCellWeightsTensor = 24;
constexpr int kBwRecurrentToOutputWeightsTensor = 25;
constexpr int kBwCellToInputWeightsTensor = 26;
constexpr int kBwCellToForgetWeightsTensor = 27;
constexpr int kBwCellToOutputWeightsTensor = 28;
constexpr int kBwInputGateBiasTensor = 29;
constexpr int kBwForgetGateBiasTensor = 30;
constexpr int kBwCellGateBiasTensor = 31;
constexpr int kBwOutputGateBiasTensor = 32;
constexpr int kBwProjectionWeightsTensor = 33;
constexpr int kBwProjectionBiasTensor = 34;
constexpr int kFwInputActivationStateTensor = 35;
constexpr int kFwInputCellStateTensor = 36;
constexpr int kBwInputActivationStateTensor = 37;
constexpr int kBwInputCellStateTensor = 38;
constexpr int kAuxInputTensor = 39;
constexpr int kFwAuxInputToInputWeightsTensor = 40;
constexpr int kFwAuxInputToForgetWeightsTensor = 41;
constexpr int kFwAuxInputToCellWeightsTensor = 42;
constexpr int kFwAuxInputToOutputWeightsTensor = 43;
constexpr int kBwAuxInputToInputWeightsTensor = 44;
constexpr int kBwAuxInputToForgetWeightsTensor = 45;
constexpr int kBwAuxInputToCellWeightsTensor = 46;
constexpr int kBwAuxInputToOutputWeightsTensor = 47;
constexpr int kFwOutputTensor = 0;
constexpr int kBwOutputTensor = 1;
enum TemporaryTensor {
kFwScratchBuffer = 0,
kBwScratchBuffer = 1,
kInputQuantized = 2,
kFwActivationStateQuantized = 3,
kBwActivationStateQuantized = 4,
kFwCellStateQuantized = 5,
kBwCellStateQuantized = 6,
kInputScalingFactors = 7,
kAuxInputScalingFactors = 8,
kOutputStateScalingFactors = 9,
kProductScalingFactors = 10,
kRecoveredCellWeights = 11,
kAccumScratchBuffer = 12,
kInputZeroPoints = 13,
kAuxInputZeroPoints = 14,
kOutputStateZeroPoints = 15,
kFwRowSums = 16,
kBwRowSums = 17,
kAuxInputQuantized = 18,
kNumTemporaryTensors = 19,
};
struct OpData {
int scratch_tensor_index;
bool compute_fw_row_sums = false;
bool compute_bw_row_sums = false;
};
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
auto* op_data = new OpData();
context->AddTensors(context, kNumTemporaryTensors,
&op_data->scratch_tensor_index);
return op_data;
}
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<OpData*>(buffer);
}
TfLiteStatus CheckLstmTensorDimensionsAndTypes(
TfLiteContext* context, TfLiteNode* node, int n_input, int n_output,
int n_cell, int input_to_input_weights_tensor,
int input_to_forget_weights_tensor, int input_to_cell_weights_tensor,
int input_to_output_weights_tensor, int recurrent_to_input_weights_tensor,
int recurrent_to_forget_weights_tensor,
int recurrent_to_cell_weights_tensor,
int recurrent_to_output_weights_tensor, int cell_to_input_weights_tensor,
int cell_to_forget_weights_tensor, int cell_to_output_weights_tensor,
int input_gate_bias_tensor, int forget_gate_bias_tensor,
int cell_gate_bias_tensor, int output_gate_bias_tensor,
int projection_weights_tensor, int projection_bias_tensor) {
const auto* params = reinterpret_cast<TfLiteBidirectionalSequenceLSTMParams*>(
node->builtin_data);
TF_LITE_ENSURE(context, params->cell_clip >= 0);
TF_LITE_ENSURE(context, params->proj_clip >= 0);
const TfLiteTensor* input_to_forget_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, input_to_forget_weights_tensor,
&input_to_forget_weights));
TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[1], n_input);
TF_LITE_ENSURE(context, (input_to_forget_weights->type == kTfLiteFloat32) ||
(input_to_forget_weights->type == kTfLiteInt8) ||
(input_to_forget_weights->type == kTfLiteUInt8));
const TfLiteTensor* input_to_input_weights =
GetOptionalInputTensor(context, node, input_to_input_weights_tensor);
if (input_to_input_weights != nullptr) {
TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[1], n_input);
TF_LITE_ENSURE_TYPES_EQ(context, input_to_input_weights->type,
input_to_forget_weights->type);
}
const TfLiteTensor* input_to_cell_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, input_to_cell_weights_tensor,
&input_to_cell_weights));
TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[1], n_input);
TF_LITE_ENSURE_TYPES_EQ(context, input_to_cell_weights->type,
input_to_forget_weights->type);
const TfLiteTensor* input_to_output_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, input_to_output_weights_tensor,
&input_to_output_weights));
TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->data[1], n_input);
TF_LITE_ENSURE_TYPES_EQ(context, input_to_output_weights->type,
input_to_forget_weights->type);
const TfLiteTensor* recurrent_to_input_weights =
GetOptionalInputTensor(context, node, recurrent_to_input_weights_tensor);
if (recurrent_to_input_weights != nullptr) {
TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[0],
n_cell);
TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[1],
n_output);
TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_input_weights->type,
input_to_forget_weights->type);
}
const TfLiteTensor* recurrent_to_forget_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, recurrent_to_forget_weights_tensor,
&recurrent_to_forget_weights));
TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[0],
n_cell);
TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[1],
n_output);
TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_forget_weights->type,
input_to_forget_weights->type);
const TfLiteTensor* recurrent_to_cell_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, recurrent_to_cell_weights_tensor,
&recurrent_to_cell_weights));
TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[1],
n_output);
TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_cell_weights->type,
input_to_forget_weights->type);
const bool cifg_weights_all_or_none =
((input_to_input_weights != nullptr) &&
(recurrent_to_input_weights != nullptr)) ||
((input_to_input_weights == nullptr) &&
(recurrent_to_input_weights == nullptr));
TF_LITE_ENSURE(context, cifg_weights_all_or_none == true);
const TfLiteTensor* cell_to_input_weights =
GetOptionalInputTensor(context, node, cell_to_input_weights_tensor);
if (cell_to_input_weights != nullptr) {
TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->size, 1);
TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_TYPES_EQ(context, cell_to_input_weights->type,
input_to_forget_weights->type);
}
const TfLiteTensor* cell_to_forget_weights =
GetOptionalInputTensor(context, node, cell_to_forget_weights_tensor);
if (cell_to_forget_weights != nullptr) {
TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->size, 1);
TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_TYPES_EQ(context, cell_to_forget_weights->type,
input_to_forget_weights->type);
}
const TfLiteTensor* cell_to_output_weights =
GetOptionalInputTensor(context, node, cell_to_output_weights_tensor);
if (cell_to_output_weights != nullptr) {
TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->size, 1);
TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->data[0], n_cell);
TF_LITE_ENSURE_TYPES_EQ(context, cell_to_output_weights->type,
input_to_forget_weights->type);
}
const bool use_cifg = (input_to_input_weights == nullptr);
const bool peephole_weights_all_or_none =
((cell_to_input_weights != nullptr || use_cifg) &&
(cell_to_forget_weights != nullptr) &&
(cell_to_output_weights != nullptr)) ||
((cell_to_input_weights == nullptr) &&
(cell_to_forget_weights == nullptr) &&
(cell_to_output_weights == nullptr));
TF_LITE_ENSURE(context, peephole_weights_all_or_none == true);
const TfLiteTensor* input_gate_bias =
GetOptionalInputTensor(context, node, input_gate_bias_tensor);
if (use_cifg) {
TF_LITE_ENSURE_EQ(context, input_gate_bias, nullptr);
} else {
TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->size, 1);
TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->data[0], n_cell);
TF_LITE_ENSURE_TYPES_EQ(context, input_gate_bias->type, kTfLiteFloat32);
}
const TfLiteTensor* forget_gate_bias;
TF_LITE_ENSURE_OK(
context,
GetInputSafe(context, node, forget_gate_bias_tensor, &forget_gate_bias));
TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->size, 1);
TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->data[0], n_cell);
TF_LITE_ENSURE_TYPES_EQ(context, forget_gate_bias->type, kTfLiteFloat32);
const TfLiteTensor* cell_gate_bias;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, cell_gate_bias_tensor,
&cell_gate_bias));
TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->size, 1);
TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->data[0], n_cell);
TF_LITE_ENSURE_EQ(context, cell_gate_bias->type, kTfLiteFloat32);
const TfLiteTensor* output_gate_bias;
TF_LITE_ENSURE_OK(
context,
GetInputSafe(context, node, output_gate_bias_tensor, &output_gate_bias));
TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->size, 1);
TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->data[0], n_cell);
TF_LITE_ENSURE_TYPES_EQ(context, output_gate_bias->type, kTfLiteFloat32);
const TfLiteTensor* projection_weights =
GetOptionalInputTensor(context, node, projection_weights_tensor);
if (projection_weights != nullptr) {
TF_LITE_ENSURE_EQ(context, projection_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[0], n_output);
TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[1], n_cell);
TF_LITE_ENSURE_TYPES_EQ(context, projection_weights->type,
input_to_forget_weights->type);
}
const TfLiteTensor* projection_bias =
GetOptionalInputTensor(context, node, projection_bias_tensor);
if (projection_bias != nullptr) {
TF_LITE_ENSURE_EQ(context, projection_bias->dims->size, 1);
TF_LITE_ENSURE_EQ(context, projection_bias->dims->data[0], n_output);
TF_LITE_ENSURE_TYPES_EQ(context, projection_bias->type, kTfLiteFloat32);
}
const bool projecton_tensors_consistent =
((projection_weights != nullptr) || (projection_bias == nullptr));
TF_LITE_ENSURE(context, projecton_tensors_consistent == true);
return kTfLiteOk;
}
TfLiteStatus CheckInputTensorDimensions(TfLiteContext* context,
TfLiteNode* node, int n_input,
int n_output, int n_cell) {
TF_LITE_ENSURE_OK(
context,
CheckLstmTensorDimensionsAndTypes(
context, node, n_input, n_output, n_cell,
kFwInputToInputWeightsTensor, kFwInputToForgetWeightsTensor,
kFwInputToCellWeightsTensor, kFwInputToOutputWeightsTensor,
kFwRecurrentToInputWeightsTensor, kFwRecurrentToForgetWeightsTensor,
kFwRecurrentToCellWeightsTensor, kFwRecurrentToOutputWeightsTensor,
kFwCellToInputWeightsTensor, kFwCellToForgetWeightsTensor,
kFwCellToOutputWeightsTensor, kFwInputGateBiasTensor,
kFwForgetGateBiasTensor, kFwCellGateBiasTensor,
kFwOutputGateBiasTensor, kFwProjectionWeightsTensor,
kFwProjectionBiasTensor));
TF_LITE_ENSURE_OK(
context,
CheckLstmTensorDimensionsAndTypes(
context, node, n_input, n_output, n_cell,
kBwInputToInputWeightsTensor, kBwInputToForgetWeightsTensor,
kBwInputToCellWeightsTensor, kBwInputToOutputWeightsTensor,
kBwRecurrentToInputWeightsTensor, kBwRecurrentToForgetWeightsTensor,
kBwRecurrentToCellWeightsTensor, kBwRecurrentToOutputWeightsTensor,
kBwCellToInputWeightsTensor, kBwCellToForgetWeightsTensor,
kBwCellToOutputWeightsTensor, kBwInputGateBiasTensor,
kBwForgetGateBiasTensor, kBwCellGateBiasTensor,
kBwOutputGateBiasTensor, kBwProjectionWeightsTensor,
kBwProjectionBiasTensor));
return kTfLiteOk;
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* op_data = reinterpret_cast<OpData*>(node->user_data);
const auto* params = reinterpret_cast<TfLiteBidirectionalSequenceLSTMParams*>(
node->builtin_data);
TF_LITE_ENSURE_EQ(context, node->inputs->size, 48);
TF_LITE_ENSURE_EQ(context, node->outputs->size,
params->merge_outputs ? 1 : 2);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, input->dims->size, 3);
const bool time_major = params->time_major;
const int max_time = time_major ? input->dims->data[0] : input->dims->data[1];
const int n_batch = time_major ? input->dims->data[1] : input->dims->data[0];
const int n_input = input->dims->data[2];
const TfLiteTensor* fw_input_to_output_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kFwInputToOutputWeightsTensor,
&fw_input_to_output_weights));
const int n_fw_cell = fw_input_to_output_weights->dims->data[0];
TF_LITE_ENSURE_EQ(context, fw_input_to_output_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, fw_input_to_output_weights->dims->data[1],
n_input);
const TfLiteTensor* bw_input_to_output_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kBwInputToOutputWeightsTensor,
&bw_input_to_output_weights));
const int n_bw_cell = bw_input_to_output_weights->dims->data[0];
TF_LITE_ENSURE_EQ(context, bw_input_to_output_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, bw_input_to_output_weights->dims->data[1],
n_input);
TF_LITE_ENSURE_EQ(context, bw_input_to_output_weights->type,
fw_input_to_output_weights->type);
const TfLiteTensor* fw_recurrent_to_output_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kFwRecurrentToOutputWeightsTensor,
&fw_recurrent_to_output_weights));
TF_LITE_ENSURE_EQ(context, fw_recurrent_to_output_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, fw_recurrent_to_output_weights->dims->data[0],
n_fw_cell);
TF_LITE_ENSURE_EQ(context, fw_recurrent_to_output_weights->type,
fw_input_to_output_weights->type);
const int n_fw_output = fw_recurrent_to_output_weights->dims->data[1];
const TfLiteTensor* bw_recurrent_to_output_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kBwRecurrentToOutputWeightsTensor,
&bw_recurrent_to_output_weights));
TF_LITE_ENSURE_EQ(context, bw_recurrent_to_output_weights->dims->size, 2);
TF_LITE_ENSURE_EQ(context, bw_recurrent_to_output_weights->dims->data[0],
n_bw_cell);
TF_LITE_ENSURE_EQ(context, bw_recurrent_to_output_weights->type,
fw_input_to_output_weights->type);
const int n_bw_output = bw_recurrent_to_output_weights->dims->data[1];
TF_LITE_ENSURE_OK(
context, CheckInputTensorDimensions(context, node, n_input, n_fw_output,
n_fw_cell));
const TfLiteTensor* aux_input =
GetOptionalInputTensor(context, node, kAuxInputTensor);
const TfLiteTensor* fw_aux_input_to_input_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToInputWeightsTensor);
const TfLiteTensor* fw_aux_input_to_forget_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToForgetWeightsTensor);
const TfLiteTensor* fw_aux_input_to_cell_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToCellWeightsTensor);
const TfLiteTensor* fw_aux_input_to_output_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToOutputWeightsTensor);
const TfLiteTensor* bw_aux_input_to_input_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToInputWeightsTensor);
const TfLiteTensor* bw_aux_input_to_forget_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToForgetWeightsTensor);
const TfLiteTensor* bw_aux_input_to_cell_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToCellWeightsTensor);
const TfLiteTensor* bw_aux_input_to_output_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToOutputWeightsTensor);
const bool aux_inputs_weights_all_or_none =
((fw_aux_input_to_cell_weights != nullptr) &&
(fw_aux_input_to_forget_weights != nullptr) &&
(fw_aux_input_to_output_weights != nullptr) &&
(bw_aux_input_to_cell_weights != nullptr) &&
(bw_aux_input_to_forget_weights != nullptr) &&
(bw_aux_input_to_output_weights != nullptr)) ||
((fw_aux_input_to_cell_weights == nullptr) &&
(fw_aux_input_to_forget_weights == nullptr) &&
(fw_aux_input_to_output_weights == nullptr) &&
(bw_aux_input_to_cell_weights == nullptr) &&
(bw_aux_input_to_forget_weights == nullptr) &&
(bw_aux_input_to_output_weights == nullptr));
TF_LITE_ENSURE(context, aux_inputs_weights_all_or_none);
const bool has_aux_input = (fw_aux_input_to_forget_weights != nullptr);
if (has_aux_input) {
TF_LITE_ASSERT_EQ(aux_input->dims->data[0], input->dims->data[0]);
TF_LITE_ASSERT_EQ(aux_input->dims->data[1], input->dims->data[1]);
}
TfLiteTensor* fw_output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kFwOutputTensor, &fw_output));
TfLiteTensor* fw_activation_state =
GetVariableInput(context, node, kFwInputActivationStateTensor);
TF_LITE_ENSURE(context, fw_activation_state != nullptr);
TfLiteTensor* fw_cell_state =
GetVariableInput(context, node, kFwInputCellStateTensor);
TF_LITE_ENSURE(context, fw_cell_state != nullptr);
TF_LITE_ENSURE_EQ(context, NumElements(fw_activation_state),
n_batch * n_fw_output);
TF_LITE_ENSURE_EQ(context, NumElements(fw_cell_state), n_batch * n_fw_cell);
TfLiteIntArray* fw_output_size = TfLiteIntArrayCreate(3);
fw_output_size->data[0] = time_major ? max_time : n_batch;
fw_output_size->data[1] = time_major ? n_batch : max_time;
fw_output_size->data[2] =
params->merge_outputs ? n_bw_output + n_fw_output : n_fw_output;
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, fw_output, fw_output_size));
const bool is_hybrid_op = IsHybridOp(input, fw_input_to_output_weights);
TfLiteIntArrayFree(node->temporaries);
if (is_hybrid_op) {
node->temporaries = TfLiteIntArrayCreate(
has_aux_input ? kNumTemporaryTensors : kNumTemporaryTensors - 1);
} else {
node->temporaries = TfLiteIntArrayCreate(2);
}
node->temporaries->data[kFwScratchBuffer] =
op_data->scratch_tensor_index + kFwScratchBuffer;
TfLiteTensor* fw_scratch_buffer;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, kFwScratchBuffer,
&fw_scratch_buffer));
fw_scratch_buffer->type = input->type;
fw_scratch_buffer->allocation_type = kTfLiteArenaRw;
const TfLiteTensor* fw_input_to_input_weights =
GetOptionalInputTensor(context, node, kFwInputToInputWeightsTensor);
const bool fw_use_cifg = (fw_input_to_input_weights == nullptr);
if (has_aux_input && !fw_use_cifg) {
TF_LITE_ENSURE_EQ(context, fw_aux_input_to_input_weights->dims->data[0],
fw_input_to_input_weights->dims->data[0]);
}
TfLiteIntArray* fw_scratch_buffer_size = TfLiteIntArrayCreate(2);
fw_scratch_buffer_size->data[0] = n_batch;
if (fw_use_cifg) {
fw_scratch_buffer_size->data[1] = n_fw_cell * 4 + 16;
} else {
fw_scratch_buffer_size->data[1] = n_fw_cell * 5 + 16;
}
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, fw_scratch_buffer,
fw_scratch_buffer_size));
TF_LITE_ENSURE_OK(
context, CheckInputTensorDimensions(context, node, n_input, n_bw_output,
n_bw_cell));
TfLiteTensor* bw_activation_state =
GetVariableInput(context, node, kBwInputActivationStateTensor);
TF_LITE_ENSURE(context, bw_activation_state != nullptr);
TfLiteTensor* bw_cell_state =
GetVariableInput(context, node, kBwInputCellStateTensor);
TF_LITE_ENSURE(context, bw_cell_state != nullptr);
if (!params->merge_outputs) {
TfLiteTensor* bw_output;
TF_LITE_ENSURE_OK(
context, GetOutputSafe(context, node, kBwOutputTensor, &bw_output));
TfLiteIntArray* bw_output_size = TfLiteIntArrayCreate(3);
bw_output_size->data[0] = time_major ? max_time : n_batch;
bw_output_size->data[1] = time_major ? n_batch : max_time;
bw_output_size->data[2] = n_bw_output;
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, bw_output, bw_output_size));
}
TF_LITE_ENSURE_EQ(context, NumElements(bw_activation_state),
n_batch * n_bw_output);
TF_LITE_ENSURE_EQ(context, NumElements(bw_cell_state), n_batch * n_bw_cell);
node->temporaries->data[kBwScratchBuffer] =
op_data->scratch_tensor_index + kBwScratchBuffer;
TfLiteTensor* bw_scratch_buffer;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, kBwScratchBuffer,
&bw_scratch_buffer));
bw_scratch_buffer->type = input->type;
bw_scratch_buffer->allocation_type = kTfLiteArenaRw;
const TfLiteTensor* bw_input_to_input_weights =
GetOptionalInputTensor(context, node, kBwInputToInputWeightsTensor);
const bool bw_use_cifg = (bw_input_to_input_weights == nullptr);
if (has_aux_input && !bw_use_cifg) {
TF_LITE_ENSURE_EQ(context, bw_aux_input_to_input_weights->dims->data[0],
bw_input_to_input_weights->dims->data[0]);
}
TfLiteIntArray* bw_scratch_buffer_size = TfLiteIntArrayCreate(2);
bw_scratch_buffer_size->data[0] = n_batch;
if (bw_use_cifg) {
bw_scratch_buffer_size->data[1] = n_bw_cell * 4;
} else {
bw_scratch_buffer_size->data[1] = n_bw_cell * 5;
}
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, bw_scratch_buffer,
bw_scratch_buffer_size));
if (is_hybrid_op) {
op_data->compute_fw_row_sums = true;
op_data->compute_bw_row_sums = true;
node->temporaries->data[kInputQuantized] =
op_data->scratch_tensor_index + kInputQuantized;
TfLiteTensor* input_quantized;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, kInputQuantized,
&input_quantized));
input_quantized->type = fw_input_to_output_weights->type;
input_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {
TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,
input_quantized_size));
}
node->temporaries->data[kFwActivationStateQuantized] =
op_data->scratch_tensor_index + kFwActivationStateQuantized;
TfLiteTensor* fw_activation_state_quantized;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kFwActivationStateQuantized,
&fw_activation_state_quantized));
fw_activation_state_quantized->type = fw_input_to_output_weights->type;
fw_activation_state_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(fw_activation_state_quantized->dims,
fw_activation_state->dims)) {
TfLiteIntArray* fw_activation_state_quantized_size =
TfLiteIntArrayCopy(fw_activation_state->dims);
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, fw_activation_state_quantized,
fw_activation_state_quantized_size));
}
node->temporaries->data[kBwActivationStateQuantized] =
op_data->scratch_tensor_index + kBwActivationStateQuantized;
TfLiteTensor* bw_activation_state_quantized;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kBwActivationStateQuantized,
&bw_activation_state_quantized));
bw_activation_state_quantized->type = fw_input_to_output_weights->type;
bw_activation_state_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(bw_activation_state_quantized->dims,
bw_activation_state->dims)) {
TfLiteIntArray* bw_activation_state_quantized_size =
TfLiteIntArrayCopy(bw_activation_state->dims);
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, bw_activation_state_quantized,
bw_activation_state_quantized_size));
}
node->temporaries->data[kFwCellStateQuantized] =
op_data->scratch_tensor_index + kFwCellStateQuantized;
TfLiteTensor* fw_cell_state_quantized;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kFwCellStateQuantized,
&fw_cell_state_quantized));
fw_cell_state_quantized->type = fw_input_to_output_weights->type;
fw_cell_state_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(fw_cell_state_quantized->dims,
fw_cell_state->dims)) {
TfLiteIntArray* fw_cell_state_quantized_size =
TfLiteIntArrayCopy(fw_cell_state->dims);
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, fw_cell_state_quantized,
fw_cell_state_quantized_size));
}
node->temporaries->data[kBwCellStateQuantized] =
op_data->scratch_tensor_index + kBwCellStateQuantized;
TfLiteTensor* bw_cell_state_quantized;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kBwCellStateQuantized,
&bw_cell_state_quantized));
bw_cell_state_quantized->type = fw_input_to_output_weights->type;
bw_cell_state_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(bw_cell_state_quantized->dims,
bw_cell_state->dims)) {
TfLiteIntArray* bw_cell_state_quantized_size =
TfLiteIntArrayCopy(bw_cell_state->dims);
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, bw_cell_state_quantized,
bw_cell_state_quantized_size));
}
node->temporaries->data[kInputScalingFactors] =
op_data->scratch_tensor_index + kInputScalingFactors;
TfLiteTensor* input_sf;
TF_LITE_ENSURE_OK(
context,
GetTemporarySafe(context, node, kInputScalingFactors, &input_sf));
input_sf->type = kTfLiteFloat32;
input_sf->allocation_type = kTfLiteArenaRw;
int scaling_dims[1] = {n_batch};
if (!TfLiteIntArrayEqualsArray(input_sf->dims, 1, scaling_dims)) {
TfLiteIntArray* input_sf_size = TfLiteIntArrayCreate(1);
input_sf_size->data[0] = n_batch;
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, input_sf, input_sf_size));
}
node->temporaries->data[kAuxInputScalingFactors] =
op_data->scratch_tensor_index + kAuxInputScalingFactors;
TfLiteTensor* aux_input_sf;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kAuxInputScalingFactors,
&aux_input_sf));
aux_input_sf->type = kTfLiteFloat32;
aux_input_sf->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqualsArray(aux_input_sf->dims, 1, scaling_dims)) {
TfLiteIntArray* aux_input_sf_size = TfLiteIntArrayCreate(1);
aux_input_sf_size->data[0] = n_batch;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, aux_input_sf,
aux_input_sf_size));
}
node->temporaries->data[kOutputStateScalingFactors] =
op_data->scratch_tensor_index + kOutputStateScalingFactors;
TfLiteTensor* output_state_sf;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kOutputStateScalingFactors,
&output_state_sf));
output_state_sf->type = kTfLiteFloat32;
output_state_sf->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqualsArray(output_state_sf->dims, 1, scaling_dims)) {
TfLiteIntArray* output_state_sf_size = TfLiteIntArrayCreate(1);
output_state_sf_size->data[0] = n_batch;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_state_sf,
output_state_sf_size));
}
node->temporaries->data[kProductScalingFactors] =
op_data->scratch_tensor_index + kProductScalingFactors;
TfLiteTensor* prod_scaling_factors;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kProductScalingFactors,
&prod_scaling_factors));
prod_scaling_factors->type = kTfLiteFloat32;
prod_scaling_factors->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqualsArray(prod_scaling_factors->dims, 1,
scaling_dims)) {
TfLiteIntArray* prod_scaling_factors_size = TfLiteIntArrayCreate(1);
prod_scaling_factors_size->data[0] = n_batch;
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, prod_scaling_factors,
prod_scaling_factors_size));
}
node->temporaries->data[kRecoveredCellWeights] =
op_data->scratch_tensor_index + kRecoveredCellWeights;
TfLiteTensor* recovered_cell_weights;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kRecoveredCellWeights,
&recovered_cell_weights));
recovered_cell_weights->type = kTfLiteFloat32;
recovered_cell_weights->allocation_type = kTfLiteArenaRw;
int recovered_cell_dims[1] = {n_fw_cell};
if (!TfLiteIntArrayEqualsArray(recovered_cell_weights->dims, 1,
recovered_cell_dims)) {
TfLiteIntArray* recovered_cell_weights_size = TfLiteIntArrayCreate(1);
recovered_cell_weights_size->data[0] = n_fw_cell;
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, recovered_cell_weights,
recovered_cell_weights_size));
}
node->temporaries->data[kAccumScratchBuffer] =
op_data->scratch_tensor_index + kAccumScratchBuffer;
TfLiteTensor* accum_scratch;
TF_LITE_ENSURE_OK(
context,
GetTemporarySafe(context, node, kAccumScratchBuffer, &accum_scratch));
accum_scratch->type = kTfLiteInt32;
accum_scratch->allocation_type = kTfLiteArenaRw;
int n_cell = std::max(n_fw_cell, n_bw_cell);
if (has_aux_input) {
n_cell = std::max(n_cell, fw_aux_input_to_output_weights->dims->data[0]);
n_cell = std::max(n_cell, bw_aux_input_to_output_weights->dims->data[0]);
}
int accum_scratch_dims[2] = {n_cell, n_batch};
if (!TfLiteIntArrayEqualsArray(accum_scratch->dims, 2,
accum_scratch_dims)) {
TfLiteIntArray* accum_size = TfLiteIntArrayCreate(2);
accum_size->data[0] = n_cell;
accum_size->data[1] = n_batch;
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, accum_scratch, accum_size));
}
node->temporaries->data[kInputZeroPoints] =
op_data->scratch_tensor_index + kInputZeroPoints;
TfLiteTensor* input_zp;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kInputZeroPoints, &input_zp));
input_zp->type = kTfLiteFloat32;
input_zp->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqualsArray(input_zp->dims, 1, scaling_dims)) {
TfLiteIntArray* input_zp_size = TfLiteIntArrayCreate(1);
input_zp_size->data[0] = n_batch;
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, input_zp, input_zp_size));
}
node->temporaries->data[kAuxInputZeroPoints] =
op_data->scratch_tensor_index + kAuxInputZeroPoints;
TfLiteTensor* aux_input_zp;
TF_LITE_ENSURE_OK(
context,
GetTemporarySafe(context, node, kAuxInputZeroPoints, &aux_input_zp));
aux_input_zp->type = kTfLiteFloat32;
aux_input_zp->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqualsArray(aux_input_zp->dims, 1, scaling_dims)) {
TfLiteIntArray* aux_input_zp_size = TfLiteIntArrayCreate(1);
aux_input_zp_size->data[0] = n_batch;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, aux_input_zp,
aux_input_zp_size));
}
node->temporaries->data[kOutputStateZeroPoints] =
op_data->scratch_tensor_index + kOutputStateZeroPoints;
TfLiteTensor* output_state_zp;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kOutputStateZeroPoints,
&output_state_zp));
output_state_zp->type = kTfLiteFloat32;
output_state_zp->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqualsArray(output_state_zp->dims, 1, scaling_dims)) {
TfLiteIntArray* output_state_zp_size = TfLiteIntArrayCreate(1);
output_state_zp_size->data[0] = n_batch;
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_state_zp,
output_state_zp_size));
}
int fw_row_sums_rows = fw_use_cifg ? 6 : 8;
if (has_aux_input) {
fw_row_sums_rows += fw_use_cifg ? 3 : 4;
}
const TfLiteTensor* fw_projection_weights =
GetOptionalInputTensor(context, node, kFwProjectionWeightsTensor);
if (fw_projection_weights != nullptr) {
fw_row_sums_rows += ceil(static_cast<float>(n_fw_output) / n_fw_cell);
}
node->temporaries->data[kFwRowSums] =
op_data->scratch_tensor_index + kFwRowSums;
TfLiteTensor* fw_row_sums;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kFwRowSums, &fw_row_sums));
fw_row_sums->type = kTfLiteInt32;
fw_row_sums->allocation_type = kTfLiteArenaRwPersistent;
int fw_row_sums_dims[2] = {fw_row_sums_rows, n_fw_cell};
if (!TfLiteIntArrayEqualsArray(fw_row_sums->dims, 2, fw_row_sums_dims)) {
TfLiteIntArray* fw_hybrid_scratch_size = TfLiteIntArrayCreate(2);
fw_hybrid_scratch_size->data[0] = fw_row_sums_dims[0];
fw_hybrid_scratch_size->data[1] = fw_row_sums_dims[1];
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, fw_row_sums,
fw_hybrid_scratch_size));
}
int bw_row_sums_rows = bw_use_cifg ? 6 : 8;
if (has_aux_input) {
bw_row_sums_rows += bw_use_cifg ? 3 : 4;
}
const TfLiteTensor* bw_projection_weights =
GetOptionalInputTensor(context, node, kBwProjectionWeightsTensor);
if (bw_projection_weights != nullptr) {
bw_row_sums_rows += ceil(static_cast<float>(n_bw_output) / n_bw_cell);
}
node->temporaries->data[kBwRowSums] =
op_data->scratch_tensor_index + kBwRowSums;
TfLiteTensor* bw_row_sums;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kBwRowSums, &bw_row_sums));
bw_row_sums->type = kTfLiteInt32;
bw_row_sums->allocation_type = kTfLiteArenaRwPersistent;
int bw_row_sums_dims[2] = {bw_row_sums_rows, n_bw_cell};
if (!TfLiteIntArrayEqualsArray(bw_row_sums->dims, 2, bw_row_sums_dims)) {
TfLiteIntArray* bw_row_sums_size = TfLiteIntArrayCreate(2);
bw_row_sums_size->data[0] = bw_row_sums_dims[0];
bw_row_sums_size->data[1] = bw_row_sums_dims[1];
TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, bw_row_sums,
bw_row_sums_size));
}
if (has_aux_input) {
node->temporaries->data[kAuxInputQuantized] =
op_data->scratch_tensor_index + kAuxInputQuantized;
TfLiteTensor* aux_input_quantized;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kAuxInputQuantized,
&aux_input_quantized));
aux_input_quantized->type = fw_input_to_output_weights->type;
aux_input_quantized->allocation_type = kTfLiteArenaRw;
if (!TfLiteIntArrayEqual(aux_input_quantized->dims, aux_input->dims)) {
TfLiteIntArray* aux_input_quantized_size =
TfLiteIntArrayCopy(aux_input->dims);
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, aux_input_quantized,
aux_input_quantized_size));
}
}
}
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const auto* params = reinterpret_cast<TfLiteBidirectionalSequenceLSTMParams*>(
node->builtin_data);
auto* op_data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const TfLiteTensor* fw_input_to_input_weights =
GetOptionalInputTensor(context, node, kFwInputToInputWeightsTensor);
const TfLiteTensor* fw_input_to_forget_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kFwInputToForgetWeightsTensor,
&fw_input_to_forget_weights));
const TfLiteTensor* fw_input_to_cell_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kFwInputToCellWeightsTensor,
&fw_input_to_cell_weights));
const TfLiteTensor* fw_input_to_output_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kFwInputToOutputWeightsTensor,
&fw_input_to_output_weights));
const TfLiteTensor* fw_recurrent_to_input_weights =
GetOptionalInputTensor(context, node, kFwRecurrentToInputWeightsTensor);
const TfLiteTensor* fw_recurrent_to_forget_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kFwRecurrentToForgetWeightsTensor,
&fw_recurrent_to_forget_weights));
const TfLiteTensor* fw_recurrent_to_cell_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kFwRecurrentToCellWeightsTensor,
&fw_recurrent_to_cell_weights));
const TfLiteTensor* fw_recurrent_to_output_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kFwRecurrentToOutputWeightsTensor,
&fw_recurrent_to_output_weights));
const TfLiteTensor* fw_cell_to_input_weights =
GetOptionalInputTensor(context, node, kFwCellToInputWeightsTensor);
const TfLiteTensor* fw_cell_to_forget_weights =
GetOptionalInputTensor(context, node, kFwCellToForgetWeightsTensor);
const TfLiteTensor* fw_cell_to_output_weights =
GetOptionalInputTensor(context, node, kFwCellToOutputWeightsTensor);
const TfLiteTensor* fw_input_gate_bias =
GetOptionalInputTensor(context, node, kFwInputGateBiasTensor);
const TfLiteTensor* fw_forget_gate_bias;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kFwForgetGateBiasTensor,
&fw_forget_gate_bias));
const TfLiteTensor* fw_cell_gate_bias;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kFwCellGateBiasTensor,
&fw_cell_gate_bias));
const TfLiteTensor* fw_output_gate_bias;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kFwOutputGateBiasTensor,
&fw_output_gate_bias));
const TfLiteTensor* fw_projection_weights =
GetOptionalInputTensor(context, node, kFwProjectionWeightsTensor);
const TfLiteTensor* fw_projection_bias =
GetOptionalInputTensor(context, node, kFwProjectionBiasTensor);
TfLiteTensor* fw_activation_state =
GetVariableInput(context, node, kFwInputActivationStateTensor);
TFLITE_DCHECK(fw_activation_state != nullptr);
TfLiteTensor* fw_cell_state =
GetVariableInput(context, node, kFwInputCellStateTensor);
TFLITE_DCHECK(fw_cell_state != nullptr);
TfLiteTensor* fw_output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kFwOutputTensor, &fw_output));
const TfLiteTensor* bw_input_to_input_weights =
GetOptionalInputTensor(context, node, kBwInputToInputWeightsTensor);
const TfLiteTensor* bw_input_to_forget_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kBwInputToForgetWeightsTensor,
&bw_input_to_forget_weights));
const TfLiteTensor* bw_input_to_cell_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kBwInputToCellWeightsTensor,
&bw_input_to_cell_weights));
const TfLiteTensor* bw_input_to_output_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kBwInputToOutputWeightsTensor,
&bw_input_to_output_weights));
const TfLiteTensor* bw_recurrent_to_input_weights =
GetOptionalInputTensor(context, node, kBwRecurrentToInputWeightsTensor);
const TfLiteTensor* bw_recurrent_to_forget_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kBwRecurrentToForgetWeightsTensor,
&bw_recurrent_to_forget_weights));
const TfLiteTensor* bw_recurrent_to_cell_weights;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kBwRecurrentToCellWeightsTensor,
&bw_recurrent_to_cell_weights));
const TfLiteTensor* bw_recurrent_to_output_weights;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kBwRecurrentToOutputWeightsTensor,
&bw_recurrent_to_output_weights));
const TfLiteTensor* bw_cell_to_input_weights =
GetOptionalInputTensor(context, node, kBwCellToInputWeightsTensor);
const TfLiteTensor* bw_cell_to_forget_weights =
GetOptionalInputTensor(context, node, kBwCellToForgetWeightsTensor);
const TfLiteTensor* bw_cell_to_output_weights =
GetOptionalInputTensor(context, node, kBwCellToOutputWeightsTensor);
const TfLiteTensor* bw_input_gate_bias =
GetOptionalInputTensor(context, node, kBwInputGateBiasTensor);
const TfLiteTensor* bw_forget_gate_bias;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kBwForgetGateBiasTensor,
&bw_forget_gate_bias));
const TfLiteTensor* bw_cell_gate_bias;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBwCellGateBiasTensor,
&bw_cell_gate_bias));
const TfLiteTensor* bw_output_gate_bias;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kBwOutputGateBiasTensor,
&bw_output_gate_bias));
const TfLiteTensor* bw_projection_weights =
GetOptionalInputTensor(context, node, kBwProjectionWeightsTensor);
const TfLiteTensor* bw_projection_bias =
GetOptionalInputTensor(context, node, kBwProjectionBiasTensor);
TfLiteTensor* bw_activation_state =
GetVariableInput(context, node, kBwInputActivationStateTensor);
TFLITE_DCHECK(bw_activation_state != nullptr);
TfLiteTensor* bw_cell_state =
GetVariableInput(context, node, kBwInputCellStateTensor);
TFLITE_DCHECK(bw_cell_state != nullptr);
TfLiteTensor* bw_output = params->merge_outputs
? nullptr
: GetOutput(context, node, kBwOutputTensor);
TfLiteTensor* fw_scratch_buffer;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, kFwScratchBuffer,
&fw_scratch_buffer));
TfLiteTensor* bw_scratch_buffer;
TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, kBwScratchBuffer,
&bw_scratch_buffer));
const TfLiteTensor* aux_input =
GetOptionalInputTensor(context, node, kAuxInputTensor);
const TfLiteTensor* fw_aux_input_to_input_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToInputWeightsTensor);
const TfLiteTensor* fw_aux_input_to_forget_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToForgetWeightsTensor);
const TfLiteTensor* fw_aux_input_to_cell_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToCellWeightsTensor);
const TfLiteTensor* fw_aux_input_to_output_weights =
GetOptionalInputTensor(context, node, kFwAuxInputToOutputWeightsTensor);
const TfLiteTensor* bw_aux_input_to_input_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToInputWeightsTensor);
const TfLiteTensor* bw_aux_input_to_forget_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToForgetWeightsTensor);
const TfLiteTensor* bw_aux_input_to_cell_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToCellWeightsTensor);
const TfLiteTensor* bw_aux_input_to_output_weights =
GetOptionalInputTensor(context, node, kBwAuxInputToOutputWeightsTensor);
const bool has_previous_bw_output = (aux_input != nullptr);
const bool use_aux_input = (fw_aux_input_to_forget_weights != nullptr);
TfLiteLSTMParams lstm_params = {params->activation, params->cell_clip,
params->proj_clip, kTfLiteLSTMFullKernel,
params->asymmetric_quantize_inputs};
const int bw_output_offset =
params->merge_outputs ? fw_recurrent_to_output_weights->dims->data[1] : 0;
const auto actual_bw_output = params->merge_outputs ? fw_output : bw_output;
const bool time_major = params->time_major;
const bool non_stacking_mode = !use_aux_input && has_previous_bw_output;
const TfLiteTensor* bw_input = non_stacking_mode ? aux_input : input;
const TfLiteTensor* real_aux_input = non_stacking_mode ? nullptr : aux_input;
switch (fw_input_to_output_weights->type) {
case kTfLiteFloat32: {
TfLiteStatus fw_pass_status = lstm_eval::EvalFloat(
input, fw_input_to_input_weights, fw_input_to_forget_weights,
fw_input_to_cell_weights, fw_input_to_output_weights,
fw_recurrent_to_input_weights, fw_recurrent_to_forget_weights,
fw_recurrent_to_cell_weights, fw_recurrent_to_output_weights,
fw_cell_to_input_weights, fw_cell_to_forget_weights,
fw_cell_to_output_weights,
nullptr,
nullptr,
nullptr,
nullptr, real_aux_input,
fw_aux_input_to_input_weights, fw_aux_input_to_forget_weights,
fw_aux_input_to_cell_weights, fw_aux_input_to_output_weights,
fw_input_gate_bias, fw_forget_gate_bias, fw_cell_gate_bias,
fw_output_gate_bias, fw_projection_weights, fw_projection_bias,
&lstm_params,
true, time_major, 0,
fw_scratch_buffer, fw_activation_state, fw_cell_state, fw_output,
false,
false,
false,
false,
CpuBackendContext::GetFromContext(context));
TF_LITE_ENSURE_OK(context, fw_pass_status);
TfLiteStatus bw_pass_status = lstm_eval::EvalFloat(
bw_input, bw_input_to_input_weights, bw_input_to_forget_weights,
bw_input_to_cell_weights, bw_input_to_output_weights,
bw_recurrent_to_input_weights, bw_recurrent_to_forget_weights,
bw_recurrent_to_cell_weights, bw_recurrent_to_output_weights,
bw_cell_to_input_weights, bw_cell_to_forget_weights,
bw_cell_to_output_weights,
nullptr,
nullptr,
nullptr,
nullptr, real_aux_input,
bw_aux_input_to_input_weights, bw_aux_input_to_forget_weights,
bw_aux_input_to_cell_weights, bw_aux_input_to_output_weights,
bw_input_gate_bias, bw_forget_gate_bias, bw_cell_gate_bias,
bw_output_gate_bias, bw_projection_weights, bw_projection_bias,
&lstm_params,
false, time_major, bw_output_offset,
bw_scratch_buffer, bw_activation_state, bw_cell_state,
actual_bw_output,
false,
false,
false,
false,
CpuBackendContext::GetFromContext(context));
TF_LITE_ENSURE_OK(context, bw_pass_status);
return kTfLiteOk;
}
case kTfLiteUInt8:
case kTfLiteInt8: {
TfLiteTensor* input_quantized;
TF_LITE_ENSURE_OK(
context,
GetTemporarySafe(context, node, kInputQuantized, &input_quantized));
TfLiteTensor* fw_activation_state_quantized;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kFwActivationStateQuantized,
&fw_activation_state_quantized));
TfLiteTensor* bw_activation_state_quantized;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kBwActivationStateQuantized,
&bw_activation_state_quantized));
TfLiteTensor* fw_cell_state_quantized;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kFwCellStateQuantized,
&fw_cell_state_quantized));
TfLiteTensor* bw_cell_state_quantized;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kBwCellStateQuantized,
&bw_cell_state_quantized));
TfLiteTensor* prod_scaling_factors;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kProductScalingFactors,
&prod_scaling_factors));
TfLiteTensor* recovered_cell_weights;
TF_LITE_ENSURE_OK(context,
GetTemporarySafe(context, node, kRecoveredCellWeights,
&recovered_cell_weights));
TfLiteTensor* aux_input_quantized =
use_aux_input ? GetTemporary(context, node, kAuxInputQuantized)
: nullptr;
TfLiteTensor* accum_scratch;
TF_LITE_ENSURE_OK(
context,
GetTemporarySafe(context, node, kAccumScratchBuffer, &accum_scratch));
TfLiteTensor* fw_row_sums;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kFwRowSums, &fw_row_sums));
TfLiteTensor* bw_row_sums;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, kBwRowSums, &bw_row_sums));
const int fw_row_sums_size = fw_row_sums->dims->data[0];
const int bw_row_sums_size = bw_row_sums->dims->data[0];
TfLiteStatus fw_pass_status = lstm_eval::EvalHybrid(
input, fw_input_to_input_weights,
nullptr, fw_input_to_forget_weights,
nullptr, fw_input_to_cell_weights,
nullptr, fw_input_to_output_weights,
nullptr,
fw_recurrent_to_input_weights,
nullptr,
fw_recurrent_to_forget_weights,
nullptr,
fw_recurrent_to_cell_weights,
nullptr,
fw_recurrent_to_output_weights,
nullptr,
fw_cell_to_input_weights, fw_cell_to_forget_weights,
fw_cell_to_output_weights,
nullptr,
nullptr,
nullptr,
nullptr, real_aux_input,
fw_aux_input_to_input_weights, fw_aux_input_to_forget_weights,
fw_aux_input_to_cell_weights, fw_aux_input_to_output_weights,
fw_input_gate_bias, fw_forget_gate_bias, fw_cell_gate_bias,
fw_output_gate_bias, fw_projection_weights,
nullptr, fw_projection_bias,
&lstm_params,
true, time_major, 0,
fw_scratch_buffer, GetTemporary(context, node, kInputScalingFactors),
GetTemporary(context, node, kAuxInputScalingFactors),
GetTemporary(context, node, kOutputStateScalingFactors),
prod_scaling_factors, recovered_cell_weights, input_quantized,
aux_input_quantized, fw_activation_state_quantized,
fw_cell_state_quantized, fw_activation_state, fw_cell_state,
accum_scratch, fw_output,
GetTemporary(context, node, kInputZeroPoints),
GetTemporary(context, node, kAuxInputZeroPoints),
GetTemporary(context, node, kOutputStateZeroPoints), fw_row_sums,
fw_row_sums_size, &op_data->compute_fw_row_sums,
false,
false,
false,
false,
CpuBackendContext::GetFromContext(context));
TF_LITE_ENSURE_OK(context, fw_pass_status);
TfLiteStatus bw_pass_status = lstm_eval::EvalHybrid(
bw_input, bw_input_to_input_weights,
nullptr, bw_input_to_forget_weights,
nullptr, bw_input_to_cell_weights,
nullptr, bw_input_to_output_weights,
nullptr,
bw_recurrent_to_input_weights,
nullptr,
bw_recurrent_to_forget_weights,
nullptr,
bw_recurrent_to_cell_weights,
nullptr,
bw_recurrent_to_output_weights,
nullptr,
bw_cell_to_input_weights, bw_cell_to_forget_weights,
bw_cell_to_output_weights,
nullptr,
nullptr,
nullptr,
nullptr, real_aux_input,
bw_aux_input_to_input_weights, bw_aux_input_to_forget_weights,
bw_aux_input_to_cell_weights, bw_aux_input_to_output_weights,
bw_input_gate_bias, bw_forget_gate_bias, bw_cell_gate_bias,
bw_output_gate_bias, bw_projection_weights,
nullptr, bw_projection_bias,
&lstm_params,
false, time_major, bw_output_offset,
bw_scratch_buffer, GetTemporary(context, node, kInputScalingFactors),
GetTemporary(context, node, kAuxInputScalingFactors),
GetTemporary(context, node, kOutputStateScalingFactors),
prod_scaling_factors, recovered_cell_weights, input_quantized,
aux_input_quantized, bw_activation_state_quantized,
bw_cell_state_quantized, bw_activation_state, bw_cell_state,
accum_scratch, actual_bw_output,
GetTemporary(context, node, kInputZeroPoints),
GetTemporary(context, node, kAuxInputZeroPoints),
GetTemporary(context, node, kOutputStateZeroPoints), bw_row_sums,
bw_row_sums_size, &op_data->compute_bw_row_sums,
false,
false,
false,
false,
CpuBackendContext::GetFromContext(context));
TF_LITE_ENSURE_OK(context, bw_pass_status);
return kTfLiteOk;
}
default:
TF_LITE_KERNEL_LOG(context, "Type %s is not currently supported.",
TfLiteTypeGetName(fw_input_to_output_weights->type));
return kTfLiteError;
}
}
}
TfLiteRegistration* Register_BIDIRECTIONAL_SEQUENCE_LSTM() {
static TfLiteRegistration r = {
bidirectional_sequence_lstm::Init, bidirectional_sequence_lstm::Free,
bidirectional_sequence_lstm::Prepare, bidirectional_sequence_lstm::Eval};
return &r;
}
}
}
} | #include <tuple>
#include <vector>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffers.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/schema/schema_generated.h"
namespace tflite {
namespace {
using ::testing::ElementsAreArray;
class BidirectionalLSTMOpModel : public SingleOpModel {
public:
BidirectionalLSTMOpModel(int n_batch, int n_input, int n_cell, int n_output,
int sequence_length, bool use_cifg,
bool use_peephole, bool use_projection_weights,
bool use_projection_bias, bool merge_outputs,
bool use_aux_input, float cell_clip, float proj_clip,
bool quantize_weights, bool time_major,
const std::vector<std::vector<int>>& input_shapes,
bool asymmetric_quantize_inputs = false)
: n_batch_(n_batch),
n_input_(n_input),
n_fw_cell_(n_cell),
n_bw_cell_(n_cell),
n_fw_output_(n_output),
n_bw_output_(n_output),
sequence_length_(sequence_length),
quantize_weights_(quantize_weights) {
input_ = AddInput(TensorType_FLOAT32);
const auto weight_type =
quantize_weights_ ? TensorType_UINT8 : TensorType_FLOAT32;
if (use_cifg) {
fw_input_to_input_weights_ = AddNullInput();
} else {
fw_input_to_input_weights_ = AddInput(weight_type);
}
fw_input_to_forget_weights_ = AddInput(weight_type);
fw_input_to_cell_weights_ = AddInput(weight_type);
fw_input_to_output_weights_ = AddInput(weight_type);
if (use_cifg) {
fw_recurrent_to_input_weights_ = AddNullInput();
} else {
fw_recurrent_to_input_weights_ = AddInput(weight_type);
}
fw_recurrent_to_forget_weights_ = AddInput(weight_type);
fw_recurrent_to_cell_weights_ = AddInput(weight_type);
fw_recurrent_to_output_weights_ = AddInput(weight_type);
if (use_peephole) {
if (use_cifg) {
fw_cell_to_input_weights_ = AddNullInput();
} else {
fw_cell_to_input_weights_ = AddInput(weight_type);
}
fw_cell_to_forget_weights_ = AddInput(weight_type);
fw_cell_to_output_weights_ = AddInput(weight_type);
} else {
fw_cell_to_input_weights_ = AddNullInput();
fw_cell_to_forget_weights_ = AddNullInput();
fw_cell_to_output_weights_ = AddNullInput();
}
if (use_cifg) {
fw_input_gate_bias_ = AddNullInput();
} else {
fw_input_gate_bias_ = AddInput(TensorType_FLOAT32);
}
fw_forget_gate_bias_ = AddInput(TensorType_FLOAT32);
fw_cell_gate_bias_ = AddInput(TensorType_FLOAT32);
fw_output_gate_bias_ = AddInput(TensorType_FLOAT32);
if (use_projection_weights) {
fw_projection_weights_ = AddInput(TensorType_FLOAT32);
if (use_projection_bias) {
fw_projection_bias_ = AddInput(TensorType_FLOAT32);
} else {
fw_projection_bias_ = AddNullInput();
}
} else {
fw_projection_weights_ = AddNullInput();
fw_projection_bias_ = AddNullInput();
}
if (use_cifg) {
bw_input_to_input_weights_ = AddNullInput();
} else {
bw_input_to_input_weights_ = AddInput(weight_type);
}
bw_input_to_forget_weights_ = AddInput(weight_type);
bw_input_to_cell_weights_ = AddInput(weight_type);
bw_input_to_output_weights_ = AddInput(weight_type);
if (use_cifg) {
bw_recurrent_to_input_weights_ = AddNullInput();
} else {
bw_recurrent_to_input_weights_ = AddInput(weight_type);
}
bw_recurrent_to_forget_weights_ = AddInput(weight_type);
bw_recurrent_to_cell_weights_ = AddInput(weight_type);
bw_recurrent_to_output_weights_ = AddInput(weight_type);
if (use_peephole) {
if (use_cifg) {
bw_cell_to_input_weights_ = AddNullInput();
} else {
bw_cell_to_input_weights_ = AddInput(weight_type);
}
bw_cell_to_forget_weights_ = AddInput(weight_type);
bw_cell_to_output_weights_ = AddInput(weight_type);
} else {
bw_cell_to_input_weights_ = AddNullInput();
bw_cell_to_forget_weights_ = AddNullInput();
bw_cell_to_output_weights_ = AddNullInput();
}
if (use_cifg) {
bw_input_gate_bias_ = AddNullInput();
} else {
bw_input_gate_bias_ = AddInput(TensorType_FLOAT32);
}
bw_forget_gate_bias_ = AddInput(TensorType_FLOAT32);
bw_cell_gate_bias_ = AddInput(TensorType_FLOAT32);
bw_output_gate_bias_ = AddInput(TensorType_FLOAT32);
if (use_projection_weights) {
bw_projection_weights_ = AddInput(weight_type);
if (use_projection_bias) {
bw_projection_bias_ = AddInput(TensorType_FLOAT32);
} else {
bw_projection_bias_ = AddNullInput();
}
} else {
bw_projection_weights_ = AddNullInput();
bw_projection_bias_ = AddNullInput();
}
fw_input_activation_state_ = AddVariableInput(
TensorData{TensorType_FLOAT32, {n_fw_output_ * n_batch_}});
fw_input_cell_state_ = AddVariableInput(
TensorData{TensorType_FLOAT32, {n_fw_cell_ * n_batch_}});
bw_input_activation_state_ = AddVariableInput(
TensorData{TensorType_FLOAT32, {n_bw_output_ * n_batch_}});
bw_input_cell_state_ = AddVariableInput(
TensorData{TensorType_FLOAT32, {n_bw_cell_ * n_batch_}});
fw_output_ = AddOutput(TensorType_FLOAT32);
if (!merge_outputs) {
bw_output_ = AddOutput(TensorType_FLOAT32);
}
if (use_aux_input) {
aux_input_ = AddInput(TensorType_FLOAT32);
fw_aux_input_to_input_weights_ = AddInput(weight_type);
fw_aux_input_to_forget_weights_ = AddInput(weight_type);
fw_aux_input_to_cell_weights_ = AddInput(weight_type);
fw_aux_input_to_output_weights_ = AddInput(weight_type);
bw_aux_input_to_input_weights_ = AddInput(weight_type);
bw_aux_input_to_forget_weights_ = AddInput(weight_type);
bw_aux_input_to_cell_weights_ = AddInput(weight_type);
bw_aux_input_to_output_weights_ = AddInput(weight_type);
} else {
aux_input_ = AddNullInput();
fw_aux_input_to_input_weights_ = AddNullInput();
fw_aux_input_to_forget_weights_ = AddNullInput();
fw_aux_input_to_cell_weights_ = AddNullInput();
fw_aux_input_to_output_weights_ = AddNullInput();
bw_aux_input_to_input_weights_ = AddNullInput();
bw_aux_input_to_forget_weights_ = AddNullInput();
bw_aux_input_to_cell_weights_ = AddNullInput();
bw_aux_input_to_output_weights_ = AddNullInput();
}
SetBuiltinOp(
BuiltinOperator_BIDIRECTIONAL_SEQUENCE_LSTM,
BuiltinOptions_BidirectionalSequenceLSTMOptions,
CreateBidirectionalSequenceLSTMOptions(
builder_, ActivationFunctionType_TANH, cell_clip, proj_clip,
merge_outputs, time_major, asymmetric_quantize_inputs)
.Union());
BuildInterpreter(input_shapes);
}
void PopulateWeightTensor(int tensor_id, const std::vector<float>& f) {
if (quantize_weights_) {
SymmetricQuantizeAndPopulate(tensor_id, f);
} else {
PopulateTensor(tensor_id, f);
}
}
void SetInputToInputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_input_to_input_weights_, f);
PopulateWeightTensor(bw_input_to_input_weights_, f);
}
void SetInputToForgetWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_input_to_forget_weights_, f);
PopulateWeightTensor(bw_input_to_forget_weights_, f);
}
void SetInputToCellWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_input_to_cell_weights_, f);
PopulateWeightTensor(bw_input_to_cell_weights_, f);
}
void SetInputToOutputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_input_to_output_weights_, f);
PopulateWeightTensor(bw_input_to_output_weights_, f);
}
void SetRecurrentToInputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_recurrent_to_input_weights_, f);
PopulateWeightTensor(bw_recurrent_to_input_weights_, f);
}
void SetRecurrentToForgetWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_recurrent_to_forget_weights_, f);
PopulateWeightTensor(bw_recurrent_to_forget_weights_, f);
}
void SetRecurrentToCellWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_recurrent_to_cell_weights_, f);
PopulateWeightTensor(bw_recurrent_to_cell_weights_, f);
}
void SetRecurrentToOutputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_recurrent_to_output_weights_, f);
PopulateWeightTensor(bw_recurrent_to_output_weights_, f);
}
void SetCellToInputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_cell_to_input_weights_, f);
PopulateWeightTensor(bw_cell_to_input_weights_, f);
}
void SetCellToForgetWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_cell_to_forget_weights_, f);
PopulateWeightTensor(bw_cell_to_forget_weights_, f);
}
void SetCellToOutputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_cell_to_output_weights_, f);
PopulateWeightTensor(bw_cell_to_output_weights_, f);
}
void SetInputGateBias(const std::vector<float>& f) {
PopulateTensor(fw_input_gate_bias_, f);
PopulateTensor(bw_input_gate_bias_, f);
}
void SetForgetGateBias(const std::vector<float>& f) {
PopulateTensor(fw_forget_gate_bias_, f);
PopulateTensor(bw_forget_gate_bias_, f);
}
void SetCellBias(const std::vector<float>& f) {
PopulateTensor(fw_cell_gate_bias_, f);
PopulateTensor(bw_cell_gate_bias_, f);
}
void SetOutputGateBias(const std::vector<float>& f) {
PopulateTensor(fw_output_gate_bias_, f);
PopulateTensor(bw_output_gate_bias_, f);
}
void SetProjectionWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_projection_weights_, f);
PopulateWeightTensor(bw_projection_weights_, f);
}
void SetProjectionBias(const std::vector<float>& f) {
PopulateTensor(fw_projection_bias_, f);
PopulateTensor(bw_projection_bias_, f);
}
void SetInput(int offset, float* begin, float* end) {
PopulateTensor(input_, offset, begin, end);
}
void SetAuxInput(int offset, float* begin, float* end) {
PopulateTensor(aux_input_, offset, begin, end);
}
void SetAuxInputToInputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_aux_input_to_input_weights_, f);
PopulateWeightTensor(bw_aux_input_to_input_weights_, f);
}
void SetAuxInputToForgetWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_aux_input_to_forget_weights_, f);
PopulateWeightTensor(bw_aux_input_to_forget_weights_, f);
}
void SetAuxInputToCellWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_aux_input_to_cell_weights_, f);
PopulateWeightTensor(bw_aux_input_to_cell_weights_, f);
}
void SetAuxInputToOutputWeights(const std::vector<float>& f) {
PopulateWeightTensor(fw_aux_input_to_output_weights_, f);
PopulateWeightTensor(bw_aux_input_to_output_weights_, f);
}
std::vector<float> GetFwOutput() { return ExtractVector<float>(fw_output_); }
std::vector<float> GetBwOutput() { return ExtractVector<float>(bw_output_); }
int num_inputs() { return n_input_; }
int num_fw_outputs() { return n_fw_output_; }
int num_bw_outputs() { return n_bw_output_; }
int num_fw_cells() { return n_fw_cell_; }
int num_bw_cells() { return n_bw_cell_; }
int num_batches() { return n_batch_; }
int sequence_length() { return sequence_length_; }
private:
int input_;
int fw_input_to_input_weights_;
int fw_input_to_forget_weights_;
int fw_input_to_cell_weights_;
int fw_input_to_output_weights_;
int fw_recurrent_to_input_weights_;
int fw_recurrent_to_forget_weights_;
int fw_recurrent_to_cell_weights_;
int fw_recurrent_to_output_weights_;
int fw_cell_to_input_weights_;
int fw_cell_to_forget_weights_;
int fw_cell_to_output_weights_;
int fw_input_gate_bias_;
int fw_forget_gate_bias_;
int fw_cell_gate_bias_;
int fw_output_gate_bias_;
int fw_projection_weights_;
int fw_projection_bias_;
int bw_input_to_input_weights_;
int bw_input_to_forget_weights_;
int bw_input_to_cell_weights_;
int bw_input_to_output_weights_;
int bw_recurrent_to_input_weights_;
int bw_recurrent_to_forget_weights_;
int bw_recurrent_to_cell_weights_;
int bw_recurrent_to_output_weights_;
int bw_cell_to_input_weights_;
int bw_cell_to_forget_weights_;
int bw_cell_to_output_weights_;
int bw_input_gate_bias_;
int bw_forget_gate_bias_;
int bw_cell_gate_bias_;
int bw_output_gate_bias_;
int bw_projection_weights_;
int bw_projection_bias_;
int fw_input_activation_state_;
int fw_input_cell_state_;
int bw_input_activation_state_;
int bw_input_cell_state_;
int fw_output_;
int bw_output_;
int aux_input_;
int fw_aux_input_to_input_weights_;
int fw_aux_input_to_forget_weights_;
int fw_aux_input_to_cell_weights_;
int fw_aux_input_to_output_weights_;
int bw_aux_input_to_input_weights_;
int bw_aux_input_to_forget_weights_;
int bw_aux_input_to_cell_weights_;
int bw_aux_input_to_output_weights_;
int n_batch_;
int n_input_;
int n_fw_cell_;
int n_bw_cell_;
int n_fw_output_;
int n_bw_output_;
int sequence_length_;
bool quantize_weights_;
};
class LSTMOpTest
: public ::testing::TestWithParam<::testing::tuple<bool, bool>> {};
INSTANTIATE_TEST_SUITE_P(QuantizationOrNot, LSTMOpTest,
::testing::Combine(
::testing::Bool(),
::testing::Bool()));
TEST_P(LSTMOpTest, BlackBoxTestNoCifgNoPeepholeNoProjectionNoClipping) {
const int n_batch = 1;
const int n_input = 2;
const int n_cell = 4;
const int n_output = 4;
const int sequence_length = 3;
auto params = GetParam();
const bool quantize_weights = std::get<0>(params);
const bool asymmetric_quantize_inputs = std::get<1>(params);
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, false,
false, false,
false, false,
false, 0.0,
0.0, quantize_weights, true,
{
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, 0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
},
asymmetric_quantize_inputs);
lstm.SetInputToInputWeights({-0.45018822, -0.02338299, -0.0870589,
-0.34550029, 0.04266912, -0.15680569,
-0.34856534, 0.43890524});
lstm.SetInputToCellWeights({-0.50013041, 0.1370284, 0.11810488, 0.2013163,
-0.20583314, 0.44344562, 0.22077113,
-0.29909778});
lstm.SetInputToForgetWeights({0.09701663, 0.20334584, -0.50592935,
-0.31343272, -0.40032279, 0.44781327,
0.01387155, -0.35593212});
lstm.SetInputToOutputWeights({-0.25065863, -0.28290087, 0.04613829,
0.40525138, 0.44272184, 0.03897077, -0.1556896,
0.19487578});
lstm.SetInputGateBias({0., 0., 0., 0.});
lstm.SetCellBias({0., 0., 0., 0.});
lstm.SetForgetGateBias({1., 1., 1., 1.});
lstm.SetOutputGateBias({0., 0., 0., 0.});
lstm.SetRecurrentToInputWeights(
{-0.0063535, -0.2042388, 0.31454784, -0.35746509, 0.28902304, 0.08183324,
-0.16555229, 0.02286911, -0.13566875, 0.03034258, 0.48091322,
-0.12528998, 0.24077177, -0.51332325, -0.33502164, 0.10629296});
lstm.SetRecurrentToCellWeights(
{-0.3407414, 0.24443203, -0.2078532, 0.26320225, 0.05695659, -0.00123841,
-0.4744786, -0.35869038, -0.06418842, -0.13502428, -0.501764, 0.22830659,
-0.46367589, 0.26016325, -0.03894562, -0.16368064});
lstm.SetRecurrentToForgetWeights(
{-0.48684245, -0.06655136, 0.42224967, 0.2112639, 0.27654213, 0.20864892,
-0.07646349, 0.45877004, 0.00141793, -0.14609534, 0.36447752, 0.09196436,
0.28053468, 0.01560611, -0.20127171, -0.01140004});
lstm.SetRecurrentToOutputWeights(
{0.43385774, -0.17194885, 0.2718237, 0.09215671, 0.24107647, -0.39835793,
0.18212086, 0.01301402, 0.48572797, -0.50656658, 0.20047462, -0.20607421,
-0.51818722, -0.15390486, 0.0468148, 0.39922136});
static float lstm_input[] = {2., 3., 3., 4., 1., 1.};
static float lstm_fw_golden_output[] = {
-0.02973187, 0.1229473, 0.20885126, -0.15358765,
-0.03716109, 0.12507336, 0.41193449, -0.20860538,
-0.15053082, 0.09120187, 0.24278517, -0.12222792};
static float lstm_bw_golden_output[] = {
-0.0806187, 0.139077, 0.400476, -0.197842, -0.0332076, 0.123838,
0.309777, -0.17621, -0.0490733, 0.0739237, 0.067706, -0.0208124};
float* batch0_start = lstm_input;
float* batch0_end = batch0_start + lstm.num_inputs() * lstm.sequence_length();
lstm.SetInput(0, batch0_start, batch0_end);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
float* fw_golden_start = lstm_fw_golden_output;
float* fw_golden_end =
fw_golden_start + lstm.num_fw_outputs() * lstm.sequence_length();
std::vector<float> fw_expected;
fw_expected.insert(fw_expected.end(), fw_golden_start, fw_golden_end);
EXPECT_THAT(lstm.GetFwOutput(),
ElementsAreArray(
ArrayFloatNear(fw_expected, quantize_weights ? 1e-2 : 1e-5)));
float* bw_golden_start = lstm_bw_golden_output;
float* bw_golden_end =
bw_golden_start + lstm.num_bw_outputs() * lstm.sequence_length();
std::vector<float> bw_expected;
bw_expected.insert(bw_expected.end(), bw_golden_start, bw_golden_end);
EXPECT_THAT(lstm.GetBwOutput(),
ElementsAreArray(
ArrayFloatNear(bw_expected, quantize_weights ? 1e-2 : 1e-5)));
}
TEST_P(LSTMOpTest, BlackBoxTestMergedOutput) {
const int n_batch = 2;
const int n_input = 2;
const int n_cell = 4;
const int n_output = 4;
const int sequence_length = 3;
auto params = GetParam();
const bool quantize_weights = std::get<0>(params);
const bool asymmetric_quantize_inputs = std::get<1>(params);
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, false,
false, false,
false, true,
false, 0.0,
0.0, quantize_weights, true,
{
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, 0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
},
asymmetric_quantize_inputs);
lstm.SetInputToInputWeights({-0.45018822, -0.02338299, -0.0870589,
-0.34550029, 0.04266912, -0.15680569,
-0.34856534, 0.43890524});
lstm.SetInputToCellWeights({-0.50013041, 0.1370284, 0.11810488, 0.2013163,
-0.20583314, 0.44344562, 0.22077113,
-0.29909778});
lstm.SetInputToForgetWeights({0.09701663, 0.20334584, -0.50592935,
-0.31343272, -0.40032279, 0.44781327,
0.01387155, -0.35593212});
lstm.SetInputToOutputWeights({-0.25065863, -0.28290087, 0.04613829,
0.40525138, 0.44272184, 0.03897077, -0.1556896,
0.19487578});
lstm.SetInputGateBias({0., 0., 0., 0.});
lstm.SetCellBias({0., 0., 0., 0.});
lstm.SetForgetGateBias({1., 1., 1., 1.});
lstm.SetOutputGateBias({0., 0., 0., 0.});
lstm.SetRecurrentToInputWeights(
{-0.0063535, -0.2042388, 0.31454784, -0.35746509, 0.28902304, 0.08183324,
-0.16555229, 0.02286911, -0.13566875, 0.03034258, 0.48091322,
-0.12528998, 0.24077177, -0.51332325, -0.33502164, 0.10629296});
lstm.SetRecurrentToCellWeights(
{-0.3407414, 0.24443203, -0.2078532, 0.26320225, 0.05695659, -0.00123841,
-0.4744786, -0.35869038, -0.06418842, -0.13502428, -0.501764, 0.22830659,
-0.46367589, 0.26016325, -0.03894562, -0.16368064});
lstm.SetRecurrentToForgetWeights(
{-0.48684245, -0.06655136, 0.42224967, 0.2112639, 0.27654213, 0.20864892,
-0.07646349, 0.45877004, 0.00141793, -0.14609534, 0.36447752, 0.09196436,
0.28053468, 0.01560611, -0.20127171, -0.01140004});
lstm.SetRecurrentToOutputWeights(
{0.43385774, -0.17194885, 0.2718237, 0.09215671, 0.24107647, -0.39835793,
0.18212086, 0.01301402, 0.48572797, -0.50656658, 0.20047462, -0.20607421,
-0.51818722, -0.15390486, 0.0468148, 0.39922136});
static float lstm_input[] = {2., 3., 2., 3., 3., 4., 3., 4., 1., 1., 1., 1.};
static float lstm_fw_golden_output[] = {
-0.02973187, 0.1229473, 0.20885126, -0.15358765, -0.02973187,
0.1229473, 0.20885126, -0.15358765, -0.03716109, 0.12507336,
0.41193449, -0.20860538, -0.03716109, 0.12507336, 0.41193449,
-0.20860538, -0.15053082, 0.09120187, 0.24278517, -0.12222792,
-0.15053082, 0.09120187, 0.24278517, -0.12222792};
static float lstm_bw_golden_output[] = {
-0.0806187, 0.139077, 0.400476, -0.197842, -0.0806187, 0.139077,
0.400476, -0.197842, -0.0332076, 0.123838, 0.309777, -0.17621,
-0.0332076, 0.123838, 0.309777, -0.17621, -0.0490733, 0.0739237,
0.067706, -0.0208124, -0.0490733, 0.0739237, 0.067706, -0.0208124};
float* batch0_start = lstm_input;
float* batch0_end = batch0_start + lstm.num_inputs() * lstm.num_batches() *
lstm.sequence_length();
lstm.SetInput(0, batch0_start, batch0_end);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
std::vector<float> merged_expected;
for (int k = 0; k < lstm.sequence_length() * lstm.num_batches(); k++) {
merged_expected.insert(
merged_expected.end(),
lstm_fw_golden_output + k * lstm.num_fw_outputs(),
lstm_fw_golden_output + (k + 1) * lstm.num_fw_outputs());
merged_expected.insert(
merged_expected.end(),
lstm_bw_golden_output + k * lstm.num_bw_outputs(),
lstm_bw_golden_output + (k + 1) * lstm.num_bw_outputs());
}
EXPECT_THAT(lstm.GetFwOutput(),
ElementsAreArray(ArrayFloatNear(merged_expected,
quantize_weights ? 1e-2 : 1e-5)));
}
TEST(LSTMOpTest, BlackBoxTestNoCifgNoPeepholeNoProjectionNoClippingReverse) {
const int n_batch = 1;
const int n_input = 2;
const int n_cell = 4;
const int n_output = 4;
const int sequence_length = 3;
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, false,
false, false,
false, false,
false, 0.0,
0.0, false, true,
{
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, 0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
});
lstm.SetInputToInputWeights({-0.45018822, -0.02338299, -0.0870589,
-0.34550029, 0.04266912, -0.15680569,
-0.34856534, 0.43890524});
lstm.SetInputToCellWeights({-0.50013041, 0.1370284, 0.11810488, 0.2013163,
-0.20583314, 0.44344562, 0.22077113,
-0.29909778});
lstm.SetInputToForgetWeights({0.09701663, 0.20334584, -0.50592935,
-0.31343272, -0.40032279, 0.44781327,
0.01387155, -0.35593212});
lstm.SetInputToOutputWeights({-0.25065863, -0.28290087, 0.04613829,
0.40525138, 0.44272184, 0.03897077, -0.1556896,
0.19487578});
lstm.SetInputGateBias({0., 0., 0., 0.});
lstm.SetCellBias({0., 0., 0., 0.});
lstm.SetForgetGateBias({1., 1., 1., 1.});
lstm.SetOutputGateBias({0., 0., 0., 0.});
lstm.SetRecurrentToInputWeights(
{-0.0063535, -0.2042388, 0.31454784, -0.35746509, 0.28902304, 0.08183324,
-0.16555229, 0.02286911, -0.13566875, 0.03034258, 0.48091322,
-0.12528998, 0.24077177, -0.51332325, -0.33502164, 0.10629296});
lstm.SetRecurrentToCellWeights(
{-0.3407414, 0.24443203, -0.2078532, 0.26320225, 0.05695659, -0.00123841,
-0.4744786, -0.35869038, -0.06418842, -0.13502428, -0.501764, 0.22830659,
-0.46367589, 0.26016325, -0.03894562, -0.16368064});
lstm.SetRecurrentToForgetWeights(
{-0.48684245, -0.06655136, 0.42224967, 0.2112639, 0.27654213, 0.20864892,
-0.07646349, 0.45877004, 0.00141793, -0.14609534, 0.36447752, 0.09196436,
0.28053468, 0.01560611, -0.20127171, -0.01140004});
lstm.SetRecurrentToOutputWeights(
{0.43385774, -0.17194885, 0.2718237, 0.09215671, 0.24107647, -0.39835793,
0.18212086, 0.01301402, 0.48572797, -0.50656658, 0.20047462, -0.20607421,
-0.51818722, -0.15390486, 0.0468148, 0.39922136});
static float lstm_input_reversed[] = {1., 1., 3., 4., 2., 3.};
static float lstm_fw_golden_output[] = {
-0.02973187, 0.1229473, 0.20885126, -0.15358765,
-0.03716109, 0.12507336, 0.41193449, -0.20860538,
-0.15053082, 0.09120187, 0.24278517, -0.12222792};
static float lstm_bw_golden_output[] = {
-0.0806187, 0.139077, 0.400476, -0.197842, -0.0332076, 0.123838,
0.309777, -0.17621, -0.0490733, 0.0739237, 0.067706, -0.0208124};
float* batch0_start = lstm_input_reversed;
float* batch0_end = batch0_start + lstm.num_inputs() * lstm.sequence_length();
lstm.SetInput(0, batch0_start, batch0_end);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
std::vector<float> fw_expected;
for (int s = 0; s < lstm.sequence_length(); s++) {
float* fw_golden_start = lstm_fw_golden_output + s * lstm.num_fw_outputs();
float* fw_golden_end = fw_golden_start + lstm.num_fw_outputs();
fw_expected.insert(fw_expected.begin(), fw_golden_start, fw_golden_end);
}
EXPECT_THAT(lstm.GetBwOutput(),
ElementsAreArray(ArrayFloatNear(fw_expected)));
std::vector<float> bw_expected;
for (int s = 0; s < lstm.sequence_length(); s++) {
float* bw_golden_start = lstm_bw_golden_output + s * lstm.num_bw_outputs();
float* bw_golden_end = bw_golden_start + lstm.num_bw_outputs();
bw_expected.insert(bw_expected.begin(), bw_golden_start, bw_golden_end);
}
EXPECT_THAT(lstm.GetFwOutput(),
ElementsAreArray(ArrayFloatNear(bw_expected)));
}
TEST(LSTMOpTest, BlackBoxTestWithCifgWithPeepholeNoProjectionNoClipping) {
const int n_batch = 1;
const int n_input = 2;
const int n_cell = 4;
const int n_output = 4;
const int sequence_length = 3;
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, true,
true, false,
false, false,
false, 0.0,
0.0, false, true,
{
{sequence_length, n_batch, n_input},
{0, 0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{0, 0},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{n_cell},
{n_cell},
{0},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{0, 0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{0, 0},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{n_cell},
{n_cell},
{0},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, 0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
});
lstm.SetInputToCellWeights({-0.49770179, -0.27711356, -0.09624726, 0.05100781,
0.04717243, 0.48944736, -0.38535351,
-0.17212132});
lstm.SetInputToForgetWeights({-0.55291498, -0.42866567, 0.13056988,
-0.3633365, -0.22755712, 0.28253698, 0.24407166,
0.33826375});
lstm.SetInputToOutputWeights({0.10725588, -0.02335852, -0.55932593,
-0.09426838, -0.44257352, 0.54939759,
0.01533556, 0.42751634});
lstm.SetCellBias({0., 0., 0., 0.});
lstm.SetForgetGateBias({1., 1., 1., 1.});
lstm.SetOutputGateBias({0., 0., 0., 0.});
lstm.SetRecurrentToCellWeights(
{0.54066205, -0.32668582, -0.43562764, -0.56094903, 0.42957711,
0.01841056, -0.32764608, -0.33027974, -0.10826075, 0.20675004,
0.19069612, -0.03026325, -0.54532051, 0.33003211, 0.44901288,
0.21193194});
lstm.SetRecurrentToForgetWeights(
{-0.13832897, -0.0515101, -0.2359007, -0.16661474, -0.14340827,
0.36986142, 0.23414481, 0.55899, 0.10798943, -0.41174671, 0.17751795,
-0.34484994, -0.35874045, -0.11352962, 0.27268326, 0.54058349});
lstm.SetRecurrentToOutputWeights(
{0.41613156, 0.42610586, -0.16495961, -0.5663873, 0.30579174, -0.05115908,
-0.33941799, 0.23364776, 0.11178309, 0.09481031, -0.26424935, 0.46261835,
0.50248802, 0.26114327, -0.43736315, 0.33149987});
lstm.SetCellToForgetWeights(
{0.47485286, -0.51955009, -0.24458408, 0.31544167});
lstm.SetCellToOutputWeights(
{-0.17135078, 0.82760304, 0.85573703, -0.77109635});
static float lstm_input[] = {2., 3., 3., 4., 1., 1.};
static float lstm_fw_golden_output[] = {
-0.36444446, -0.00352185, 0.12886585, -0.05163646,
-0.42312205, -0.01218222, 0.24201041, -0.08124574,
-0.358325, -0.04621704, 0.21641694, -0.06471302};
static float lstm_bw_golden_output[] = {
-0.401685, -0.0232794, 0.288642, -0.123074, -0.42915, -0.00871577,
0.20912, -0.103567, -0.166398, -0.00486649, 0.0697471, -0.0537578};
float* batch0_start = lstm_input;
float* batch0_end = batch0_start + lstm.num_inputs() * lstm.sequence_length();
lstm.SetInput(0, batch0_start, batch0_end);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
float* fw_golden_start = lstm_fw_golden_output;
float* fw_golden_end =
fw_golden_start + lstm.num_fw_outputs() * lstm.sequence_length();
std::vector<float> fw_expected;
fw_expected.insert(fw_expected.end(), fw_golden_start, fw_golden_end);
EXPECT_THAT(lstm.GetFwOutput(),
ElementsAreArray(ArrayFloatNear(fw_expected)));
float* bw_golden_start = lstm_bw_golden_output;
float* bw_golden_end =
bw_golden_start + lstm.num_bw_outputs() * lstm.sequence_length();
std::vector<float> bw_expected;
bw_expected.insert(bw_expected.end(), bw_golden_start, bw_golden_end);
EXPECT_THAT(lstm.GetBwOutput(),
ElementsAreArray(ArrayFloatNear(bw_expected)));
}
TEST(LSTMOpTest,
BlackBoxTestWithCifgWithPeepholeNoProjectionNoClippingReversed) {
const int n_batch = 1;
const int n_input = 2;
const int n_cell = 4;
const int n_output = 4;
const int sequence_length = 3;
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, true,
true, false,
false, false,
false, 0.0,
0.0, false, true,
{
{sequence_length, n_batch, n_input},
{0, 0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{0, 0},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{n_cell},
{n_cell},
{0},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{0, 0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{0, 0},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{n_cell},
{n_cell},
{0},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, 0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
});
lstm.SetInputToCellWeights({-0.49770179, -0.27711356, -0.09624726, 0.05100781,
0.04717243, 0.48944736, -0.38535351,
-0.17212132});
lstm.SetInputToForgetWeights({-0.55291498, -0.42866567, 0.13056988,
-0.3633365, -0.22755712, 0.28253698, 0.24407166,
0.33826375});
lstm.SetInputToOutputWeights({0.10725588, -0.02335852, -0.55932593,
-0.09426838, -0.44257352, 0.54939759,
0.01533556, 0.42751634});
lstm.SetCellBias({0., 0., 0., 0.});
lstm.SetForgetGateBias({1., 1., 1., 1.});
lstm.SetOutputGateBias({0., 0., 0., 0.});
lstm.SetRecurrentToCellWeights(
{0.54066205, -0.32668582, -0.43562764, -0.56094903, 0.42957711,
0.01841056, -0.32764608, -0.33027974, -0.10826075, 0.20675004,
0.19069612, -0.03026325, -0.54532051, 0.33003211, 0.44901288,
0.21193194});
lstm.SetRecurrentToForgetWeights(
{-0.13832897, -0.0515101, -0.2359007, -0.16661474, -0.14340827,
0.36986142, 0.23414481, 0.55899, 0.10798943, -0.41174671, 0.17751795,
-0.34484994, -0.35874045, -0.11352962, 0.27268326, 0.54058349});
lstm.SetRecurrentToOutputWeights(
{0.41613156, 0.42610586, -0.16495961, -0.5663873, 0.30579174, -0.05115908,
-0.33941799, 0.23364776, 0.11178309, 0.09481031, -0.26424935, 0.46261835,
0.50248802, 0.26114327, -0.43736315, 0.33149987});
lstm.SetCellToForgetWeights(
{0.47485286, -0.51955009, -0.24458408, 0.31544167});
lstm.SetCellToOutputWeights(
{-0.17135078, 0.82760304, 0.85573703, -0.77109635});
static float lstm_input_reversed[] = {1., 1., 3., 4., 2., 3.};
static float lstm_fw_golden_output[] = {
-0.36444446, -0.00352185, 0.12886585, -0.05163646,
-0.42312205, -0.01218222, 0.24201041, -0.08124574,
-0.358325, -0.04621704, 0.21641694, -0.06471302};
static float lstm_bw_golden_output[] = {
-0.401685, -0.0232794, 0.288642, -0.123074, -0.42915, -0.00871577,
0.20912, -0.103567, -0.166398, -0.00486649, 0.0697471, -0.0537578};
float* batch0_start = lstm_input_reversed;
float* batch0_end = batch0_start + lstm.num_inputs() * lstm.sequence_length();
lstm.SetInput(0, batch0_start, batch0_end);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
std::vector<float> fw_expected;
for (int s = 0; s < lstm.sequence_length(); s++) {
float* fw_golden_start = lstm_fw_golden_output + s * lstm.num_fw_outputs();
float* fw_golden_end = fw_golden_start + lstm.num_fw_outputs();
fw_expected.insert(fw_expected.begin(), fw_golden_start, fw_golden_end);
}
EXPECT_THAT(lstm.GetBwOutput(),
ElementsAreArray(ArrayFloatNear(fw_expected)));
std::vector<float> bw_expected;
for (int s = 0; s < lstm.sequence_length(); s++) {
float* bw_golden_start = lstm_bw_golden_output + s * lstm.num_bw_outputs();
float* bw_golden_end = bw_golden_start + lstm.num_bw_outputs();
bw_expected.insert(bw_expected.begin(), bw_golden_start, bw_golden_end);
}
EXPECT_THAT(lstm.GetFwOutput(),
ElementsAreArray(ArrayFloatNear(bw_expected)));
}
TEST(LSTMOpTest, BlackBoxTestWithPeepholeWithProjectionNoClipping) {
const int n_batch = 2;
const int n_input = 5;
const int n_cell = 20;
const int n_output = 16;
const int sequence_length = 4;
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, false,
true, true,
false, false,
false, 0.0,
0.0, false, true,
{
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_output, n_cell},
{0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_output, n_cell},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, 0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
});
lstm.SetInputToInputWeights(
{0.021393683, 0.06124551, 0.046905167, -0.014657677, -0.03149463,
0.09171803, 0.14647801, 0.10797193, -0.0057968358, 0.0019193048,
-0.2726754, 0.10154029, -0.018539885, 0.080349885, -0.10262385,
-0.022599787, -0.09121155, -0.008675967, -0.045206103, -0.0821282,
-0.008045952, 0.015478081, 0.055217247, 0.038719587, 0.044153627,
-0.06453243, 0.05031825, -0.046935108, -0.008164439, 0.014574226,
-0.1671009, -0.15519552, -0.16819797, -0.13971269, -0.11953059,
0.25005487, -0.22790983, 0.009855087, -0.028140958, -0.11200698,
0.11295408, -0.0035217577, 0.054485075, 0.05184695, 0.064711206,
0.10989193, 0.11674786, 0.03490607, 0.07727357, 0.11390585,
-0.1863375, -0.1034451, -0.13945189, -0.049401227, -0.18767063,
0.042483903, 0.14233552, 0.13832581, 0.18350165, 0.14545603,
-0.028545704, 0.024939531, 0.050929718, 0.0076203286, -0.0029723682,
-0.042484224, -0.11827596, -0.09171104, -0.10808628, -0.16327988,
-0.2273378, -0.0993647, -0.017155107, 0.0023917493, 0.049272764,
0.0038534778, 0.054764505, 0.089753784, 0.06947234, 0.08014476,
-0.04544234, -0.0497073, -0.07135631, -0.048929106, -0.004042012,
-0.009284026, 0.018042054, 0.0036860977, -0.07427302, -0.11434604,
-0.018995456, 0.031487543, 0.012834908, 0.019977754, 0.044256654,
-0.39292613, -0.18519334, -0.11651281, -0.06809892, 0.011373677});
lstm.SetInputToForgetWeights(
{-0.0018401089, -0.004852237, 0.03698424, 0.014181704, 0.028273236,
-0.016726194, -0.05249759, -0.10204261, 0.00861066, -0.040979505,
-0.009899187, 0.01923892, -0.028177269, -0.08535103, -0.14585495,
0.10662567, -0.01909731, -0.017883534, -0.0047269356, -0.045103323,
0.0030784295, 0.076784775, 0.07463696, 0.094531395, 0.0814421,
-0.12257899, -0.033945758, -0.031303465, 0.045630626, 0.06843887,
-0.13492945, -0.012480007, -0.0811829, -0.07224499, -0.09628791,
0.045100946, 0.0012300825, 0.013964662, 0.099372394, 0.02543059,
0.06958324, 0.034257296, 0.0482646, 0.06267997, 0.052625068,
0.12784666, 0.07077897, 0.025725935, 0.04165009, 0.07241905,
0.018668644, -0.037377294, -0.06277783, -0.08833636, -0.040120605,
-0.011405586, -0.007808335, -0.010301386, -0.005102167, 0.027717464,
0.05483423, 0.11449111, 0.11289652, 0.10939839, 0.13396506,
-0.08402166, -0.01901462, -0.044678304, -0.07720565, 0.014350063,
-0.11757958, -0.0652038, -0.08185733, -0.076754324, -0.092614375,
0.10405491, 0.052960336, 0.035755895, 0.035839386, -0.012540553,
0.036881298, 0.02913376, 0.03420159, 0.05448447, -0.054523353,
0.02582715, 0.02327355, -0.011857179, -0.0011980024, -0.034641717,
-0.026125094, -0.17582615, -0.15923657, -0.27486774, -0.0006143371,
0.0001771948, -8.470171e-05, 0.02651807, 0.045790765, 0.06956496});
lstm.SetInputToCellWeights(
{-0.04580283, -0.09549462, -0.032418985, -0.06454633,
-0.043528453, 0.043018587, -0.049152344, -0.12418144,
-0.078985475, -0.07596889, 0.019484362, -0.11434962,
-0.0074034138, -0.06314844, -0.092981495, 0.0062155537,
-0.025034338, -0.0028890965, 0.048929527, 0.06235075,
0.10665918, -0.032036792, -0.08505916, -0.10843358,
-0.13002433, -0.036816437, -0.02130134, -0.016518239,
0.0047691227, -0.0025825808, 0.066017866, 0.029991534,
-0.10652836, -0.1037554, -0.13056071, -0.03266643,
-0.033702414, -0.006473424, -0.04611692, 0.014419339,
-0.025174323, 0.0396852, 0.081777506, 0.06157468,
0.10210095, -0.009658194, 0.046511717, 0.03603906,
0.0069369148, 0.015960095, -0.06507666, 0.09551598,
0.053568836, 0.06408714, 0.12835667, -0.008714329,
-0.20211966, -0.12093674, 0.029450472, 0.2849013,
-0.029227901, 0.1164364, -0.08560263, 0.09941786,
-0.036999565, -0.028842626, -0.0033637602, -0.017012902,
-0.09720865, -0.11193351, -0.029155117, -0.017936034,
-0.009768936, -0.04223324, -0.036159635, 0.06505112,
-0.021742892, -0.023377212, -0.07221364, -0.06430552,
0.05453865, 0.091149814, 0.06387331, 0.007518393,
0.055960953, 0.069779344, 0.046411168, 0.10509911,
0.07463894, 0.0075130584, 0.012850982, 0.04555431,
0.056955688, 0.06555285, 0.050801456, -0.009862683,
0.00826772, -0.026555609, -0.0073611983, -0.0014897042});
lstm.SetInputToOutputWeights(
{-0.0998932, -0.07201956, -0.052803773, -0.15629593, -0.15001918,
-0.07650751, 0.02359855, -0.075155355, -0.08037709, -0.15093534,
0.029517552, -0.04751393, 0.010350531, -0.02664851, -0.016839722,
-0.023121163, 0.0077019283, 0.012851257, -0.05040649, -0.0129761,
-0.021737747, -0.038305793, -0.06870586, -0.01481247, -0.001285394,
0.10124236, 0.083122835, 0.053313006, -0.062235646, -0.075637154,
-0.027833903, 0.029774971, 0.1130802, 0.09218906, 0.09506135,
-0.086665764, -0.037162706, -0.038880914, -0.035832845, -0.014481564,
-0.09825003, -0.12048569, -0.097665586, -0.05287633, -0.0964047,
-0.11366429, 0.035777505, 0.13568819, 0.052451383, 0.050649304,
0.05798951, -0.021852335, -0.099848844, 0.014740475, -0.078897946,
0.04974699, 0.014160473, 0.06973932, 0.04964942, 0.033364646,
0.08190124, 0.025535367, 0.050893165, 0.048514254, 0.06945813,
-0.078907564, -0.06707616, -0.11844508, -0.09986688, -0.07509403,
0.06263226, 0.14925587, 0.20188436, 0.12098451, 0.14639415,
0.0015017595, -0.014267382, -0.03417257, 0.012711468, 0.0028300495,
-0.024758482, -0.05098548, -0.0821182, 0.014225672, 0.021544158,
0.08949725, 0.07505268, -0.0020780868, 0.04908258, 0.06476295,
-0.022907063, 0.027562456, 0.040185735, 0.019567577, -0.015598739,
-0.049097303, -0.017121866, -0.083368234, -0.02332002, -0.0840956});
lstm.SetInputGateBias(
{0.02234832, 0.14757581, 0.18176508, 0.10380666, 0.053110216,
-0.06928846, -0.13942584, -0.11816189, 0.19483899, 0.03652339,
-0.10250295, 0.036714908, -0.18426876, 0.036065217, 0.21810818,
0.02383196, -0.043370757, 0.08690144, -0.04444982, 0.00030581196});
lstm.SetForgetGateBias({0.035185695, -0.042891346, -0.03032477, 0.23027696,
0.11098921, 0.15378423, 0.09263801, 0.09790885,
0.09508917, 0.061199076, 0.07665568, -0.015443159,
-0.03499149, 0.046190713, 0.08895977, 0.10899629,
0.40694186, 0.06030037, 0.012413437, -0.06108739});
lstm.SetCellBias({-0.024379363, 0.0055531194, 0.23377132, 0.033463873,
-0.1483596, -0.10639995, -0.091433935, 0.058573797,
-0.06809782, -0.07889636, -0.043246906, -0.09829136,
-0.4279842, 0.034901652, 0.18797937, 0.0075234566,
0.016178843, 0.1749513, 0.13975595, 0.92058027});
lstm.SetOutputGateBias(
{0.046159424, -0.0012809046, 0.03563469, 0.12648113, 0.027195795,
0.35373217, -0.018957434, 0.008907322, -0.0762701, 0.12018895,
0.04216877, 0.0022856654, 0.040952638, 0.3147856, 0.08225149,
-0.057416286, -0.14995944, -0.008040261, 0.13208859, 0.029760877});
lstm.SetRecurrentToInputWeights(
{-0.001374326, -0.078856036, 0.10672688, 0.029162422,
-0.11585556, 0.02557986, -0.13446963, -0.035785314,
-0.01244275, 0.025961924, -0.02337298, -0.044228926,
-0.055839065, -0.046598054, -0.010546039, -0.06900766,
0.027239809, 0.022582639, -0.013296484, -0.05459212,
0.08981, -0.045407712, 0.08682226, -0.06867011,
-0.14390695, -0.02916037, 0.000996957, 0.091420636,
0.14283475, -0.07390571, -0.06402044, 0.062524505,
-0.093129106, 0.04860203, -0.08364217, -0.08119002,
0.009352075, 0.22920375, 0.0016303885, 0.11583097,
-0.13732095, 0.012405723, -0.07551853, 0.06343048,
0.12162708, -0.031923793, -0.014335606, 0.01790974,
-0.10650317, -0.0724401, 0.08554849, -0.05727212,
0.06556731, -0.042729504, -0.043227166, 0.011683251,
-0.013082158, -0.029302018, -0.010899579, -0.062036745,
-0.022509435, -0.00964907, -0.01567329, 0.04260106,
-0.07787477, -0.11576462, 0.017356863, 0.048673786,
-0.017577527, -0.05527947, -0.082487635, -0.040137455,
-0.10820036, -0.04666372, 0.022746278, -0.07851417,
0.01068115, 0.032956902, 0.022433773, 0.0026891115,
0.08944216, -0.0685835, 0.010513544, 0.07228705,
0.02032331, -0.059686817, -0.0005566496, -0.086984694,
0.040414046, -0.1380399, 0.094208956, -0.05722982,
0.012092817, -0.04989123, -0.086576, -0.003399834,
-0.04696032, -0.045747425, 0.10091314, 0.048676282,
-0.029037097, 0.031399418, -0.0040285117, 0.047237843,
0.09504992, 0.041799378, -0.049185462, -0.031518843,
-0.10516937, 0.026374253, 0.10058866, -0.0033195973,
-0.041975245, 0.0073591834, 0.0033782164, -0.004325073,
-0.10167381, 0.042500053, -0.01447153, 0.06464186,
-0.017142897, 0.03312627, 0.009205989, 0.024138335,
-0.011337001, 0.035530265, -0.010912711, 0.0706555,
-0.005894094, 0.051841937, -0.1401738, -0.02351249,
0.0365468, 0.07590991, 0.08838724, 0.021681072,
-0.10086113, 0.019608743, -0.06195883, 0.077335775,
0.023646897, -0.095322326, 0.02233014, 0.09756986,
-0.048691444, -0.009579111, 0.07595467, 0.11480546,
-0.09801813, 0.019894179, 0.08502348, 0.004032281,
0.037211012, 0.068537936, -0.048005626, -0.091520436,
-0.028379958, -0.01556313, 0.06554592, -0.045599163,
-0.01672207, -0.020169014, -0.011877351, -0.20212261,
0.010889619, 0.0047078193, 0.038385306, 0.08540671,
-0.017140968, -0.0035865551, 0.016678626, 0.005633034,
0.015963363, 0.00871737, 0.060130805, 0.028611384,
0.10109069, -0.015060172, -0.07894427, 0.06401885,
0.011584063, -0.024466386, 0.0047652307, -0.09041358,
0.030737216, -0.0046374933, 0.14215417, -0.11823516,
0.019899689, 0.006106124, -0.027092824, 0.0786356,
0.05052217, -0.058925, -0.011402121, -0.024987547,
-0.0013661642, -0.06832946, -0.015667673, -0.1083353,
-0.00096863037, -0.06988685, -0.053350925, -0.027275559,
-0.033664223, -0.07978348, -0.025200296, -0.017207067,
-0.058403496, -0.055697463, 0.005798788, 0.12965427,
-0.062582195, 0.0013350133, -0.10482091, 0.0379771,
0.072521195, -0.0029455067, -0.13797039, -0.03628521,
0.013806405, -0.017858358, -0.01008298, -0.07700066,
-0.017081132, 0.019358726, 0.0027079724, 0.004635139,
0.062634714, -0.02338735, -0.039547626, -0.02050681,
0.03385117, -0.083611414, 0.002862572, -0.09421313,
0.058618143, -0.08598433, 0.00972939, 0.023867095,
-0.053934585, -0.023203006, 0.07452513, -0.048767887,
-0.07314807, -0.056307215, -0.10433547, -0.06440842,
0.04328182, 0.04389765, -0.020006588, -0.09076438,
-0.11652589, -0.021705797, 0.03345259, -0.010329105,
-0.025767034, 0.013057034, -0.07316461, -0.10145612,
0.06358255, 0.18531723, 0.07759293, 0.12006465,
0.1305557, 0.058638252, -0.03393652, 0.09622831,
-0.16253184, -2.4580743e-06, 0.079869635, -0.070196845,
-0.005644518, 0.06857898, -0.12598175, -0.035084512,
0.03156317, -0.12794146, -0.031963028, 0.04692781,
0.030070418, 0.0071660685, -0.095516115, -0.004643372,
0.040170413, -0.062104587, -0.0037324072, 0.0554317,
0.08184801, -0.019164372, 0.06791302, 0.034257166,
-0.10307039, 0.021943003, 0.046745934, 0.0790918,
-0.0265588, -0.007824208, 0.042546265, -0.00977924,
-0.0002440307, -0.017384544, -0.017990116, 0.12252321,
-0.014512694, -0.08251313, 0.08861942, 0.13589665,
0.026351685, 0.012641483, 0.07466548, 0.044301085,
-0.045414884, -0.051112458, 0.03444247, -0.08502782,
-0.04106223, -0.028126027, 0.028473156, 0.10467447});
lstm.SetRecurrentToForgetWeights(
{-0.057784554, -0.026057621, -0.068447545, -0.022581743,
0.14811787, 0.10826372, 0.09471067, 0.03987225,
-0.0039523416, 0.00030638507, 0.053185795, 0.10572994,
0.08414449, -0.022036452, -0.00066928595, -0.09203576,
0.032950465, -0.10985798, -0.023809856, 0.0021431844,
-0.02196096, -0.00326074, 0.00058621005, -0.074678116,
-0.06193199, 0.055729095, 0.03736828, 0.020123724,
0.061878487, -0.04729229, 0.034919553, -0.07585433,
-0.04421272, -0.044019096, 0.085488975, 0.04058006,
-0.06890133, -0.030951202, -0.024628663, -0.07672815,
0.034293607, 0.08556707, -0.05293577, -0.033561368,
-0.04899627, 0.0241671, 0.015736353, -0.095442444,
-0.029564252, 0.016493602, -0.035026584, 0.022337519,
-0.026871363, 0.004780428, 0.0077918363, -0.03601621,
0.016435321, -0.03263031, -0.09543275, -0.047392778,
0.013454138, 0.028934088, 0.01685226, -0.086110644,
-0.046250615, -0.01847454, 0.047608484, 0.07339695,
0.034546845, -0.04881143, 0.009128804, -0.08802852,
0.03761666, 0.008096139, -0.014454086, 0.014361001,
-0.023502491, -0.0011840804, -0.07607001, 0.001856849,
-0.06509276, -0.006021153, -0.08570962, -0.1451793,
0.060212336, 0.055259194, 0.06974018, 0.049454916,
-0.027794661, -0.08077226, -0.016179763, 0.1169753,
0.17213494, -0.0056326236, -0.053934924, -0.0124349,
-0.11520337, 0.05409887, 0.088759385, 0.0019655675,
0.0042065294, 0.03881498, 0.019844765, 0.041858196,
-0.05695512, 0.047233116, 0.038937137, -0.06542224,
0.014429736, -0.09719407, 0.13908425, -0.05379757,
0.012321099, 0.082840554, -0.029899208, 0.044217527,
0.059855383, 0.07711018, -0.045319796, 0.0948846,
-0.011724666, -0.0033288454, -0.033542685, -0.04764985,
-0.13873616, 0.040668588, 0.034832682, -0.015319203,
-0.018715994, 0.046002675, 0.0599172, -0.043107376,
0.0294216, -0.002314414, -0.022424703, 0.0030315618,
0.0014641669, 0.0029166266, -0.11878115, 0.013738511,
0.12375372, -0.0006038222, 0.029104086, 0.087442465,
0.052958444, 0.07558703, 0.04817258, 0.044462286,
-0.015213451, -0.08783778, -0.0561384, -0.003008196,
0.047060397, -0.002058388, 0.03429439, -0.018839769,
0.024734668, 0.024614193, -0.042046934, 0.09597743,
-0.0043254104, 0.04320769, 0.0064070094, -0.0019131786,
-0.02558259, -0.022822596, -0.023273505, -0.02464396,
-0.10991725, -0.006240552, 0.0074488563, 0.024044557,
0.04383914, -0.046476185, 0.028658995, 0.060410924,
0.050786525, 0.009452605, -0.0073054377, -0.024810238,
0.0052906186, 0.0066939713, -0.0020913032, 0.014515517,
0.015898481, 0.021362653, -0.030262267, 0.016587038,
-0.011442813, 0.041154444, -0.007631438, -0.03423484,
-0.010977775, 0.036152758, 0.0066366293, 0.11915515,
0.02318443, -0.041350313, 0.021485701, -0.10906167,
-0.028218046, -0.00954771, 0.020531068, -0.11995105,
-0.03672871, 0.024019798, 0.014255957, -0.05221243,
-0.00661567, -0.04630967, 0.033188973, 0.10107534,
-0.014027541, 0.030796422, -0.10270911, -0.035999842,
0.15443139, 0.07684145, 0.036571592, -0.035900835,
-0.0034699554, 0.06209149, 0.015920248, -0.031122351,
-0.03858649, 0.01849943, 0.13872518, 0.01503974,
0.069941424, -0.06948533, -0.0088794185, 0.061282158,
-0.047401894, 0.03100163, -0.041533746, -0.10430945,
0.044574402, -0.01425562, -0.024290353, 0.034563623,
0.05866852, 0.023947537, -0.09445152, 0.035450947,
0.02247216, -0.0042998926, 0.061146557, -0.10250651,
0.020881841, -0.06747029, 0.10062043, -0.0023941975,
0.03532124, -0.016341697, 0.09685456, -0.016764693,
0.051808182, 0.05875331, -0.04536488, 0.001626336,
-0.028892258, -0.01048663, -0.009793449, -0.017093895,
0.010987891, 0.02357273, -0.00010856845, 0.0099760275,
-0.001845119, -0.03551521, 0.0018358806, 0.05763657,
-0.01769146, 0.040995963, 0.02235177, -0.060430344,
0.11475477, -0.023854522, 0.10071741, 0.0686208,
-0.014250481, 0.034261297, 0.047418304, 0.08562733,
-0.030519066, 0.0060542435, 0.014653856, -0.038836084,
0.04096551, 0.032249358, -0.08355519, -0.026823482,
0.056386515, -0.010401743, -0.028396193, 0.08507674,
0.014410365, 0.020995233, 0.17040324, 0.11511526,
0.02459721, 0.0066619175, 0.025853224, -0.023133837,
-0.081302024, 0.017264642, -0.009585969, 0.09491168,
-0.051313367, 0.054532815, -0.014298593, 0.10657464,
0.007076659, 0.10964551, 0.0409152, 0.008275321,
-0.07283536, 0.07937492, 0.04192024, -0.1075027});
lstm.SetRecurrentToCellWeights(
{-0.037322544, 0.018592842, 0.0056175636, -0.06253426,
0.055647098, -0.05713207, -0.05626563, 0.005559383,
0.03375411, -0.025757805, -0.088049285, 0.06017052,
-0.06570978, 0.007384076, 0.035123326, -0.07920549,
0.053676967, 0.044480428, -0.07663568, 0.0071805613,
0.08089997, 0.05143358, 0.038261272, 0.03339287,
-0.027673481, 0.044746667, 0.028349208, 0.020090483,
-0.019443132, -0.030755889, -0.0040000007, 0.04465846,
-0.021585021, 0.0031670958, 0.0053199246, -0.056117613,
-0.10893326, 0.076739706, -0.08509834, -0.027997585,
0.037871376, 0.01449768, -0.09002357, -0.06111149,
-0.046195522, 0.0422062, -0.005683705, -0.1253618,
-0.012925729, -0.04890792, 0.06985068, 0.037654128,
0.03398274, -0.004781977, 0.007032333, -0.031787455,
0.010868644, -0.031489216, 0.09525667, 0.013939797,
0.0058680447, 0.0167067, 0.02668468, -0.04797466,
-0.048885044, -0.12722108, 0.035304096, 0.06554885,
0.00972396, -0.039238118, -0.05159735, -0.11329045,
0.1613692, -0.03750952, 0.06529313, -0.071974665,
-0.11769596, 0.015524369, -0.0013754242, -0.12446318,
0.02786344, -0.014179351, 0.005264273, 0.14376344,
0.015983658, 0.03406988, -0.06939408, 0.040699873,
0.02111075, 0.09669095, 0.041345075, -0.08316494,
-0.07684199, -0.045768797, 0.032298047, -0.041805092,
0.0119405, 0.0061010392, 0.12652606, 0.0064572375,
-0.024950314, 0.11574242, 0.04508852, -0.04335324,
0.06760663, -0.027437469, 0.07216407, 0.06977076,
-0.05438599, 0.034033038, -0.028602652, 0.05346137,
0.043184172, -0.037189785, 0.10420091, 0.00882477,
-0.054019816, -0.074273005, -0.030617684, -0.0028467078,
0.024302477, -0.0038869337, 0.005332455, 0.0013399826,
0.04361412, -0.007001822, 0.09631092, -0.06702025,
-0.042049985, -0.035070654, -0.04103342, -0.10273396,
0.0544271, 0.037184782, -0.13150354, -0.0058036847,
-0.008264958, 0.042035464, 0.05891794, 0.029673764,
0.0063542654, 0.044788733, 0.054816857, 0.062257513,
-0.00093483756, 0.048938446, -0.004952862, -0.007730018,
-0.04043371, -0.017094059, 0.07229206, -0.023670016,
-0.052195564, -0.025616996, -0.01520939, 0.045104615,
-0.007376126, 0.003533447, 0.006570588, 0.056037236,
0.12436656, 0.051817212, 0.028532185, -0.08686856,
0.11868599, 0.07663395, -0.07323171, 0.03463402,
-0.050708205, -0.04458982, -0.11590894, 0.021273347,
0.1251325, -0.15313013, -0.12224372, 0.17228661,
0.023029093, 0.086124025, 0.006445803, -0.03496501,
0.028332196, 0.04449512, -0.042436164, -0.026587414,
-0.006041347, -0.09292539, -0.05678812, 0.03897832,
0.09465633, 0.008115513, -0.02171956, 0.08304309,
0.071401566, 0.019622514, 0.032163795, -0.004167056,
0.02295182, 0.030739572, 0.056506045, 0.004612461,
0.06524936, 0.059999723, 0.046395954, -0.0045512207,
-0.1335546, -0.030136576, 0.11584653, -0.014678886,
0.0020118146, -0.09688814, -0.0790206, 0.039770417,
-0.0329582, 0.07922767, 0.029322514, 0.026405897,
0.04207835, -0.07073373, 0.063781224, 0.0859677,
-0.10925287, -0.07011058, 0.048005477, 0.03438226,
-0.09606514, -0.006669445, -0.043381985, 0.04240257,
-0.06955775, -0.06769346, 0.043903265, -0.026784198,
-0.017840602, 0.024307009, -0.040079936, -0.019946516,
0.045318738, -0.12233574, 0.026170589, 0.0074471775,
0.15978073, 0.10185836, 0.10298046, -0.015476589,
-0.039390966, -0.072174534, 0.0739445, -0.1211869,
-0.0347889, -0.07943156, 0.014809798, -0.12412325,
-0.0030663363, 0.039695457, 0.0647603, -0.08291318,
-0.018529687, -0.004423833, 0.0037507233, 0.084633216,
-0.01514876, -0.056505352, -0.012800942, -0.06994386,
0.012962922, -0.031234352, 0.07029052, 0.016418684,
0.03618972, 0.055686004, -0.08663945, -0.017404709,
-0.054761406, 0.029065743, 0.052404847, 0.020238016,
0.0048197987, -0.0214882, 0.07078733, 0.013016777,
0.06262858, 0.009184685, 0.020785125, -0.043904778,
-0.0270329, -0.03299152, -0.060088247, -0.015162964,
-0.001828936, 0.12642565, -0.056757294, 0.013586685,
0.09232601, -0.035886683, 0.06000002, 0.05229691,
-0.052580316, -0.082029596, -0.010794592, 0.012947712,
-0.036429964, -0.085508935, -0.13127148, -0.017744139,
0.031502828, 0.036232427, -0.031581745, 0.023051167,
-0.05325106, -0.03421577, 0.028793324, -0.034633752,
-0.009881397, -0.043551125, -0.018609839, 0.0019097115,
-0.008799762, 0.056595087, 0.0022273948, 0.055752404});
lstm.SetRecurrentToOutputWeights({
0.025825322, -0.05813119, 0.09495884, -0.045984812, -0.01255415,
-0.0026479573, -0.08196161, -0.054914974, -0.0046604523, -0.029587349,
-0.044576716, -0.07480124, -0.082868785, 0.023254942, 0.027502948,
-0.0039728214, -0.08683098, -0.08116779, -0.014675607, -0.037924774,
-0.023314456, -0.007401714, -0.09255757, 0.029460307, -0.08829125,
-0.005139627, -0.08989442, -0.0555066, 0.13596267, -0.025062224,
-0.048351806, -0.03850004, 0.07266485, -0.022414139, 0.05940088,
0.075114764, 0.09597592, -0.010211725, -0.0049794707, -0.011523867,
-0.025980417, 0.072999895, 0.11091378, -0.081685916, 0.014416728,
0.043229222, 0.034178585, -0.07530371, 0.035837382, -0.085607,
-0.007721233, -0.03287832, -0.043848954, -0.06404588, -0.06632928,
-0.073643476, 0.008214239, -0.045984086, 0.039764922, 0.03474462,
0.060612556, -0.080590084, 0.049127717, 0.04151091, -0.030063879,
0.008801774, -0.023021035, -0.019558564, 0.05158114, -0.010947698,
-0.011825728, 0.0075720972, 0.0699727, -0.0039981045, 0.069350146,
0.08799282, 0.016156472, 0.035502106, 0.11695009, 0.006217345,
0.13392477, -0.037875112, 0.025745004, 0.08940699, -0.00924166,
0.0046702605, -0.036598757, -0.08811812, 0.10522024, -0.032441203,
0.008176899, -0.04454919, 0.07058152, 0.0067963637, 0.039206743,
0.03259838, 0.03725492, -0.09515802, 0.013326398, -0.052055415,
-0.025676316, 0.03198509, -0.015951829, -0.058556724, 0.036879618,
0.043357447, 0.028362012, -0.05908629, 0.0059240665, -0.04995891,
-0.019187413, 0.0276265, -0.01628143, 0.0025863599, 0.08800015,
0.035250366, -0.022165963, -0.07328642, -0.009415526, -0.07455109,
0.11690406, 0.0363299, 0.07411125, 0.042103454, -0.009660886,
0.019076364, 0.018299393, -0.046004917, 0.08891175, 0.0431396,
-0.026327137, -0.051502608, 0.08979574, -0.051670972, 0.04940282,
-0.07491107, -0.021240504, 0.022596184, -0.034280192, 0.060163025,
-0.058211457, -0.051837247, -0.01349775, -0.04639988, -0.035936575,
-0.011681591, 0.064818054, 0.0073146066, -0.021745546, -0.043124277,
-0.06471268, -0.07053354, -0.029321948, -0.05330136, 0.016933719,
-0.053782392, 0.13747959, -0.1361751, -0.11569455, 0.0033329215,
0.05693899, -0.053219706, 0.063698, 0.07977434, -0.07924483,
0.06936997, 0.0034815092, -0.007305279, -0.037325785, -0.07251102,
-0.033633437, -0.08677009, 0.091591336, -0.14165086, 0.021752775,
0.019683983, 0.0011612234, -0.058154266, 0.049996935, 0.0288841,
-0.0024567875, -0.14345716, 0.010955264, -0.10234828, 0.1183656,
-0.0010731248, -0.023590032, -0.072285876, -0.0724771, -0.026382286,
-0.0014920527, 0.042667855, 0.0018776858, 0.02986552, 0.009814309,
0.0733756, 0.12289186, 0.018043943, -0.0458958, 0.049412545,
0.033632483, 0.05495232, 0.036686596, -0.013781798, -0.010036754,
0.02576849, -0.08307328, 0.010112348, 0.042521734, -0.05869831,
-0.071689695, 0.03876447, -0.13275425, -0.0352966, -0.023077697,
0.10285965, 0.084736146, 0.15568255, -0.00040734606, 0.027835453,
-0.10292561, -0.032401145, 0.10053256, -0.026142767, -0.08271222,
-0.0030240538, -0.016368777, 0.1070414, 0.042672627, 0.013456989,
-0.0437609, -0.022309763, 0.11576483, 0.04108048, 0.061026827,
-0.0190714, -0.0869359, 0.037901703, 0.0610107, 0.07202949,
0.01675338, 0.086139716, -0.08795751, -0.014898893, -0.023771819,
-0.01965048, 0.007955471, -0.043740474, 0.03346837, -0.10549954,
0.090567775, 0.042013682, -0.03176985, 0.12569028, -0.02421228,
-0.029526481, 0.023851605, 0.031539805, 0.05292009, -0.02344001,
-0.07811758, -0.08834428, 0.10094801, 0.16594367, -0.06861939,
-0.021256343, -0.041093912, -0.06669611, 0.035498552, 0.021757556,
-0.09302526, -0.015403468, -0.06614931, -0.051798206, -0.013874718,
0.03630673, 0.010412845, -0.08077351, 0.046185967, 0.0035662893,
0.03541868, -0.094149634, -0.034814864, 0.003128424, -0.020674974,
-0.03944324, -0.008110165, -0.11113267, 0.08484226, 0.043586485,
0.040582247, 0.0968012, -0.065249965, -0.028036479, 0.0050708856,
0.0017462453, 0.0326779, 0.041296225, 0.09164146, -0.047743853,
-0.015952192, -0.034451712, 0.084197424, -0.05347844, -0.11768019,
0.085926116, -0.08251791, -0.045081906, 0.0948852, 0.068401024,
0.024856757, 0.06978981, -0.057309967, -0.012775832, -0.0032452994,
0.01977615, -0.041040014, -0.024264973, 0.063464895, 0.05431621,
});
lstm.SetCellToInputWeights(
{0.040369894, 0.030746894, 0.24704495, 0.018586371, -0.037586458,
-0.15312155, -0.11812848, -0.11465643, 0.20259799, 0.11418174,
-0.10116027, -0.011334949, 0.12411352, -0.076769054, -0.052169047,
0.21198851, -0.38871562, -0.09061183, -0.09683246, -0.21929175});
lstm.SetCellToForgetWeights(
{-0.01998659, -0.15568835, -0.24248174, -0.012770197, 0.041331276,
-0.072311886, -0.052123554, -0.0066330447, -0.043891653, 0.036225766,
-0.047248036, 0.021479502, 0.033189066, 0.11952997, -0.020432774,
0.64658105, -0.06650122, -0.03467612, 0.095340036, 0.23647355});
lstm.SetCellToOutputWeights(
{0.08286371, -0.08261836, -0.51210177, 0.002913762, 0.17764764,
-0.5495371, -0.08460716, -0.24552552, 0.030037103, 0.04123544,
-0.11940523, 0.007358328, 0.1890978, 0.4833202, -0.34441817,
0.36312827, -0.26375428, 0.1457655, -0.19724406, 0.15548733});
lstm.SetProjectionWeights(
{-0.009802181, 0.09401916, 0.0717386, -0.13895074, 0.09641832,
0.060420845, 0.08539281, 0.054285463, 0.061395317, 0.034448683,
-0.042991187, 0.019801661, -0.16840284, -0.015726732, -0.23041931,
-0.024478018, -0.10959692, -0.013875541, 0.18600968, -0.061274476,
0.0138165, -0.08160894, -0.07661644, 0.032372914, 0.16169067,
0.22465782, -0.03993472, -0.004017731, 0.08633481, -0.28869787,
0.08682067, 0.17240396, 0.014975425, 0.056431185, 0.031037588,
0.16702051, 0.0077946745, 0.15140012, 0.29405436, 0.120285,
-0.188994, -0.027265169, 0.043389652, -0.022061434, 0.014777949,
-0.20203483, 0.094781205, 0.19100232, 0.13987629, -0.036132768,
-0.06426278, -0.05108664, 0.13221376, 0.009441198, -0.16715929,
0.15859416, -0.040437475, 0.050779544, -0.022187516, 0.012166504,
0.027685808, -0.07675938, -0.0055694645, -0.09444123, 0.0046453946,
0.050794356, 0.10770313, -0.20790008, -0.07149004, -0.11425117,
0.008225835, -0.035802525, 0.14374903, 0.15262283, 0.048710253,
0.1847461, -0.007487823, 0.11000021, -0.09542012, 0.22619456,
-0.029149994, 0.08527916, 0.009043713, 0.0042746216, 0.016261552,
0.022461696, 0.12689082, -0.043589946, -0.12035478, -0.08361797,
-0.050666027, -0.1248618, -0.1275799, -0.071875185, 0.07377272,
0.09944291, -0.18897448, -0.1593054, -0.06526116, -0.040107165,
-0.004618631, -0.067624845, -0.007576253, 0.10727444, 0.041546922,
-0.20424393, 0.06907816, 0.050412357, 0.00724631, 0.039827548,
0.12449835, 0.10747581, 0.13708383, 0.09134148, -0.12617786,
-0.06428341, 0.09956831, 0.1208086, -0.14676677, -0.0727722,
0.1126304, 0.010139365, 0.015571211, -0.038128063, 0.022913318,
-0.042050496, 0.16842307, -0.060597885, 0.10531834, -0.06411776,
-0.07451711, -0.03410368, -0.13393489, 0.06534304, 0.003620307,
0.04490757, 0.05970546, 0.05197996, 0.02839995, 0.10434969,
-0.013699693, -0.028353551, -0.07260381, 0.047201227, -0.024575593,
-0.036445823, 0.07155557, 0.009672501, -0.02328883, 0.009533515,
-0.03606021, -0.07421458, -0.028082801, -0.2678904, -0.13221288,
0.18419984, -0.13012612, -0.014588381, -0.035059117, -0.04824723,
0.07830115, -0.056184657, 0.03277091, 0.025466874, 0.14494097,
-0.12522776, -0.098633975, -0.10766018, -0.08317623, 0.08594209,
0.07749552, 0.039474737, 0.1776665, -0.07409566, -0.0477268,
0.29323658, 0.10801441, 0.1154011, 0.013952499, 0.10739139,
0.10708251, -0.051456142, 0.0074137426, -0.10430189, 0.10034707,
0.045594677, 0.0635285, -0.0715442, -0.089667566, -0.10811871,
0.00026344223, 0.08298446, -0.009525053, 0.006585689, -0.24567553,
-0.09450807, 0.09648481, 0.026996298, -0.06419476, -0.04752702,
-0.11063944, -0.23441927, -0.17608605, -0.052156363, 0.067035615,
0.19271925, -0.0032889997, -0.043264326, 0.09663576, -0.057112187,
-0.10100678, 0.0628376, 0.04447668, 0.017961001, -0.10094388,
-0.10190601, 0.18335468, 0.10494553, -0.052095775, -0.0026118709,
0.10539724, -0.04383912, -0.042349473, 0.08438151, -0.1947263,
0.02251204, 0.11216432, -0.10307853, 0.17351969, -0.039091777,
0.08066188, -0.00561982, 0.12633002, 0.11335965, -0.0088127935,
-0.019777594, 0.06864014, -0.059751723, 0.016233567, -0.06894641,
-0.28651384, -0.004228674, 0.019708522, -0.16305895, -0.07468996,
-0.0855457, 0.099339016, -0.07580735, -0.13775392, 0.08434318,
0.08330512, -0.12131499, 0.031935584, 0.09180414, -0.08876437,
-0.08049874, 0.008753825, 0.03498998, 0.030215185, 0.03907079,
0.089751154, 0.029194152, -0.03337423, -0.019092513, 0.04331237,
0.04299654, -0.036394123, -0.12915532, 0.09793732, 0.07512415,
-0.11319543, -0.032502122, 0.15661901, 0.07671967, -0.005491124,
-0.19379048, -0.218606, 0.21448623, 0.017840758, 0.1416943,
-0.07051762, 0.19488361, 0.02664691, -0.18104725, -0.09334311,
0.15026465, -0.15493552, -0.057762887, -0.11604192, -0.262013,
-0.01391798, 0.012185008, 0.11156489, -0.07483202, 0.06693364,
-0.26151478, 0.046425626, 0.036540434, -0.16435726, 0.17338543,
-0.21401681, -0.11385144, -0.08283257, -0.069031075, 0.030635102,
0.010969227, 0.11109743, 0.010919218, 0.027526086, 0.13519906,
0.01891392, -0.046839405, -0.040167913, 0.017953383, -0.09700955,
0.0061885654, -0.07000971, 0.026893595, -0.038844477, 0.14543656});
static float lstm_input[][20] = {
{
0.787926, 0.151646, 0.071352, 0.118426, 0.458058, 0.596268, 0.998386,
0.568695, 0.864524, 0.571277, 0.073204, 0.296072, 0.743333, 0.069199,
0.045348, 0.867394, 0.291279, 0.013714, 0.482521, 0.626339},
{
0.295743, 0.544053, 0.690064, 0.858138, 0.497181, 0.642421, 0.524260,
0.134799, 0.003639, 0.162482, 0.640394, 0.930399, 0.050782, 0.432485,
0.988078, 0.082922, 0.563329, 0.865614, 0.333232, 0.259916}};
static float lstm_fw_golden_output[][64] = {
{
-0.00396806, 0.029352, -0.00279226, 0.0159977, -0.00835576,
-0.0211779, 0.0283512, -0.0114597, 0.00907307, -0.0244004,
-0.0152191, -0.0259063, 0.00914318, 0.00415118, 0.017147,
0.0134203, -0.0166936, 0.0381209, 0.000889694, 0.0143363,
-0.0328911, -0.0234288, 0.0333051, -0.012229, 0.0110322,
-0.0457725, -0.000832209, -0.0202817, 0.0327257, 0.0121308,
0.0155969, 0.0312091, -0.0213783, 0.0350169, 0.000324794,
0.0276012, -0.0263374, -0.0371449, 0.0446149, -0.0205474,
0.0103729, -0.0576349, -0.0150052, -0.0292043, 0.0376827,
0.0136115, 0.0243435, 0.0354492, -0.0189322, 0.0464512,
-0.00251373, 0.0225745, -0.0308346, -0.0317124, 0.0460407,
-0.0189395, 0.0149363, -0.0530162, -0.0150767, -0.0340193,
0.0286833, 0.00824207, 0.0264887, 0.0305169},
{
-0.013869, 0.0287268, -0.00334693, 0.00733398, -0.0287926,
-0.0186926, 0.0193662, -0.0115437, 0.00422612, -0.0345232,
0.00223253, -0.00957321, 0.0210624, 0.013331, 0.0150954,
0.02168, -0.0141913, 0.0322082, 0.00227024, 0.0260507,
-0.0188721, -0.0296489, 0.0399134, -0.0160509, 0.0116039,
-0.0447318, -0.0150515, -0.0277406, 0.0316596, 0.0118233,
0.0214762, 0.0293641, -0.0204549, 0.0450315, -0.00117378,
0.0167673, -0.0375007, -0.0238314, 0.038784, -0.0174034,
0.0131743, -0.0506589, -0.0048447, -0.0240239, 0.0325789,
0.00790065, 0.0220157, 0.0333314, -0.0264787, 0.0387855,
-0.000764675, 0.0217599, -0.037537, -0.0335206, 0.0431679,
-0.0211424, 0.010203, -0.062785, -0.00832363, -0.025181,
0.0412031, 0.0118723, 0.0239643, 0.0394009}};
static float lstm_combined_golden_output[][64] = {
{-0.022014, 0.073544, -0.002235, 0.040068, -0.037136, -0.052788,
0.075325, -0.029378, 0.024298, -0.07733, -0.030674, -0.060229,
0.040599, 0.011608, 0.042005, 0.045977, -0.039225, 0.076294,
0.000735, 0.032852, -0.069869, -0.053312, 0.073527, -0.028136,
0.021585, -0.102679, -0.004327, -0.043304, 0.072861, 0.027077,
0.034558, 0.068292, -0.036292, 0.069832, -0.003032, 0.053829,
-0.043821, -0.072713, 0.085029, -0.040374, 0.020014, -0.104521,
-0.034504, -0.059759, 0.062569, 0.025652, 0.049306, 0.061189,
-0.025146, 0.079643, -0.005188, 0.033080, -0.048079, -0.048082,
0.069369, -0.028900, 0.024572, -0.077547, -0.022517, -0.054477,
0.038857, 0.013336, 0.043234, 0.044788},
{-0.039186, 0.070792, -0.005913, 0.02642, -0.068274, -0.05022,
0.061444, -0.031241, 0.014996, -0.094544, -0.004146, -0.03464,
0.058981, 0.026097, 0.039781, 0.058408, -0.031887, 0.069252,
0.00576, 0.054062, -0.042801, -0.059974, 0.085272, -0.034453,
0.026097, -0.0959, -0.031164, -0.058699, 0.06839, 0.020512,
0.044727, 0.063609, -0.039863, 0.084819, -0.003909, 0.028666,
-0.075677, -0.045125, 0.070379, -0.033895, 0.022111, -0.097184,
-0.004921, -0.040851, 0.062316, 0.017435, 0.041437, 0.064568,
-0.039656, 0.060726, -0.003402, 0.036854, -0.056503, -0.058554,
0.068588, -0.034879, 0.01352, -0.09962, -0.01434, -0.039505,
0.065133, 0.024321, 0.038473, 0.062438}};
for (int i = 0; i < lstm.sequence_length(); i++) {
float* batch0_start = lstm_input[0] + i * lstm.num_inputs();
float* batch0_end = batch0_start + lstm.num_inputs();
lstm.SetInput(2 * i * lstm.num_inputs(), batch0_start, batch0_end);
float* batch1_start = lstm_input[1] + i * lstm.num_inputs();
float* batch1_end = batch1_start + lstm.num_inputs();
lstm.SetInput((2 * i + 1) * lstm.num_inputs(), batch1_start, batch1_end);
}
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
std::vector<float> expected;
for (int i = 0; i < lstm.sequence_length(); i++) {
float* golden_start_batch0 =
lstm_fw_golden_output[0] + i * lstm.num_fw_outputs();
float* golden_end_batch0 = golden_start_batch0 + lstm.num_fw_outputs();
float* golden_start_batch1 =
lstm_fw_golden_output[1] + i * lstm.num_fw_outputs();
float* golden_end_batch1 = golden_start_batch1 + lstm.num_fw_outputs();
expected.insert(expected.end(), golden_start_batch0, golden_end_batch0);
expected.insert(expected.end(), golden_start_batch1, golden_end_batch1);
}
EXPECT_THAT(lstm.GetFwOutput(), ElementsAreArray(ArrayFloatNear(expected)));
expected.clear();
for (int i = 0; i < lstm.sequence_length(); i++) {
float* golden_start_batch0 =
lstm_combined_golden_output[0] + i * lstm.num_fw_outputs();
float* golden_end_batch0 = golden_start_batch0 + lstm.num_fw_outputs();
float* golden_start_batch1 =
lstm_combined_golden_output[1] + i * lstm.num_fw_outputs();
float* golden_end_batch1 = golden_start_batch1 + lstm.num_fw_outputs();
expected.insert(expected.end(), golden_start_batch0, golden_end_batch0);
expected.insert(expected.end(), golden_start_batch1, golden_end_batch1);
}
std::vector<float> combined;
for (int i = 0; i < lstm.GetFwOutput().size(); ++i) {
combined.push_back(lstm.GetFwOutput()[i] + lstm.GetBwOutput()[i]);
}
EXPECT_THAT(combined, ElementsAreArray(ArrayFloatNear(expected)));
}
TEST(LSTMOpTest, BlackBoxTestWithPeepholeWithProjectionNoClippingBatchMajor) {
const int n_batch = 2;
const int n_input = 5;
const int n_cell = 20;
const int n_output = 16;
const int sequence_length = 4;
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, false,
true, true,
false, false,
false, 0.0,
0.0, false, false,
{
{n_batch, sequence_length, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_output, n_cell},
{0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{n_output, n_cell},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, sequence_length, 0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
});
lstm.SetInputToInputWeights(
{0.021393683, 0.06124551, 0.046905167, -0.014657677, -0.03149463,
0.09171803, 0.14647801, 0.10797193, -0.0057968358, 0.0019193048,
-0.2726754, 0.10154029, -0.018539885, 0.080349885, -0.10262385,
-0.022599787, -0.09121155, -0.008675967, -0.045206103, -0.0821282,
-0.008045952, 0.015478081, 0.055217247, 0.038719587, 0.044153627,
-0.06453243, 0.05031825, -0.046935108, -0.008164439, 0.014574226,
-0.1671009, -0.15519552, -0.16819797, -0.13971269, -0.11953059,
0.25005487, -0.22790983, 0.009855087, -0.028140958, -0.11200698,
0.11295408, -0.0035217577, 0.054485075, 0.05184695, 0.064711206,
0.10989193, 0.11674786, 0.03490607, 0.07727357, 0.11390585,
-0.1863375, -0.1034451, -0.13945189, -0.049401227, -0.18767063,
0.042483903, 0.14233552, 0.13832581, 0.18350165, 0.14545603,
-0.028545704, 0.024939531, 0.050929718, 0.0076203286, -0.0029723682,
-0.042484224, -0.11827596, -0.09171104, -0.10808628, -0.16327988,
-0.2273378, -0.0993647, -0.017155107, 0.0023917493, 0.049272764,
0.0038534778, 0.054764505, 0.089753784, 0.06947234, 0.08014476,
-0.04544234, -0.0497073, -0.07135631, -0.048929106, -0.004042012,
-0.009284026, 0.018042054, 0.0036860977, -0.07427302, -0.11434604,
-0.018995456, 0.031487543, 0.012834908, 0.019977754, 0.044256654,
-0.39292613, -0.18519334, -0.11651281, -0.06809892, 0.011373677});
lstm.SetInputToForgetWeights(
{-0.0018401089, -0.004852237, 0.03698424, 0.014181704, 0.028273236,
-0.016726194, -0.05249759, -0.10204261, 0.00861066, -0.040979505,
-0.009899187, 0.01923892, -0.028177269, -0.08535103, -0.14585495,
0.10662567, -0.01909731, -0.017883534, -0.0047269356, -0.045103323,
0.0030784295, 0.076784775, 0.07463696, 0.094531395, 0.0814421,
-0.12257899, -0.033945758, -0.031303465, 0.045630626, 0.06843887,
-0.13492945, -0.012480007, -0.0811829, -0.07224499, -0.09628791,
0.045100946, 0.0012300825, 0.013964662, 0.099372394, 0.02543059,
0.06958324, 0.034257296, 0.0482646, 0.06267997, 0.052625068,
0.12784666, 0.07077897, 0.025725935, 0.04165009, 0.07241905,
0.018668644, -0.037377294, -0.06277783, -0.08833636, -0.040120605,
-0.011405586, -0.007808335, -0.010301386, -0.005102167, 0.027717464,
0.05483423, 0.11449111, 0.11289652, 0.10939839, 0.13396506,
-0.08402166, -0.01901462, -0.044678304, -0.07720565, 0.014350063,
-0.11757958, -0.0652038, -0.08185733, -0.076754324, -0.092614375,
0.10405491, 0.052960336, 0.035755895, 0.035839386, -0.012540553,
0.036881298, 0.02913376, 0.03420159, 0.05448447, -0.054523353,
0.02582715, 0.02327355, -0.011857179, -0.0011980024, -0.034641717,
-0.026125094, -0.17582615, -0.15923657, -0.27486774, -0.0006143371,
0.0001771948, -8.470171e-05, 0.02651807, 0.045790765, 0.06956496});
lstm.SetInputToCellWeights(
{-0.04580283, -0.09549462, -0.032418985, -0.06454633,
-0.043528453, 0.043018587, -0.049152344, -0.12418144,
-0.078985475, -0.07596889, 0.019484362, -0.11434962,
-0.0074034138, -0.06314844, -0.092981495, 0.0062155537,
-0.025034338, -0.0028890965, 0.048929527, 0.06235075,
0.10665918, -0.032036792, -0.08505916, -0.10843358,
-0.13002433, -0.036816437, -0.02130134, -0.016518239,
0.0047691227, -0.0025825808, 0.066017866, 0.029991534,
-0.10652836, -0.1037554, -0.13056071, -0.03266643,
-0.033702414, -0.006473424, -0.04611692, 0.014419339,
-0.025174323, 0.0396852, 0.081777506, 0.06157468,
0.10210095, -0.009658194, 0.046511717, 0.03603906,
0.0069369148, 0.015960095, -0.06507666, 0.09551598,
0.053568836, 0.06408714, 0.12835667, -0.008714329,
-0.20211966, -0.12093674, 0.029450472, 0.2849013,
-0.029227901, 0.1164364, -0.08560263, 0.09941786,
-0.036999565, -0.028842626, -0.0033637602, -0.017012902,
-0.09720865, -0.11193351, -0.029155117, -0.017936034,
-0.009768936, -0.04223324, -0.036159635, 0.06505112,
-0.021742892, -0.023377212, -0.07221364, -0.06430552,
0.05453865, 0.091149814, 0.06387331, 0.007518393,
0.055960953, 0.069779344, 0.046411168, 0.10509911,
0.07463894, 0.0075130584, 0.012850982, 0.04555431,
0.056955688, 0.06555285, 0.050801456, -0.009862683,
0.00826772, -0.026555609, -0.0073611983, -0.0014897042});
lstm.SetInputToOutputWeights(
{-0.0998932, -0.07201956, -0.052803773, -0.15629593, -0.15001918,
-0.07650751, 0.02359855, -0.075155355, -0.08037709, -0.15093534,
0.029517552, -0.04751393, 0.010350531, -0.02664851, -0.016839722,
-0.023121163, 0.0077019283, 0.012851257, -0.05040649, -0.0129761,
-0.021737747, -0.038305793, -0.06870586, -0.01481247, -0.001285394,
0.10124236, 0.083122835, 0.053313006, -0.062235646, -0.075637154,
-0.027833903, 0.029774971, 0.1130802, 0.09218906, 0.09506135,
-0.086665764, -0.037162706, -0.038880914, -0.035832845, -0.014481564,
-0.09825003, -0.12048569, -0.097665586, -0.05287633, -0.0964047,
-0.11366429, 0.035777505, 0.13568819, 0.052451383, 0.050649304,
0.05798951, -0.021852335, -0.099848844, 0.014740475, -0.078897946,
0.04974699, 0.014160473, 0.06973932, 0.04964942, 0.033364646,
0.08190124, 0.025535367, 0.050893165, 0.048514254, 0.06945813,
-0.078907564, -0.06707616, -0.11844508, -0.09986688, -0.07509403,
0.06263226, 0.14925587, 0.20188436, 0.12098451, 0.14639415,
0.0015017595, -0.014267382, -0.03417257, 0.012711468, 0.0028300495,
-0.024758482, -0.05098548, -0.0821182, 0.014225672, 0.021544158,
0.08949725, 0.07505268, -0.0020780868, 0.04908258, 0.06476295,
-0.022907063, 0.027562456, 0.040185735, 0.019567577, -0.015598739,
-0.049097303, -0.017121866, -0.083368234, -0.02332002, -0.0840956});
lstm.SetInputGateBias(
{0.02234832, 0.14757581, 0.18176508, 0.10380666, 0.053110216,
-0.06928846, -0.13942584, -0.11816189, 0.19483899, 0.03652339,
-0.10250295, 0.036714908, -0.18426876, 0.036065217, 0.21810818,
0.02383196, -0.043370757, 0.08690144, -0.04444982, 0.00030581196});
lstm.SetForgetGateBias({0.035185695, -0.042891346, -0.03032477, 0.23027696,
0.11098921, 0.15378423, 0.09263801, 0.09790885,
0.09508917, 0.061199076, 0.07665568, -0.015443159,
-0.03499149, 0.046190713, 0.08895977, 0.10899629,
0.40694186, 0.06030037, 0.012413437, -0.06108739});
lstm.SetCellBias({-0.024379363, 0.0055531194, 0.23377132, 0.033463873,
-0.1483596, -0.10639995, -0.091433935, 0.058573797,
-0.06809782, -0.07889636, -0.043246906, -0.09829136,
-0.4279842, 0.034901652, 0.18797937, 0.0075234566,
0.016178843, 0.1749513, 0.13975595, 0.92058027});
lstm.SetOutputGateBias(
{0.046159424, -0.0012809046, 0.03563469, 0.12648113, 0.027195795,
0.35373217, -0.018957434, 0.008907322, -0.0762701, 0.12018895,
0.04216877, 0.0022856654, 0.040952638, 0.3147856, 0.08225149,
-0.057416286, -0.14995944, -0.008040261, 0.13208859, 0.029760877});
lstm.SetRecurrentToInputWeights(
{-0.001374326, -0.078856036, 0.10672688, 0.029162422,
-0.11585556, 0.02557986, -0.13446963, -0.035785314,
-0.01244275, 0.025961924, -0.02337298, -0.044228926,
-0.055839065, -0.046598054, -0.010546039, -0.06900766,
0.027239809, 0.022582639, -0.013296484, -0.05459212,
0.08981, -0.045407712, 0.08682226, -0.06867011,
-0.14390695, -0.02916037, 0.000996957, 0.091420636,
0.14283475, -0.07390571, -0.06402044, 0.062524505,
-0.093129106, 0.04860203, -0.08364217, -0.08119002,
0.009352075, 0.22920375, 0.0016303885, 0.11583097,
-0.13732095, 0.012405723, -0.07551853, 0.06343048,
0.12162708, -0.031923793, -0.014335606, 0.01790974,
-0.10650317, -0.0724401, 0.08554849, -0.05727212,
0.06556731, -0.042729504, -0.043227166, 0.011683251,
-0.013082158, -0.029302018, -0.010899579, -0.062036745,
-0.022509435, -0.00964907, -0.01567329, 0.04260106,
-0.07787477, -0.11576462, 0.017356863, 0.048673786,
-0.017577527, -0.05527947, -0.082487635, -0.040137455,
-0.10820036, -0.04666372, 0.022746278, -0.07851417,
0.01068115, 0.032956902, 0.022433773, 0.0026891115,
0.08944216, -0.0685835, 0.010513544, 0.07228705,
0.02032331, -0.059686817, -0.0005566496, -0.086984694,
0.040414046, -0.1380399, 0.094208956, -0.05722982,
0.012092817, -0.04989123, -0.086576, -0.003399834,
-0.04696032, -0.045747425, 0.10091314, 0.048676282,
-0.029037097, 0.031399418, -0.0040285117, 0.047237843,
0.09504992, 0.041799378, -0.049185462, -0.031518843,
-0.10516937, 0.026374253, 0.10058866, -0.0033195973,
-0.041975245, 0.0073591834, 0.0033782164, -0.004325073,
-0.10167381, 0.042500053, -0.01447153, 0.06464186,
-0.017142897, 0.03312627, 0.009205989, 0.024138335,
-0.011337001, 0.035530265, -0.010912711, 0.0706555,
-0.005894094, 0.051841937, -0.1401738, -0.02351249,
0.0365468, 0.07590991, 0.08838724, 0.021681072,
-0.10086113, 0.019608743, -0.06195883, 0.077335775,
0.023646897, -0.095322326, 0.02233014, 0.09756986,
-0.048691444, -0.009579111, 0.07595467, 0.11480546,
-0.09801813, 0.019894179, 0.08502348, 0.004032281,
0.037211012, 0.068537936, -0.048005626, -0.091520436,
-0.028379958, -0.01556313, 0.06554592, -0.045599163,
-0.01672207, -0.020169014, -0.011877351, -0.20212261,
0.010889619, 0.0047078193, 0.038385306, 0.08540671,
-0.017140968, -0.0035865551, 0.016678626, 0.005633034,
0.015963363, 0.00871737, 0.060130805, 0.028611384,
0.10109069, -0.015060172, -0.07894427, 0.06401885,
0.011584063, -0.024466386, 0.0047652307, -0.09041358,
0.030737216, -0.0046374933, 0.14215417, -0.11823516,
0.019899689, 0.006106124, -0.027092824, 0.0786356,
0.05052217, -0.058925, -0.011402121, -0.024987547,
-0.0013661642, -0.06832946, -0.015667673, -0.1083353,
-0.00096863037, -0.06988685, -0.053350925, -0.027275559,
-0.033664223, -0.07978348, -0.025200296, -0.017207067,
-0.058403496, -0.055697463, 0.005798788, 0.12965427,
-0.062582195, 0.0013350133, -0.10482091, 0.0379771,
0.072521195, -0.0029455067, -0.13797039, -0.03628521,
0.013806405, -0.017858358, -0.01008298, -0.07700066,
-0.017081132, 0.019358726, 0.0027079724, 0.004635139,
0.062634714, -0.02338735, -0.039547626, -0.02050681,
0.03385117, -0.083611414, 0.002862572, -0.09421313,
0.058618143, -0.08598433, 0.00972939, 0.023867095,
-0.053934585, -0.023203006, 0.07452513, -0.048767887,
-0.07314807, -0.056307215, -0.10433547, -0.06440842,
0.04328182, 0.04389765, -0.020006588, -0.09076438,
-0.11652589, -0.021705797, 0.03345259, -0.010329105,
-0.025767034, 0.013057034, -0.07316461, -0.10145612,
0.06358255, 0.18531723, 0.07759293, 0.12006465,
0.1305557, 0.058638252, -0.03393652, 0.09622831,
-0.16253184, -2.4580743e-06, 0.079869635, -0.070196845,
-0.005644518, 0.06857898, -0.12598175, -0.035084512,
0.03156317, -0.12794146, -0.031963028, 0.04692781,
0.030070418, 0.0071660685, -0.095516115, -0.004643372,
0.040170413, -0.062104587, -0.0037324072, 0.0554317,
0.08184801, -0.019164372, 0.06791302, 0.034257166,
-0.10307039, 0.021943003, 0.046745934, 0.0790918,
-0.0265588, -0.007824208, 0.042546265, -0.00977924,
-0.0002440307, -0.017384544, -0.017990116, 0.12252321,
-0.014512694, -0.08251313, 0.08861942, 0.13589665,
0.026351685, 0.012641483, 0.07466548, 0.044301085,
-0.045414884, -0.051112458, 0.03444247, -0.08502782,
-0.04106223, -0.028126027, 0.028473156, 0.10467447});
lstm.SetRecurrentToForgetWeights(
{-0.057784554, -0.026057621, -0.068447545, -0.022581743,
0.14811787, 0.10826372, 0.09471067, 0.03987225,
-0.0039523416, 0.00030638507, 0.053185795, 0.10572994,
0.08414449, -0.022036452, -0.00066928595, -0.09203576,
0.032950465, -0.10985798, -0.023809856, 0.0021431844,
-0.02196096, -0.00326074, 0.00058621005, -0.074678116,
-0.06193199, 0.055729095, 0.03736828, 0.020123724,
0.061878487, -0.04729229, 0.034919553, -0.07585433,
-0.04421272, -0.044019096, 0.085488975, 0.04058006,
-0.06890133, -0.030951202, -0.024628663, -0.07672815,
0.034293607, 0.08556707, -0.05293577, -0.033561368,
-0.04899627, 0.0241671, 0.015736353, -0.095442444,
-0.029564252, 0.016493602, -0.035026584, 0.022337519,
-0.026871363, 0.004780428, 0.0077918363, -0.03601621,
0.016435321, -0.03263031, -0.09543275, -0.047392778,
0.013454138, 0.028934088, 0.01685226, -0.086110644,
-0.046250615, -0.01847454, 0.047608484, 0.07339695,
0.034546845, -0.04881143, 0.009128804, -0.08802852,
0.03761666, 0.008096139, -0.014454086, 0.014361001,
-0.023502491, -0.0011840804, -0.07607001, 0.001856849,
-0.06509276, -0.006021153, -0.08570962, -0.1451793,
0.060212336, 0.055259194, 0.06974018, 0.049454916,
-0.027794661, -0.08077226, -0.016179763, 0.1169753,
0.17213494, -0.0056326236, -0.053934924, -0.0124349,
-0.11520337, 0.05409887, 0.088759385, 0.0019655675,
0.0042065294, 0.03881498, 0.019844765, 0.041858196,
-0.05695512, 0.047233116, 0.038937137, -0.06542224,
0.014429736, -0.09719407, 0.13908425, -0.05379757,
0.012321099, 0.082840554, -0.029899208, 0.044217527,
0.059855383, 0.07711018, -0.045319796, 0.0948846,
-0.011724666, -0.0033288454, -0.033542685, -0.04764985,
-0.13873616, 0.040668588, 0.034832682, -0.015319203,
-0.018715994, 0.046002675, 0.0599172, -0.043107376,
0.0294216, -0.002314414, -0.022424703, 0.0030315618,
0.0014641669, 0.0029166266, -0.11878115, 0.013738511,
0.12375372, -0.0006038222, 0.029104086, 0.087442465,
0.052958444, 0.07558703, 0.04817258, 0.044462286,
-0.015213451, -0.08783778, -0.0561384, -0.003008196,
0.047060397, -0.002058388, 0.03429439, -0.018839769,
0.024734668, 0.024614193, -0.042046934, 0.09597743,
-0.0043254104, 0.04320769, 0.0064070094, -0.0019131786,
-0.02558259, -0.022822596, -0.023273505, -0.02464396,
-0.10991725, -0.006240552, 0.0074488563, 0.024044557,
0.04383914, -0.046476185, 0.028658995, 0.060410924,
0.050786525, 0.009452605, -0.0073054377, -0.024810238,
0.0052906186, 0.0066939713, -0.0020913032, 0.014515517,
0.015898481, 0.021362653, -0.030262267, 0.016587038,
-0.011442813, 0.041154444, -0.007631438, -0.03423484,
-0.010977775, 0.036152758, 0.0066366293, 0.11915515,
0.02318443, -0.041350313, 0.021485701, -0.10906167,
-0.028218046, -0.00954771, 0.020531068, -0.11995105,
-0.03672871, 0.024019798, 0.014255957, -0.05221243,
-0.00661567, -0.04630967, 0.033188973, 0.10107534,
-0.014027541, 0.030796422, -0.10270911, -0.035999842,
0.15443139, 0.07684145, 0.036571592, -0.035900835,
-0.0034699554, 0.06209149, 0.015920248, -0.031122351,
-0.03858649, 0.01849943, 0.13872518, 0.01503974,
0.069941424, -0.06948533, -0.0088794185, 0.061282158,
-0.047401894, 0.03100163, -0.041533746, -0.10430945,
0.044574402, -0.01425562, -0.024290353, 0.034563623,
0.05866852, 0.023947537, -0.09445152, 0.035450947,
0.02247216, -0.0042998926, 0.061146557, -0.10250651,
0.020881841, -0.06747029, 0.10062043, -0.0023941975,
0.03532124, -0.016341697, 0.09685456, -0.016764693,
0.051808182, 0.05875331, -0.04536488, 0.001626336,
-0.028892258, -0.01048663, -0.009793449, -0.017093895,
0.010987891, 0.02357273, -0.00010856845, 0.0099760275,
-0.001845119, -0.03551521, 0.0018358806, 0.05763657,
-0.01769146, 0.040995963, 0.02235177, -0.060430344,
0.11475477, -0.023854522, 0.10071741, 0.0686208,
-0.014250481, 0.034261297, 0.047418304, 0.08562733,
-0.030519066, 0.0060542435, 0.014653856, -0.038836084,
0.04096551, 0.032249358, -0.08355519, -0.026823482,
0.056386515, -0.010401743, -0.028396193, 0.08507674,
0.014410365, 0.020995233, 0.17040324, 0.11511526,
0.02459721, 0.0066619175, 0.025853224, -0.023133837,
-0.081302024, 0.017264642, -0.009585969, 0.09491168,
-0.051313367, 0.054532815, -0.014298593, 0.10657464,
0.007076659, 0.10964551, 0.0409152, 0.008275321,
-0.07283536, 0.07937492, 0.04192024, -0.1075027});
lstm.SetRecurrentToCellWeights(
{-0.037322544, 0.018592842, 0.0056175636, -0.06253426,
0.055647098, -0.05713207, -0.05626563, 0.005559383,
0.03375411, -0.025757805, -0.088049285, 0.06017052,
-0.06570978, 0.007384076, 0.035123326, -0.07920549,
0.053676967, 0.044480428, -0.07663568, 0.0071805613,
0.08089997, 0.05143358, 0.038261272, 0.03339287,
-0.027673481, 0.044746667, 0.028349208, 0.020090483,
-0.019443132, -0.030755889, -0.0040000007, 0.04465846,
-0.021585021, 0.0031670958, 0.0053199246, -0.056117613,
-0.10893326, 0.076739706, -0.08509834, -0.027997585,
0.037871376, 0.01449768, -0.09002357, -0.06111149,
-0.046195522, 0.0422062, -0.005683705, -0.1253618,
-0.012925729, -0.04890792, 0.06985068, 0.037654128,
0.03398274, -0.004781977, 0.007032333, -0.031787455,
0.010868644, -0.031489216, 0.09525667, 0.013939797,
0.0058680447, 0.0167067, 0.02668468, -0.04797466,
-0.048885044, -0.12722108, 0.035304096, 0.06554885,
0.00972396, -0.039238118, -0.05159735, -0.11329045,
0.1613692, -0.03750952, 0.06529313, -0.071974665,
-0.11769596, 0.015524369, -0.0013754242, -0.12446318,
0.02786344, -0.014179351, 0.005264273, 0.14376344,
0.015983658, 0.03406988, -0.06939408, 0.040699873,
0.02111075, 0.09669095, 0.041345075, -0.08316494,
-0.07684199, -0.045768797, 0.032298047, -0.041805092,
0.0119405, 0.0061010392, 0.12652606, 0.0064572375,
-0.024950314, 0.11574242, 0.04508852, -0.04335324,
0.06760663, -0.027437469, 0.07216407, 0.06977076,
-0.05438599, 0.034033038, -0.028602652, 0.05346137,
0.043184172, -0.037189785, 0.10420091, 0.00882477,
-0.054019816, -0.074273005, -0.030617684, -0.0028467078,
0.024302477, -0.0038869337, 0.005332455, 0.0013399826,
0.04361412, -0.007001822, 0.09631092, -0.06702025,
-0.042049985, -0.035070654, -0.04103342, -0.10273396,
0.0544271, 0.037184782, -0.13150354, -0.0058036847,
-0.008264958, 0.042035464, 0.05891794, 0.029673764,
0.0063542654, 0.044788733, 0.054816857, 0.062257513,
-0.00093483756, 0.048938446, -0.004952862, -0.007730018,
-0.04043371, -0.017094059, 0.07229206, -0.023670016,
-0.052195564, -0.025616996, -0.01520939, 0.045104615,
-0.007376126, 0.003533447, 0.006570588, 0.056037236,
0.12436656, 0.051817212, 0.028532185, -0.08686856,
0.11868599, 0.07663395, -0.07323171, 0.03463402,
-0.050708205, -0.04458982, -0.11590894, 0.021273347,
0.1251325, -0.15313013, -0.12224372, 0.17228661,
0.023029093, 0.086124025, 0.006445803, -0.03496501,
0.028332196, 0.04449512, -0.042436164, -0.026587414,
-0.006041347, -0.09292539, -0.05678812, 0.03897832,
0.09465633, 0.008115513, -0.02171956, 0.08304309,
0.071401566, 0.019622514, 0.032163795, -0.004167056,
0.02295182, 0.030739572, 0.056506045, 0.004612461,
0.06524936, 0.059999723, 0.046395954, -0.0045512207,
-0.1335546, -0.030136576, 0.11584653, -0.014678886,
0.0020118146, -0.09688814, -0.0790206, 0.039770417,
-0.0329582, 0.07922767, 0.029322514, 0.026405897,
0.04207835, -0.07073373, 0.063781224, 0.0859677,
-0.10925287, -0.07011058, 0.048005477, 0.03438226,
-0.09606514, -0.006669445, -0.043381985, 0.04240257,
-0.06955775, -0.06769346, 0.043903265, -0.026784198,
-0.017840602, 0.024307009, -0.040079936, -0.019946516,
0.045318738, -0.12233574, 0.026170589, 0.0074471775,
0.15978073, 0.10185836, 0.10298046, -0.015476589,
-0.039390966, -0.072174534, 0.0739445, -0.1211869,
-0.0347889, -0.07943156, 0.014809798, -0.12412325,
-0.0030663363, 0.039695457, 0.0647603, -0.08291318,
-0.018529687, -0.004423833, 0.0037507233, 0.084633216,
-0.01514876, -0.056505352, -0.012800942, -0.06994386,
0.012962922, -0.031234352, 0.07029052, 0.016418684,
0.03618972, 0.055686004, -0.08663945, -0.017404709,
-0.054761406, 0.029065743, 0.052404847, 0.020238016,
0.0048197987, -0.0214882, 0.07078733, 0.013016777,
0.06262858, 0.009184685, 0.020785125, -0.043904778,
-0.0270329, -0.03299152, -0.060088247, -0.015162964,
-0.001828936, 0.12642565, -0.056757294, 0.013586685,
0.09232601, -0.035886683, 0.06000002, 0.05229691,
-0.052580316, -0.082029596, -0.010794592, 0.012947712,
-0.036429964, -0.085508935, -0.13127148, -0.017744139,
0.031502828, 0.036232427, -0.031581745, 0.023051167,
-0.05325106, -0.03421577, 0.028793324, -0.034633752,
-0.009881397, -0.043551125, -0.018609839, 0.0019097115,
-0.008799762, 0.056595087, 0.0022273948, 0.055752404});
lstm.SetRecurrentToOutputWeights({
0.025825322, -0.05813119, 0.09495884, -0.045984812, -0.01255415,
-0.0026479573, -0.08196161, -0.054914974, -0.0046604523, -0.029587349,
-0.044576716, -0.07480124, -0.082868785, 0.023254942, 0.027502948,
-0.0039728214, -0.08683098, -0.08116779, -0.014675607, -0.037924774,
-0.023314456, -0.007401714, -0.09255757, 0.029460307, -0.08829125,
-0.005139627, -0.08989442, -0.0555066, 0.13596267, -0.025062224,
-0.048351806, -0.03850004, 0.07266485, -0.022414139, 0.05940088,
0.075114764, 0.09597592, -0.010211725, -0.0049794707, -0.011523867,
-0.025980417, 0.072999895, 0.11091378, -0.081685916, 0.014416728,
0.043229222, 0.034178585, -0.07530371, 0.035837382, -0.085607,
-0.007721233, -0.03287832, -0.043848954, -0.06404588, -0.06632928,
-0.073643476, 0.008214239, -0.045984086, 0.039764922, 0.03474462,
0.060612556, -0.080590084, 0.049127717, 0.04151091, -0.030063879,
0.008801774, -0.023021035, -0.019558564, 0.05158114, -0.010947698,
-0.011825728, 0.0075720972, 0.0699727, -0.0039981045, 0.069350146,
0.08799282, 0.016156472, 0.035502106, 0.11695009, 0.006217345,
0.13392477, -0.037875112, 0.025745004, 0.08940699, -0.00924166,
0.0046702605, -0.036598757, -0.08811812, 0.10522024, -0.032441203,
0.008176899, -0.04454919, 0.07058152, 0.0067963637, 0.039206743,
0.03259838, 0.03725492, -0.09515802, 0.013326398, -0.052055415,
-0.025676316, 0.03198509, -0.015951829, -0.058556724, 0.036879618,
0.043357447, 0.028362012, -0.05908629, 0.0059240665, -0.04995891,
-0.019187413, 0.0276265, -0.01628143, 0.0025863599, 0.08800015,
0.035250366, -0.022165963, -0.07328642, -0.009415526, -0.07455109,
0.11690406, 0.0363299, 0.07411125, 0.042103454, -0.009660886,
0.019076364, 0.018299393, -0.046004917, 0.08891175, 0.0431396,
-0.026327137, -0.051502608, 0.08979574, -0.051670972, 0.04940282,
-0.07491107, -0.021240504, 0.022596184, -0.034280192, 0.060163025,
-0.058211457, -0.051837247, -0.01349775, -0.04639988, -0.035936575,
-0.011681591, 0.064818054, 0.0073146066, -0.021745546, -0.043124277,
-0.06471268, -0.07053354, -0.029321948, -0.05330136, 0.016933719,
-0.053782392, 0.13747959, -0.1361751, -0.11569455, 0.0033329215,
0.05693899, -0.053219706, 0.063698, 0.07977434, -0.07924483,
0.06936997, 0.0034815092, -0.007305279, -0.037325785, -0.07251102,
-0.033633437, -0.08677009, 0.091591336, -0.14165086, 0.021752775,
0.019683983, 0.0011612234, -0.058154266, 0.049996935, 0.0288841,
-0.0024567875, -0.14345716, 0.010955264, -0.10234828, 0.1183656,
-0.0010731248, -0.023590032, -0.072285876, -0.0724771, -0.026382286,
-0.0014920527, 0.042667855, 0.0018776858, 0.02986552, 0.009814309,
0.0733756, 0.12289186, 0.018043943, -0.0458958, 0.049412545,
0.033632483, 0.05495232, 0.036686596, -0.013781798, -0.010036754,
0.02576849, -0.08307328, 0.010112348, 0.042521734, -0.05869831,
-0.071689695, 0.03876447, -0.13275425, -0.0352966, -0.023077697,
0.10285965, 0.084736146, 0.15568255, -0.00040734606, 0.027835453,
-0.10292561, -0.032401145, 0.10053256, -0.026142767, -0.08271222,
-0.0030240538, -0.016368777, 0.1070414, 0.042672627, 0.013456989,
-0.0437609, -0.022309763, 0.11576483, 0.04108048, 0.061026827,
-0.0190714, -0.0869359, 0.037901703, 0.0610107, 0.07202949,
0.01675338, 0.086139716, -0.08795751, -0.014898893, -0.023771819,
-0.01965048, 0.007955471, -0.043740474, 0.03346837, -0.10549954,
0.090567775, 0.042013682, -0.03176985, 0.12569028, -0.02421228,
-0.029526481, 0.023851605, 0.031539805, 0.05292009, -0.02344001,
-0.07811758, -0.08834428, 0.10094801, 0.16594367, -0.06861939,
-0.021256343, -0.041093912, -0.06669611, 0.035498552, 0.021757556,
-0.09302526, -0.015403468, -0.06614931, -0.051798206, -0.013874718,
0.03630673, 0.010412845, -0.08077351, 0.046185967, 0.0035662893,
0.03541868, -0.094149634, -0.034814864, 0.003128424, -0.020674974,
-0.03944324, -0.008110165, -0.11113267, 0.08484226, 0.043586485,
0.040582247, 0.0968012, -0.065249965, -0.028036479, 0.0050708856,
0.0017462453, 0.0326779, 0.041296225, 0.09164146, -0.047743853,
-0.015952192, -0.034451712, 0.084197424, -0.05347844, -0.11768019,
0.085926116, -0.08251791, -0.045081906, 0.0948852, 0.068401024,
0.024856757, 0.06978981, -0.057309967, -0.012775832, -0.0032452994,
0.01977615, -0.041040014, -0.024264973, 0.063464895, 0.05431621,
});
lstm.SetCellToInputWeights(
{0.040369894, 0.030746894, 0.24704495, 0.018586371, -0.037586458,
-0.15312155, -0.11812848, -0.11465643, 0.20259799, 0.11418174,
-0.10116027, -0.011334949, 0.12411352, -0.076769054, -0.052169047,
0.21198851, -0.38871562, -0.09061183, -0.09683246, -0.21929175});
lstm.SetCellToForgetWeights(
{-0.01998659, -0.15568835, -0.24248174, -0.012770197, 0.041331276,
-0.072311886, -0.052123554, -0.0066330447, -0.043891653, 0.036225766,
-0.047248036, 0.021479502, 0.033189066, 0.11952997, -0.020432774,
0.64658105, -0.06650122, -0.03467612, 0.095340036, 0.23647355});
lstm.SetCellToOutputWeights(
{0.08286371, -0.08261836, -0.51210177, 0.002913762, 0.17764764,
-0.5495371, -0.08460716, -0.24552552, 0.030037103, 0.04123544,
-0.11940523, 0.007358328, 0.1890978, 0.4833202, -0.34441817,
0.36312827, -0.26375428, 0.1457655, -0.19724406, 0.15548733});
lstm.SetProjectionWeights(
{-0.009802181, 0.09401916, 0.0717386, -0.13895074, 0.09641832,
0.060420845, 0.08539281, 0.054285463, 0.061395317, 0.034448683,
-0.042991187, 0.019801661, -0.16840284, -0.015726732, -0.23041931,
-0.024478018, -0.10959692, -0.013875541, 0.18600968, -0.061274476,
0.0138165, -0.08160894, -0.07661644, 0.032372914, 0.16169067,
0.22465782, -0.03993472, -0.004017731, 0.08633481, -0.28869787,
0.08682067, 0.17240396, 0.014975425, 0.056431185, 0.031037588,
0.16702051, 0.0077946745, 0.15140012, 0.29405436, 0.120285,
-0.188994, -0.027265169, 0.043389652, -0.022061434, 0.014777949,
-0.20203483, 0.094781205, 0.19100232, 0.13987629, -0.036132768,
-0.06426278, -0.05108664, 0.13221376, 0.009441198, -0.16715929,
0.15859416, -0.040437475, 0.050779544, -0.022187516, 0.012166504,
0.027685808, -0.07675938, -0.0055694645, -0.09444123, 0.0046453946,
0.050794356, 0.10770313, -0.20790008, -0.07149004, -0.11425117,
0.008225835, -0.035802525, 0.14374903, 0.15262283, 0.048710253,
0.1847461, -0.007487823, 0.11000021, -0.09542012, 0.22619456,
-0.029149994, 0.08527916, 0.009043713, 0.0042746216, 0.016261552,
0.022461696, 0.12689082, -0.043589946, -0.12035478, -0.08361797,
-0.050666027, -0.1248618, -0.1275799, -0.071875185, 0.07377272,
0.09944291, -0.18897448, -0.1593054, -0.06526116, -0.040107165,
-0.004618631, -0.067624845, -0.007576253, 0.10727444, 0.041546922,
-0.20424393, 0.06907816, 0.050412357, 0.00724631, 0.039827548,
0.12449835, 0.10747581, 0.13708383, 0.09134148, -0.12617786,
-0.06428341, 0.09956831, 0.1208086, -0.14676677, -0.0727722,
0.1126304, 0.010139365, 0.015571211, -0.038128063, 0.022913318,
-0.042050496, 0.16842307, -0.060597885, 0.10531834, -0.06411776,
-0.07451711, -0.03410368, -0.13393489, 0.06534304, 0.003620307,
0.04490757, 0.05970546, 0.05197996, 0.02839995, 0.10434969,
-0.013699693, -0.028353551, -0.07260381, 0.047201227, -0.024575593,
-0.036445823, 0.07155557, 0.009672501, -0.02328883, 0.009533515,
-0.03606021, -0.07421458, -0.028082801, -0.2678904, -0.13221288,
0.18419984, -0.13012612, -0.014588381, -0.035059117, -0.04824723,
0.07830115, -0.056184657, 0.03277091, 0.025466874, 0.14494097,
-0.12522776, -0.098633975, -0.10766018, -0.08317623, 0.08594209,
0.07749552, 0.039474737, 0.1776665, -0.07409566, -0.0477268,
0.29323658, 0.10801441, 0.1154011, 0.013952499, 0.10739139,
0.10708251, -0.051456142, 0.0074137426, -0.10430189, 0.10034707,
0.045594677, 0.0635285, -0.0715442, -0.089667566, -0.10811871,
0.00026344223, 0.08298446, -0.009525053, 0.006585689, -0.24567553,
-0.09450807, 0.09648481, 0.026996298, -0.06419476, -0.04752702,
-0.11063944, -0.23441927, -0.17608605, -0.052156363, 0.067035615,
0.19271925, -0.0032889997, -0.043264326, 0.09663576, -0.057112187,
-0.10100678, 0.0628376, 0.04447668, 0.017961001, -0.10094388,
-0.10190601, 0.18335468, 0.10494553, -0.052095775, -0.0026118709,
0.10539724, -0.04383912, -0.042349473, 0.08438151, -0.1947263,
0.02251204, 0.11216432, -0.10307853, 0.17351969, -0.039091777,
0.08066188, -0.00561982, 0.12633002, 0.11335965, -0.0088127935,
-0.019777594, 0.06864014, -0.059751723, 0.016233567, -0.06894641,
-0.28651384, -0.004228674, 0.019708522, -0.16305895, -0.07468996,
-0.0855457, 0.099339016, -0.07580735, -0.13775392, 0.08434318,
0.08330512, -0.12131499, 0.031935584, 0.09180414, -0.08876437,
-0.08049874, 0.008753825, 0.03498998, 0.030215185, 0.03907079,
0.089751154, 0.029194152, -0.03337423, -0.019092513, 0.04331237,
0.04299654, -0.036394123, -0.12915532, 0.09793732, 0.07512415,
-0.11319543, -0.032502122, 0.15661901, 0.07671967, -0.005491124,
-0.19379048, -0.218606, 0.21448623, 0.017840758, 0.1416943,
-0.07051762, 0.19488361, 0.02664691, -0.18104725, -0.09334311,
0.15026465, -0.15493552, -0.057762887, -0.11604192, -0.262013,
-0.01391798, 0.012185008, 0.11156489, -0.07483202, 0.06693364,
-0.26151478, 0.046425626, 0.036540434, -0.16435726, 0.17338543,
-0.21401681, -0.11385144, -0.08283257, -0.069031075, 0.030635102,
0.010969227, 0.11109743, 0.010919218, 0.027526086, 0.13519906,
0.01891392, -0.046839405, -0.040167913, 0.017953383, -0.09700955,
0.0061885654, -0.07000971, 0.026893595, -0.038844477, 0.14543656});
static float lstm_input[][20] = {
{
0.787926, 0.151646, 0.071352, 0.118426, 0.458058, 0.596268, 0.998386,
0.568695, 0.864524, 0.571277, 0.073204, 0.296072, 0.743333, 0.069199,
0.045348, 0.867394, 0.291279, 0.013714, 0.482521, 0.626339},
{
0.295743, 0.544053, 0.690064, 0.858138, 0.497181, 0.642421, 0.524260,
0.134799, 0.003639, 0.162482, 0.640394, 0.930399, 0.050782, 0.432485,
0.988078, 0.082922, 0.563329, 0.865614, 0.333232, 0.259916}};
static float lstm_fw_golden_output[][64] = {
{
-0.00396806, 0.029352, -0.00279226, 0.0159977, -0.00835576,
-0.0211779, 0.0283512, -0.0114597, 0.00907307, -0.0244004,
-0.0152191, -0.0259063, 0.00914318, 0.00415118, 0.017147,
0.0134203, -0.0166936, 0.0381209, 0.000889694, 0.0143363,
-0.0328911, -0.0234288, 0.0333051, -0.012229, 0.0110322,
-0.0457725, -0.000832209, -0.0202817, 0.0327257, 0.0121308,
0.0155969, 0.0312091, -0.0213783, 0.0350169, 0.000324794,
0.0276012, -0.0263374, -0.0371449, 0.0446149, -0.0205474,
0.0103729, -0.0576349, -0.0150052, -0.0292043, 0.0376827,
0.0136115, 0.0243435, 0.0354492, -0.0189322, 0.0464512,
-0.00251373, 0.0225745, -0.0308346, -0.0317124, 0.0460407,
-0.0189395, 0.0149363, -0.0530162, -0.0150767, -0.0340193,
0.0286833, 0.00824207, 0.0264887, 0.0305169},
{
-0.013869, 0.0287268, -0.00334693, 0.00733398, -0.0287926,
-0.0186926, 0.0193662, -0.0115437, 0.00422612, -0.0345232,
0.00223253, -0.00957321, 0.0210624, 0.013331, 0.0150954,
0.02168, -0.0141913, 0.0322082, 0.00227024, 0.0260507,
-0.0188721, -0.0296489, 0.0399134, -0.0160509, 0.0116039,
-0.0447318, -0.0150515, -0.0277406, 0.0316596, 0.0118233,
0.0214762, 0.0293641, -0.0204549, 0.0450315, -0.00117378,
0.0167673, -0.0375007, -0.0238314, 0.038784, -0.0174034,
0.0131743, -0.0506589, -0.0048447, -0.0240239, 0.0325789,
0.00790065, 0.0220157, 0.0333314, -0.0264787, 0.0387855,
-0.000764675, 0.0217599, -0.037537, -0.0335206, 0.0431679,
-0.0211424, 0.010203, -0.062785, -0.00832363, -0.025181,
0.0412031, 0.0118723, 0.0239643, 0.0394009}};
static float lstm_combined_golden_output[][64] = {
{-0.022014, 0.073544, -0.002235, 0.040068, -0.037136, -0.052788,
0.075325, -0.029378, 0.024298, -0.07733, -0.030674, -0.060229,
0.040599, 0.011608, 0.042005, 0.045977, -0.039225, 0.076294,
0.000735, 0.032852, -0.069869, -0.053312, 0.073527, -0.028136,
0.021585, -0.102679, -0.004327, -0.043304, 0.072861, 0.027077,
0.034558, 0.068292, -0.036292, 0.069832, -0.003032, 0.053829,
-0.043821, -0.072713, 0.085029, -0.040374, 0.020014, -0.104521,
-0.034504, -0.059759, 0.062569, 0.025652, 0.049306, 0.061189,
-0.025146, 0.079643, -0.005188, 0.033080, -0.048079, -0.048082,
0.069369, -0.028900, 0.024572, -0.077547, -0.022517, -0.054477,
0.038857, 0.013336, 0.043234, 0.044788},
{-0.039186, 0.070792, -0.005913, 0.02642, -0.068274, -0.05022,
0.061444, -0.031241, 0.014996, -0.094544, -0.004146, -0.03464,
0.058981, 0.026097, 0.039781, 0.058408, -0.031887, 0.069252,
0.00576, 0.054062, -0.042801, -0.059974, 0.085272, -0.034453,
0.026097, -0.0959, -0.031164, -0.058699, 0.06839, 0.020512,
0.044727, 0.063609, -0.039863, 0.084819, -0.003909, 0.028666,
-0.075677, -0.045125, 0.070379, -0.033895, 0.022111, -0.097184,
-0.004921, -0.040851, 0.062316, 0.017435, 0.041437, 0.064568,
-0.039656, 0.060726, -0.003402, 0.036854, -0.056503, -0.058554,
0.068588, -0.034879, 0.01352, -0.09962, -0.01434, -0.039505,
0.065133, 0.024321, 0.038473, 0.062438}};
const int input_sequence_size = lstm.sequence_length() * lstm.num_inputs();
EXPECT_EQ(input_sequence_size, 20);
float* batch0_start = lstm_input[0];
float* batch0_end = batch0_start + input_sequence_size;
lstm.SetInput(0, batch0_start, batch0_end);
float* batch1_start = lstm_input[1];
float* batch1_end = batch1_start + input_sequence_size;
lstm.SetInput(input_sequence_size, batch1_start, batch1_end);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
const int output_sequence_size =
lstm.sequence_length() * lstm.num_fw_outputs();
EXPECT_EQ(output_sequence_size, 64);
std::vector<float> expected;
const float* golden_start_batch0 = lstm_fw_golden_output[0];
const float* golden_end_batch0 = golden_start_batch0 + output_sequence_size;
expected.insert(expected.end(), golden_start_batch0, golden_end_batch0);
const float* golden_start_batch1 = lstm_fw_golden_output[1];
const float* golden_end_batch1 = golden_start_batch1 + output_sequence_size;
expected.insert(expected.end(), golden_start_batch1, golden_end_batch1);
EXPECT_THAT(lstm.GetFwOutput(), ElementsAreArray(ArrayFloatNear(expected)));
expected.clear();
golden_start_batch0 = lstm_combined_golden_output[0];
golden_end_batch0 = golden_start_batch0 + output_sequence_size;
expected.insert(expected.end(), golden_start_batch0, golden_end_batch0);
golden_start_batch1 = lstm_combined_golden_output[1];
golden_end_batch1 = golden_start_batch1 + output_sequence_size;
expected.insert(expected.end(), golden_start_batch1, golden_end_batch1);
std::vector<float> combined;
for (int i = 0; i < lstm.GetFwOutput().size(); ++i) {
combined.push_back(lstm.GetFwOutput()[i] + lstm.GetBwOutput()[i]);
}
EXPECT_THAT(combined, ElementsAreArray(ArrayFloatNear(expected)));
}
TEST_P(LSTMOpTest, BlackBoxTestWithAuxInputZeroAuxWeight) {
const int n_batch = 1;
const int n_input = 2;
const int n_cell = 4;
const int n_output = 4;
const int sequence_length = 3;
auto params = GetParam();
const bool quantize_weights = std::get<0>(params);
const bool asymmetric_quantize_inputs = std::get<1>(params);
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, false,
false, false,
false, false,
true, 0.0,
0.0, quantize_weights, true,
{
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
},
asymmetric_quantize_inputs);
lstm.SetInputToInputWeights({-0.45018822, -0.02338299, -0.0870589,
-0.34550029, 0.04266912, -0.15680569,
-0.34856534, 0.43890524});
lstm.SetInputToCellWeights({-0.50013041, 0.1370284, 0.11810488, 0.2013163,
-0.20583314, 0.44344562, 0.22077113,
-0.29909778});
lstm.SetInputToForgetWeights({0.09701663, 0.20334584, -0.50592935,
-0.31343272, -0.40032279, 0.44781327,
0.01387155, -0.35593212});
lstm.SetInputToOutputWeights({-0.25065863, -0.28290087, 0.04613829,
0.40525138, 0.44272184, 0.03897077, -0.1556896,
0.19487578});
lstm.SetInputGateBias({0., 0., 0., 0.});
lstm.SetCellBias({0., 0., 0., 0.});
lstm.SetForgetGateBias({1., 1., 1., 1.});
lstm.SetOutputGateBias({0., 0., 0., 0.});
lstm.SetRecurrentToInputWeights(
{-0.0063535, -0.2042388, 0.31454784, -0.35746509, 0.28902304, 0.08183324,
-0.16555229, 0.02286911, -0.13566875, 0.03034258, 0.48091322,
-0.12528998, 0.24077177, -0.51332325, -0.33502164, 0.10629296});
lstm.SetRecurrentToCellWeights(
{-0.3407414, 0.24443203, -0.2078532, 0.26320225, 0.05695659, -0.00123841,
-0.4744786, -0.35869038, -0.06418842, -0.13502428, -0.501764, 0.22830659,
-0.46367589, 0.26016325, -0.03894562, -0.16368064});
lstm.SetRecurrentToForgetWeights(
{-0.48684245, -0.06655136, 0.42224967, 0.2112639, 0.27654213, 0.20864892,
-0.07646349, 0.45877004, 0.00141793, -0.14609534, 0.36447752, 0.09196436,
0.28053468, 0.01560611, -0.20127171, -0.01140004});
lstm.SetRecurrentToOutputWeights(
{0.43385774, -0.17194885, 0.2718237, 0.09215671, 0.24107647, -0.39835793,
0.18212086, 0.01301402, 0.48572797, -0.50656658, 0.20047462, -0.20607421,
-0.51818722, -0.15390486, 0.0468148, 0.39922136});
static float lstm_input[] = {2., 3., 3., 4., 1., 1.};
static float lstm_fw_golden_output[] = {
-0.02973187, 0.1229473, 0.20885126, -0.15358765,
-0.03716109, 0.12507336, 0.41193449, -0.20860538,
-0.15053082, 0.09120187, 0.24278517, -0.12222792};
static float lstm_bw_golden_output[] = {
-0.0806187, 0.139077, 0.400476, -0.197842, -0.0332076, 0.123838,
0.309777, -0.17621, -0.0490733, 0.0739237, 0.067706, -0.0208124};
float* batch0_start = lstm_input;
float* batch0_end = batch0_start + lstm.num_inputs() * lstm.sequence_length();
lstm.SetInput(0, batch0_start, batch0_end);
lstm.SetAuxInput(0, batch0_start, batch0_end);
std::vector<float> dummy_weights(n_cell * n_input, 0.0f);
lstm.SetAuxInputToInputWeights(dummy_weights);
lstm.SetAuxInputToForgetWeights(dummy_weights);
lstm.SetAuxInputToCellWeights(dummy_weights);
lstm.SetAuxInputToOutputWeights(dummy_weights);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
float* fw_golden_start = lstm_fw_golden_output;
float* fw_golden_end =
fw_golden_start + lstm.num_fw_outputs() * lstm.sequence_length();
std::vector<float> fw_expected;
fw_expected.insert(fw_expected.end(), fw_golden_start, fw_golden_end);
EXPECT_THAT(lstm.GetFwOutput(),
ElementsAreArray(
ArrayFloatNear(fw_expected, quantize_weights ? 1e-2 : 1e-5)));
float* bw_golden_start = lstm_bw_golden_output;
float* bw_golden_end =
bw_golden_start + lstm.num_bw_outputs() * lstm.sequence_length();
std::vector<float> bw_expected;
bw_expected.insert(bw_expected.end(), bw_golden_start, bw_golden_end);
EXPECT_THAT(lstm.GetBwOutput(),
ElementsAreArray(
ArrayFloatNear(bw_expected, quantize_weights ? 1e-2 : 1e-5)));
}
TEST_P(LSTMOpTest, BlackBoxTestWithAuxInput) {
const int n_batch = 1;
const int n_input = 2;
const int n_cell = 4;
const int n_output = 4;
const int sequence_length = 3;
auto params = GetParam();
const bool quantize_weights = std::get<0>(params);
const bool asymmetric_quantize_inputs = std::get<1>(params);
BidirectionalLSTMOpModel lstm(
n_batch, n_input, n_cell, n_output, sequence_length, false,
false, false,
false, false,
true, 0.0,
0.0, quantize_weights, true,
{
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{n_cell, n_output},
{0},
{0},
{0},
{n_cell},
{n_cell},
{n_cell},
{n_cell},
{0, 0},
{0},
{n_batch, n_output},
{n_batch, n_cell},
{n_batch, n_output},
{n_batch, n_cell},
{sequence_length, n_batch, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
{n_cell, n_input},
},
asymmetric_quantize_inputs);
lstm.SetInputToInputWeights({-0.45018822, -0.02338299, -0.0870589,
-0.34550029, 0.04266912, -0.15680569,
-0.34856534, 0.43890524});
lstm.SetInputToCellWeights({-0.50013041, 0.1370284, 0.11810488, 0.2013163,
-0.20583314, 0.44344562, 0.22077113,
-0.29909778});
lstm.SetInputToForgetWeights({0.09701663, 0.20334584, -0.50592935,
-0.31343272, -0.40032279, 0.44781327,
0.01387155, -0.35593212});
lstm.SetInputToOutputWeights({-0.25065863, -0.28290087, 0.04613829,
0.40525138, 0.44272184, 0.03897077, -0.1556896,
0.19487578});
lstm.SetInputGateBias({0., 0., 0., 0.});
lstm.SetCellBias({0., 0., 0., 0.});
lstm.SetForgetGateBias({1., 1., 1., 1.});
lstm.SetOutputGateBias({0., 0., 0., 0.});
lstm.SetRecurrentToInputWeights(
{-0.0063535, -0.2042388, 0.31454784, -0.35746509, 0.28902304, 0.08183324,
-0.16555229, 0.02286911, -0.13566875, 0.03034258, 0.48091322,
-0.12528998, 0.24077177, -0.51332325, -0.33502164, 0.10629296});
lstm.SetRecurrentToCellWeights(
{-0.3407414, 0.24443203, -0.2078532, 0.26320225, 0.05695659, -0.00123841,
-0.4744786, -0.35869038, -0.06418842, -0.13502428, -0.501764, 0.22830659,
-0.46367589, 0.26016325, -0.03894562, -0.16368064});
lstm.SetRecurrentToForgetWeights(
{-0.48684245, -0.06655136, 0.42224967, 0.2112639, 0.27654213, 0.20864892,
-0.07646349, 0.45877004, 0.00141793, -0.14609534, 0.36447752, 0.09196436,
0.28053468, 0.01560611, -0.20127171, -0.01140004});
lstm.SetRecurrentToOutputWeights(
{0.43385774, -0.17194885, 0.2718237, 0.09215671, 0.24107647, -0.39835793,
0.18212086, 0.01301402, 0.48572797, -0.50656658, 0.20047462, -0.20607421,
-0.51818722, -0.15390486, 0.0468148, 0.39922136});
static float lstm_input[] = {2., 3., 3., 4., 1., 1.};
static float lstm_fw_golden_output[] = {
0.153335, 0.542754, 0.708602, 0.742855, 0.247581, 0.835739,
0.947797, 0.958177, 0.410892, 0.672268, 0.761909, 0.829133};
static float lstm_bw_golden_output[] = {
0.342275, 0.883431, 0.955930, 0.975621, 0.204939, 0.806858,
0.914849, 0.934871, 0.123236, 0.373087, 0.465377, 0.517630};
lstm.SetAuxInputToInputWeights({0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8});
lstm.SetAuxInputToForgetWeights({0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 1.0});
lstm.SetAuxInputToCellWeights({0.5, 0.6, 0.7, 0.8, 0.5, 0.6, 0.7, 0.8});
lstm.SetAuxInputToOutputWeights({0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8});
float* batch0_start = lstm_input;
float* batch0_end = batch0_start + lstm.num_inputs() * lstm.sequence_length();
lstm.SetInput(0, batch0_start, batch0_end);
lstm.SetAuxInput(0, batch0_start, batch0_end);
ASSERT_EQ(lstm.Invoke(), kTfLiteOk);
float* fw_golden_start = lstm_fw_golden_output;
float* fw_golden_end =
fw_golden_start + lstm.num_fw_outputs() * lstm.sequence_length();
std::vector<float> fw_expected;
fw_expected.insert(fw_expected.end(), fw_golden_start, fw_golden_end);
EXPECT_THAT(lstm.GetFwOutput(),
ElementsAreArray(
ArrayFloatNear(fw_expected, quantize_weights ? 1e-2 : 1e-5)));
float* bw_golden_start = lstm_bw_golden_output;
float* bw_golden_end =
bw_golden_start + lstm.num_bw_outputs() * lstm.sequence_length();
std::vector<float> bw_expected;
bw_expected.insert(bw_expected.end(), bw_golden_start, bw_golden_end);
EXPECT_THAT(lstm.GetBwOutput(),
ElementsAreArray(
ArrayFloatNear(bw_expected, quantize_weights ? 1e-2 : 1e-5)));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/bidirectional_sequence_lstm.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/kernels/bidirectional_sequence_lstm_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
a162ff7a-8c7a-4e67-a748-3a3d8af56cdc | cpp | tensorflow/tensorflow | hlo_value_semantics_analysis | third_party/xla/xla/service/hlo_value_semantics_analysis.cc | third_party/xla/xla/service/hlo_value_semantics_analysis_test.cc | #include "xla/service/hlo_value_semantics_analysis.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <memory>
#include <numeric>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/dfs_hlo_visitor.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/service/hlo_value.h"
#include "xla/shape.h"
#include "xla/shape_tree.h"
#include "xla/shape_util.h"
#include "xla/side_effect_util.h"
#include "xla/util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace xla {
SendRecvGroupMap::SendRecvGroupMap(const HloModule& hlo_module) {
for (HloComputation* computation : hlo_module.computations()) {
for (HloInstruction* instruction : computation->instructions()) {
if (instruction->opcode() != HloOpcode::kSend &&
instruction->opcode() != HloOpcode::kRecv) {
continue;
}
std::string rendezvous = instruction->frontend_attributes().map().at(
kXlaHostTransferRendezvousNameAttr);
auto send_recv_iter = host_transfer_rendezvous_map_.find(rendezvous);
if (send_recv_iter == host_transfer_rendezvous_map_.end()) {
auto insert_success = host_transfer_rendezvous_map_.insert(
{rendezvous, SendRecvGroup{nullptr, nullptr}});
send_recv_iter = insert_success.first;
}
if (instruction->opcode() == HloOpcode::kSend) {
send_recv_iter->second.send = instruction;
} else {
send_recv_iter->second.recv = instruction;
}
}
}
}
absl::StatusOr<HloInstruction*> SendRecvGroupMap::GetMatchingSendOrRecv(
HloInstruction* send_or_recv) const {
if (send_or_recv->opcode() != HloOpcode::kSend &&
send_or_recv->opcode() != HloOpcode::kRecv) {
return InvalidArgument("Expecting only send or recv");
}
std::string rendezvous = send_or_recv->frontend_attributes().map().at(
kXlaHostTransferRendezvousNameAttr);
auto send_recv_iter = host_transfer_rendezvous_map_.find(rendezvous);
if (send_recv_iter == host_transfer_rendezvous_map_.end()) {
return Internal("Missing send or recv from send recv group.");
}
if (send_or_recv->opcode() == HloOpcode::kSend) {
return send_recv_iter->second.recv;
}
return send_recv_iter->second.send;
}
bool HloPreOrderDFS::IsReady(const HloInstruction* instruction) const {
for (HloInstruction* user : instruction->users()) {
if (!visited_.contains(user)) {
return false;
}
}
return true;
}
namespace {
std::vector<HloInstruction*> GetAllInstructionsWithZeroUsers(
const HloComputation& computation) {
std::vector<HloInstruction*> results;
for (HloInstruction* instruction : computation.instructions()) {
if (instruction->users().empty()) {
results.push_back(instruction);
}
}
return results;
}
}
absl::Status HloPreOrderDFS::Run(const HloComputation& computation,
DfsHloVisitorBase<HloInstruction*>* visitor) {
stack_.clear();
visited_.clear();
std::vector<HloInstruction*> roots =
GetAllInstructionsWithZeroUsers(computation);
for (HloInstruction* root : roots) {
stack_.push_back(root);
}
while (!stack_.empty()) {
HloInstruction* to_visit = stack_.back();
stack_.pop_back();
if (visited_.contains(to_visit)) {
continue;
}
visited_.insert(to_visit);
for (HloInstruction* operand : to_visit->mutable_operands()) {
if (IsReady(operand)) {
stack_.push_back(operand);
}
}
TF_RETURN_IF_ERROR(visitor->Preprocess(to_visit));
TF_RETURN_IF_ERROR(to_visit->Visit(visitor));
TF_RETURN_IF_ERROR(visitor->Postprocess(to_visit));
}
return absl::OkStatus();
}
namespace {
template <typename T>
std::string ToString(T element) {
return absl::StrCat(element);
}
template <>
std::string ToString(const HloValueSemantics* element) {
return element->ToString();
}
template <typename T>
std::string ToString(const ShapeTree<T>& tree) {
std::string str;
tree.ForEachElement([&str, &tree](const ShapeIndex& shape_index, T element) {
auto subshape = ShapeUtil::GetSubshape(tree.shape(), (shape_index));
absl::StrAppend(&str, shape_index.ToString(), ", ", subshape.ToString(),
": ", ToString(element), "\n");
});
return str;
}
}
absl::Status EinsumDepthAnalysis::RunInternal(
const HloComputation& computation,
const std::optional<ShapeTree<int>>& root_depth) {
std::vector<HloInstruction*> roots =
GetAllInstructionsWithZeroUsers(computation);
for (HloInstruction* root : roots) {
if (root == computation.root_instruction()) {
if (root_depth.has_value()) {
TF_RETURN_IF_ERROR(SetInstructionDepth(root, *root_depth));
} else {
TF_RETURN_IF_ERROR(SetInstructionDepth(root, 0));
}
} else {
GetOrCreateDepthTree(root);
}
}
HloPreOrderDFS dfs;
return dfs.Run(computation, this);
}
absl::StatusOr<std::unique_ptr<EinsumDepthAnalysis>> EinsumDepthAnalysis::Run(
const HloComputation& computation,
const SendRecvGroupMap& send_recv_group_map) {
EinsumDepthAnalysis* analysis_ptr =
new EinsumDepthAnalysis(send_recv_group_map);
std::unique_ptr<EinsumDepthAnalysis> analysis(analysis_ptr);
TF_RETURN_IF_ERROR(analysis->RunInternal(computation, std::nullopt));
return analysis;
}
namespace {
int MergeDepth(int original_depth, int new_depth) {
if (new_depth >= 0) {
return std::max(original_depth, new_depth);
}
if (new_depth < 0 && original_depth < 0) {
return std::min(original_depth, new_depth);
}
return original_depth;
}
void SetDepth(ShapeTree<int>& depth_tree, int depth) {
depth_tree.ForEachMutableElement(
[depth, &depth_tree](const ShapeIndex& shape_index, int* depth_ptr) {
if (depth_tree.IsLeaf(shape_index)) {
*depth_ptr = MergeDepth(*depth_ptr, depth);
}
});
}
void SetDepth(ShapeTree<int>& depth_tree, const ShapeTree<int>& source) {
depth_tree.ForEachMutableElement(
[&depth_tree, &source](const ShapeIndex& shape_index, int* depth_ptr) {
if (depth_tree.IsLeaf(shape_index)) {
*depth_ptr = MergeDepth(*depth_ptr, source.element(shape_index));
}
});
}
int GetMaxDepth(const ShapeTree<int>& depth_tree) {
int max_depth = -1;
depth_tree.ForEachElement(
[&max_depth](const ShapeIndex& shape_index, int depth) {
max_depth = std::max(max_depth, depth);
return absl::OkStatus();
});
if (max_depth >= 0) {
return max_depth;
}
depth_tree.ForEachElement(
[&max_depth](const ShapeIndex& shape_index, int depth) {
max_depth = std::min(max_depth, depth);
return absl::OkStatus();
});
return max_depth;
}
void SetDepthFromTupleDepth(ShapeTree<int>& depth_tree,
const ShapeTree<int>& tuple_depth_tree,
int tuple_index) {
depth_tree.ForEachMutableElement(
[&depth_tree, &tuple_depth_tree, tuple_index](
const ShapeIndex& shape_index, int* depth_ptr) {
if (depth_tree.IsLeaf(shape_index)) {
ShapeIndex output_index = shape_index;
output_index.push_front(tuple_index);
*depth_ptr =
MergeDepth(*depth_ptr, tuple_depth_tree.element(output_index));
}
});
}
}
ShapeTree<int>& EinsumDepthAnalysis::GetOrCreateDepthTree(
const HloInstruction* instruction) {
auto depth_iter = einsum_depth_map_.find(instruction);
if (depth_iter == einsum_depth_map_.end()) {
ShapeTree<int> depth_tree(instruction->shape(), -1);
auto inserted = einsum_depth_map_.insert(
std::make_pair(instruction, std::move(depth_tree)));
depth_iter = inserted.first;
}
return depth_iter->second;
}
ShapeTree<int>& EinsumDepthAnalysis::GetDepthTreeOrDie(
const HloInstruction* instruction) {
auto depth_iter = einsum_depth_map_.find(instruction);
CHECK(depth_iter != einsum_depth_map_.end())
<< "No depth tree found for instruction: " << instruction->ToString();
return depth_iter->second;
}
absl::Status EinsumDepthAnalysis::SetInstructionDepth(
const HloInstruction* instruction, int depth) {
ShapeTree<int>& depth_tree = GetOrCreateDepthTree(instruction);
SetDepth(depth_tree, depth);
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::SetInstructionDepth(
const HloInstruction* instruction, const ShapeTree<int>& depth) {
ShapeTree<int>& depth_tree = GetOrCreateDepthTree(instruction);
SetDepth(depth_tree, depth);
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::SetInstructionDepthFromTupleDepth(
const HloInstruction* instruction, const ShapeTree<int>& tuple_depth_tree,
int tuple_index) {
ShapeTree<int>& depth_tree = GetOrCreateDepthTree(instruction);
SetDepthFromTupleDepth(depth_tree, tuple_depth_tree, tuple_index);
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::DefaultAction(HloInstruction* instruction) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(instruction);
int max_depth = GetMaxDepth(depth_tree);
for (int operand_index = 0; operand_index < instruction->operand_count();
++operand_index) {
const HloInstruction* operand = instruction->operand(operand_index);
TF_RETURN_IF_ERROR(SetInstructionDepth(operand, max_depth));
}
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleTuple(HloInstruction* tuple) {
return HandleTupleLike(tuple);
}
absl::Status EinsumDepthAnalysis::HandleAllReduce(HloInstruction* all_reduce) {
if (all_reduce->shape().IsArray()) {
return DefaultAction(all_reduce);
}
return HandleTupleLike(all_reduce);
}
absl::Status EinsumDepthAnalysis::HandleTupleLike(HloInstruction* tuple_like) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(tuple_like);
for (int operand_index = 0; operand_index < tuple_like->operand_count();
++operand_index) {
HloInstruction* operand = tuple_like->mutable_operand(operand_index);
ShapeTree<int>& operand_depth = GetOrCreateDepthTree(operand);
SetDepthFromTupleDepth(operand_depth, depth_tree, operand_index);
}
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleGetTupleElement(
HloInstruction* get_tuple_element) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(get_tuple_element);
HloInstruction* operand = get_tuple_element->mutable_operand(0);
int tuple_index = get_tuple_element->tuple_index();
ShapeTree<int>& operand_depth = GetOrCreateDepthTree(operand);
operand_depth.ForEachMutableElement(
[&operand_depth, &depth_tree, tuple_index](const ShapeIndex& shape_index,
int* depth_ptr) {
if (shape_index.empty() || shape_index.front() != tuple_index) {
return;
}
if (operand_depth.IsLeaf(shape_index)) {
ShapeIndex output_index = shape_index;
output_index.pop_front();
*depth_ptr = MergeDepth(*depth_ptr, depth_tree.element(output_index));
}
});
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleDepthIncrementInstruction(
HloInstruction* instruction) {
ShapeTree<int>& depth_tree = GetDepthTreeOrDie(instruction);
int instruction_depth = depth_tree.element({});
for (HloInstruction* operand : instruction->mutable_operands()) {
TF_RETURN_IF_ERROR(SetInstructionDepth(
operand, instruction_depth >= 0 ? instruction_depth + 1
: instruction_depth - 1));
}
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleDot(HloInstruction* dot) {
return HandleDepthIncrementInstruction(dot);
}
absl::Status EinsumDepthAnalysis::HandleConvolution(
HloInstruction* convolution) {
return HandleDepthIncrementInstruction(convolution);
}
absl::Status EinsumDepthAnalysis::HandleCall(HloInstruction* call) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(call);
return HandleCalledComputation(*call->called_computations()[0], depth_tree,
call->operands());
}
absl::Status EinsumDepthAnalysis::HandleFusion(HloInstruction* fusion) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(fusion);
return HandleCalledComputation(*fusion->called_computations()[0], depth_tree,
fusion->operands());
}
absl::Status EinsumDepthAnalysis::HandleWhile(HloInstruction* xla_while) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(xla_while);
int max_depth = GetMaxDepth(depth_tree);
HloComputation* condition_computation = xla_while->while_condition();
HloInstruction* condition_root = condition_computation->root_instruction();
ShapeTree<int> condition_depth(condition_root->shape(), max_depth);
TF_RETURN_IF_ERROR(HandleCalledComputation(
*condition_computation, condition_depth, xla_while->operands()));
const ShapeTree<int>* root_depth_ptr = &depth_tree;
HloComputation* body_computation = xla_while->while_body();
bool run_depth_propagation_on_body = true;
ShapeTree<int>& root_depth =
GetOrCreateDepthTree(body_computation->root_instruction());
while (run_depth_propagation_on_body) {
run_depth_propagation_on_body = false;
TF_RETURN_IF_ERROR(HandleCalledComputation(
*body_computation, *root_depth_ptr, xla_while->operands()));
HloInstruction* operand = body_computation->parameter_instruction(0);
const ShapeTree<int>& operand_depth = GetOrCreateDepthTree(operand);
root_depth.ForEachMutableElement(
[&run_depth_propagation_on_body, &root_depth, &operand_depth](
const ShapeIndex& shape_index, int* depth_ptr) {
if (!root_depth.IsLeaf(shape_index)) {
return;
}
if (root_depth.element(shape_index) < 0 &&
operand_depth.element(shape_index) >= 0) {
*depth_ptr = operand_depth.element(shape_index);
run_depth_propagation_on_body = true;
}
});
root_depth_ptr = &root_depth;
}
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleConditional(
HloInstruction* conditional) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(conditional);
TF_RETURN_IF_ERROR(
SetInstructionDepth(conditional->operands()[0], depth_tree));
for (int i = 0; i < conditional->branch_count(); ++i) {
TF_RETURN_IF_ERROR(
HandleCalledComputation(*conditional->called_computations()[i],
depth_tree, {conditional->operands()[i + 1]}));
}
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleCalledComputation(
const HloComputation& called_computation, const ShapeTree<int>& root_depth,
absl::Span<HloInstruction* const> operands) {
TF_RETURN_IF_ERROR(RunInternal(called_computation,
std::optional<ShapeTree<int>>(root_depth)));
for (int i = 0; i < operands.size(); ++i) {
HloInstruction* operand = operands[i];
HloInstruction* parameter = called_computation.parameter_instruction(i);
const ShapeTree<int>& parameter_depth = GetOrCreateDepthTree(parameter);
TF_RETURN_IF_ERROR(SetInstructionDepth(operand, parameter_depth));
}
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleAfterAll(HloInstruction* after_all) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(after_all);
int max_depth = GetMaxDepth(depth_tree);
for (HloInstruction* operand_token : after_all->mutable_operands()) {
CHECK(operand_token->shape().IsToken());
TF_RETURN_IF_ERROR(SetInstructionDepth(operand_token, max_depth));
}
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleSend(HloInstruction* send) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(send);
HloInstruction* send_buffer = send->mutable_operand(0);
ShapeTree<int>& send_buffer_depth = GetOrCreateDepthTree(send_buffer);
SetDepthFromTupleDepth(send_buffer_depth, depth_tree, 0);
int max_depth = GetMaxDepth(depth_tree);
HloInstruction* token = send->mutable_operand(1);
return SetInstructionDepth(token, max_depth);
}
absl::Status EinsumDepthAnalysis::HandleRecv(HloInstruction* recv) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(recv);
TF_ASSIGN_OR_RETURN(HloInstruction * send,
send_recv_group_map_->GetMatchingSendOrRecv(recv));
CHECK(send) << "recv: " << recv->name()
<< " not found in send_recv_group_map: " << recv->ToString();
ShapeTree<int>& send_depth = GetOrCreateDepthTree(send);
int max_depth = GetMaxDepth(depth_tree);
send_depth.ForEachMutableElement([&depth_tree, &send_depth, max_depth](
const ShapeIndex& index, int* depth) {
if (!send_depth.IsLeaf(index)) {
return;
}
if (index.front() == 0) {
*depth = MergeDepth(*depth, depth_tree.element(index));
return;
}
*depth = MergeDepth(*depth, max_depth);
});
HloInstruction* after_all = recv->mutable_operand(0);
return SetInstructionDepth(after_all, max_depth);
}
absl::Status EinsumDepthAnalysis::HandleSendDone(HloInstruction* send_done) {
HloInstruction* send = send_done->mutable_operand(0);
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(send_done);
int max_depth = GetMaxDepth(depth_tree);
return SetInstructionDepth(send, max_depth);
}
absl::Status EinsumDepthAnalysis::HandleRecvDone(HloInstruction* recv_done) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(recv_done);
int max_depth = GetMaxDepth(depth_tree);
HloInstruction* recv = recv_done->mutable_operand(0);
ShapeTree<int>& recv_depth = GetOrCreateDepthTree(recv);
recv_depth.ForEachMutableElement([&depth_tree, &recv_depth, max_depth](
const ShapeIndex& index, int* depth) {
if (!recv_depth.IsLeaf(index)) {
return;
}
if (index.front() == 0) {
*depth = MergeDepth(*depth, depth_tree.element(index));
return;
}
*depth = MergeDepth(*depth, max_depth);
});
return absl::OkStatus();
}
absl::Status EinsumDepthAnalysis::HandleAsyncStart(
HloInstruction* async_start) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(async_start);
TF_ASSIGN_OR_RETURN(ShapeTree<int> output_depth_tree,
depth_tree.SubShapeTree({1}));
return HandleCalledComputation(*(async_start->async_wrapped_computation()),
output_depth_tree, async_start->operands());
}
absl::Status EinsumDepthAnalysis::HandleAsyncDone(HloInstruction* async_done) {
const ShapeTree<int>& depth_tree = GetDepthTreeOrDie(async_done);
HloInstruction* async_start = async_done->mutable_operand(0);
ShapeTree<int>& async_start_depth = GetOrCreateDepthTree(async_start);
async_start_depth.ForEachMutableElement(
[&depth_tree, &async_start_depth](const ShapeIndex& index, int* depth) {
if (!async_start_depth.IsLeaf(index)) {
return;
}
if (index.front() == 1) {
ShapeIndex output_index = index;
output_index.pop_front();
*depth = MergeDepth(*depth, depth_tree.element(output_index));
}
});
return absl::OkStatus();
}
namespace {
int MergeHeight(int original_height, int new_height) {
return std::max(original_height, new_height);
}
void SetHeight(ShapeTree<int>& height_tree, int height) {
height_tree.ForEachMutableElement(
[height, &height_tree](const ShapeIndex& shape_index, int* height_ptr) {
if (height_tree.IsLeaf(shape_index)) {
*height_ptr = MergeHeight(*height_ptr, height);
}
});
}
void SetHeight(ShapeTree<int>& height_tree, const ShapeTree<int>& source,
const ShapeIndex& source_index = {},
const ShapeIndex& target_index = {}) {
height_tree.ForEachMutableElement(
[&source, &source_index, &target_index](const ShapeIndex& shape_index,
int* height_ptr) {
if (shape_index.size() < target_index.size()) {
return;
}
for (int i = 0; i < target_index.size(); ++i) {
if (shape_index[i] != target_index[i]) {
return;
}
}
ShapeIndex complete_source_index = source_index;
for (int i = target_index.size(); i < shape_index.size(); ++i) {
complete_source_index.push_back(shape_index[i]);
}
*height_ptr =
MergeHeight(*height_ptr, source.element(complete_source_index));
});
}
int GetMaxHeight(const ShapeTree<int>& height_tree) {
int max_height = 0;
height_tree.ForEachElement(
[&max_height](const ShapeIndex& shape_index, int height) {
max_height = std::max(max_height, height);
return absl::OkStatus();
});
return max_height;
}
int GetMaxOperandHeight(HloInstruction* instruction,
const EinsumHeightMap& einsum_height_map) {
int max_height = 0;
for (HloInstruction* operand : instruction->mutable_operands()) {
auto operand_height_iter = einsum_height_map.find(operand);
CHECK(operand_height_iter != einsum_height_map.end())
<< "operand: " << operand->name();
const ShapeTree<int>& operand_height_tree = operand_height_iter->second;
int max_operand_height = GetMaxHeight(operand_height_tree);
max_height = std::max(max_height, max_operand_height);
}
return max_height;
}
}
absl::StatusOr<std::unique_ptr<EinsumHeightAnalysis>> EinsumHeightAnalysis::Run(
const HloComputation& computation,
const SendRecvGroupMap& send_recv_group_map) {
EinsumHeightAnalysis* analysis_ptr =
new EinsumHeightAnalysis(send_recv_group_map);
std::unique_ptr<EinsumHeightAnalysis> analysis(analysis_ptr);
TF_RETURN_IF_ERROR(analysis->RunInternal(computation, {}));
TF_RETURN_IF_ERROR(analysis->RunInternal(computation, {}));
return analysis;
}
absl::Status EinsumHeightAnalysis::RunInternal(
const HloComputation& computation,
absl::Span<HloInstruction* const> operands) {
return HandleCalledComputation(computation, operands);
}
ShapeTree<int>& EinsumHeightAnalysis::GetOrCreateHeightTree(
const HloInstruction* instruction) {
auto height_iter = einsum_height_map_.find(instruction);
if (height_iter == einsum_height_map_.end()) {
ShapeTree<int> height_tree(instruction->shape(), 0);
auto inserted = einsum_height_map_.insert(
std::make_pair(instruction, std::move(height_tree)));
height_iter = inserted.first;
}
return height_iter->second;
}
ShapeTree<int>& EinsumHeightAnalysis::GetHeightTreeOrDie(
const HloInstruction* instruction) {
auto height_iter = einsum_height_map_.find(instruction);
CHECK(height_iter != einsum_height_map_.end());
return height_iter->second;
}
bool EinsumHeightAnalysis::HasHeightFor(
const HloInstruction* instruction) const {
return einsum_height_map_.contains(instruction);
}
absl::Status EinsumHeightAnalysis::SetInstructionHeight(
const HloInstruction* instruction, int height) {
ShapeTree<int>& height_tree = GetOrCreateHeightTree(instruction);
SetHeight(height_tree, height);
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::SetInstructionHeight(
const HloInstruction* instruction, const ShapeTree<int>& height) {
ShapeTree<int>& height_tree = GetOrCreateHeightTree(instruction);
SetHeight(height_tree, height);
return absl::OkStatus();
}
#define RETURN_IF_HEIGHT_EXISTS(instruction) \
if (HasHeightFor(instruction)) { \
return absl::OkStatus(); \
}
absl::Status EinsumHeightAnalysis::HandleHeightIncrementInstruction(
HloInstruction* instruction) {
ShapeTree<int>& height_tree = GetOrCreateHeightTree(instruction);
for (HloInstruction* operand : instruction->mutable_operands()) {
const ShapeTree<int>& operand_height_tree = GetHeightTreeOrDie(operand);
SetHeight(height_tree, operand_height_tree.element({}) + 1);
}
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleCalledComputation(
const HloComputation& computation,
absl::Span<HloInstruction* const> operands) {
if (!operands.empty()) {
if (computation.num_parameters() != operands.size()) {
return absl::InvalidArgumentError(absl::StrCat(
operands.size(), " operands were passed for the computation ",
computation.name(), " with ", computation.num_parameters(),
" parameters."));
}
for (int parameter_index = 0;
parameter_index < computation.num_parameters(); ++parameter_index) {
HloInstruction* parameter =
computation.parameter_instruction(parameter_index);
HloInstruction* operand = operands[parameter_index];
const ShapeTree<int>& operand_height_tree = GetHeightTreeOrDie(operand);
TF_RETURN_IF_ERROR(SetInstructionHeight(parameter, operand_height_tree));
}
}
for (HloInstruction* instruction : computation.instructions()) {
if (instruction->user_count() == 0) {
TF_RETURN_IF_ERROR(instruction->Accept(this));
}
}
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::DefaultAction(HloInstruction* instruction) {
RETURN_IF_HEIGHT_EXISTS(instruction);
int instruction_height = GetMaxOperandHeight(instruction, einsum_height_map_);
return SetInstructionHeight(instruction, instruction_height);
}
absl::Status EinsumHeightAnalysis::HandleTupleLike(HloInstruction* tuple_like) {
ShapeTree<int>& height_tree = GetOrCreateHeightTree(tuple_like);
height_tree.ForEachMutableElement([&height_tree, tuple_like, this](
const ShapeIndex& index, int* height) {
if (!height_tree.IsLeaf(index)) {
return;
}
int operand_index = index.front();
const HloInstruction* operand = tuple_like->operand(operand_index);
const ShapeTree<int>& operand_height_tree = GetHeightTreeOrDie(operand);
ShapeIndex source_index = index;
source_index.pop_front();
*height = MergeHeight(*height, operand_height_tree.element(source_index));
});
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleTuple(HloInstruction* tuple) {
RETURN_IF_HEIGHT_EXISTS(tuple);
return HandleTupleLike(tuple);
}
absl::Status EinsumHeightAnalysis::HandleGetTupleElement(
HloInstruction* get_tuple_element) {
RETURN_IF_HEIGHT_EXISTS(get_tuple_element);
ShapeTree<int>& height_tree = GetOrCreateHeightTree(get_tuple_element);
const ShapeTree<int>& tuple_height_tree =
GetHeightTreeOrDie(get_tuple_element->operand(0));
int tuple_index = get_tuple_element->tuple_index();
SetHeight(height_tree, tuple_height_tree, {tuple_index}, {});
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleDot(HloInstruction* dot) {
RETURN_IF_HEIGHT_EXISTS(dot);
return HandleHeightIncrementInstruction(dot);
}
absl::Status EinsumHeightAnalysis::HandleConvolution(
HloInstruction* convolution) {
RETURN_IF_HEIGHT_EXISTS(convolution);
return HandleHeightIncrementInstruction(convolution);
}
absl::Status EinsumHeightAnalysis::HandleCall(HloInstruction* call) {
RETURN_IF_HEIGHT_EXISTS(call);
TF_RETURN_IF_ERROR(HandleCalledComputation(*(call->called_computations()[0]),
call->mutable_operands()));
const ShapeTree<int>& root_height_tree =
GetHeightTreeOrDie(call->called_computations()[0]->root_instruction());
TF_RETURN_IF_ERROR(SetInstructionHeight(call, root_height_tree));
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleFusion(HloInstruction* fusion) {
RETURN_IF_HEIGHT_EXISTS(fusion);
return HandleCall(fusion);
}
absl::Status EinsumHeightAnalysis::HandleWhile(HloInstruction* xla_while) {
RETURN_IF_HEIGHT_EXISTS(xla_while);
TF_RETURN_IF_ERROR(HandleCalledComputation(*(xla_while->while_condition()),
xla_while->mutable_operands()));
TF_RETURN_IF_ERROR(HandleCalledComputation(*(xla_while->while_body()),
xla_while->mutable_operands()));
const ShapeTree<int>& root_height_tree =
GetHeightTreeOrDie(xla_while->while_body()->root_instruction());
return SetInstructionHeight(xla_while, root_height_tree);
}
absl::Status EinsumHeightAnalysis::HandleConditional(
HloInstruction* conditional) {
RETURN_IF_HEIGHT_EXISTS(conditional);
ShapeTree<int>& height_tree = GetOrCreateHeightTree(conditional);
for (size_t i = 0; i < conditional->branch_count(); ++i) {
HloComputation* computation = conditional->branch_computation(i);
TF_RETURN_IF_ERROR(HandleCalledComputation(
*computation, {conditional->mutable_operands()[i + 1]}));
ShapeTree<int>& branch_root_height_tree =
GetHeightTreeOrDie(computation->root_instruction());
SetHeight(height_tree, branch_root_height_tree);
}
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleSend(HloInstruction* send) {
RETURN_IF_HEIGHT_EXISTS(send);
HloInstruction* send_buffer = send->mutable_operand(0);
const ShapeTree<int>& send_buffer_height_tree =
GetHeightTreeOrDie(send_buffer);
ShapeTree<int>& height_tree = GetOrCreateHeightTree(send);
SetHeight(height_tree, send_buffer_height_tree, {}, {0});
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleRecv(HloInstruction* recv) {
RETURN_IF_HEIGHT_EXISTS(recv);
TF_ASSIGN_OR_RETURN(HloInstruction * send,
send_recv_group_map_->GetMatchingSendOrRecv(recv));
TF_RETURN_IF_ERROR(send->Accept(this));
HloInstruction* send_buffer = send->mutable_operand(0);
const ShapeTree<int>& send_buffer_height_tree =
GetHeightTreeOrDie(send_buffer);
ShapeTree<int>& height_tree = GetOrCreateHeightTree(recv);
SetHeight(height_tree, send_buffer_height_tree, {}, {0});
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleSendDone(HloInstruction* send_done) {
RETURN_IF_HEIGHT_EXISTS(send_done);
GetOrCreateHeightTree(send_done);
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleRecvDone(HloInstruction* recv_done) {
RETURN_IF_HEIGHT_EXISTS(recv_done);
HloInstruction* recv = recv_done->mutable_operand(0);
const ShapeTree<int>& recv_height_tree = GetHeightTreeOrDie(recv);
ShapeTree<int>& height_tree = GetOrCreateHeightTree(recv_done);
SetHeight(height_tree, recv_height_tree, {0}, {0});
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleAllReduce(HloInstruction* all_reduce) {
RETURN_IF_HEIGHT_EXISTS(all_reduce);
if (all_reduce->shape().IsArray()) {
return DefaultAction(all_reduce);
}
return HandleTupleLike(all_reduce);
}
absl::Status EinsumHeightAnalysis::HandleAsyncStart(
HloInstruction* async_start) {
RETURN_IF_HEIGHT_EXISTS(async_start);
TF_RETURN_IF_ERROR(
HandleCalledComputation(*(async_start->async_wrapped_computation()),
async_start->mutable_operands()));
const ShapeTree<int>& root_height_tree = GetHeightTreeOrDie(
async_start->async_wrapped_computation()->root_instruction());
ShapeTree<int>& height_tree = GetOrCreateHeightTree(async_start);
SetHeight(height_tree, root_height_tree, {}, {1});
for (int operand_index = 0; operand_index < async_start->operands().size();
++operand_index) {
HloInstruction* operand = async_start->mutable_operands()[operand_index];
const ShapeTree<int>& operand_height_tree = GetHeightTreeOrDie(operand);
SetHeight(height_tree, operand_height_tree, {}, {0, operand_index});
}
return absl::OkStatus();
}
absl::Status EinsumHeightAnalysis::HandleAsyncDone(HloInstruction* async_done) {
RETURN_IF_HEIGHT_EXISTS(async_done);
ShapeTree<int>& height_tree = GetOrCreateHeightTree(async_done);
HloInstruction* async_start = async_done->mutable_operand(0);
const ShapeTree<int>& async_start_height_tree =
GetHeightTreeOrDie(async_start);
SetHeight(height_tree, async_start_height_tree, {1}, {});
return absl::OkStatus();
}
std::string HloValueSemanticLabelToString(HloValueSemanticLabel label) {
switch (label) {
case HloValueSemanticLabel::kStatic:
return "Static";
case HloValueSemanticLabel::kRandom:
return "Random";
case HloValueSemanticLabel::kWeight:
return "Weight";
case HloValueSemanticLabel::kActivation:
return "Activation";
case HloValueSemanticLabel::kActivationGradient:
return "ActivationGradient";
case HloValueSemanticLabel::kWeightGradient:
return "WeightGradient";
case HloValueSemanticLabel::kTupleOrToken:
return "TupleOrToken";
}
}
std::string HloValueSemantics::ToString() const {
std::string content = absl::StrJoin(
{absl::StrCat("label: ", HloValueSemanticLabelToString(label_)),
absl::StrCat("origin: ", origin_.ToString())},
", ");
return absl::StrCat("{", content, "}");
}
HloValueSemantics::HloValueSemantics(HloValueSemanticLabel label,
const HloPosition& origin)
: HloValueSemantics(0, label, origin) {}
HloValueSemantics::HloValueSemantics(Id id, HloValueSemanticLabel label,
const HloPosition& origin)
: id_(id), label_(label), origin_(origin) {}
std::string HloValueSemanticsTreeToString(
const ShapeTree<const HloValueSemantics*>& tree) {
return ToString(tree);
}
HloValueSemanticsAnalysis::HloValueSemanticsAnalysis(
const HloModule& module,
const absl::flat_hash_set<std::string_view>& execution_threads)
: module_(module), execution_threads_(execution_threads), next_id_(0) {}
const HloValueSemantics* HloValueSemanticsAnalysis::GetSemantics(
const HloInstruction* instruction, const ShapeIndex& index) const {
return GetInstructionSemantics(instruction).element(index);
}
int HloValueSemanticsAnalysis::GetDepth(const HloInstruction* instruction,
const ShapeIndex& index) const {
auto depth_iter = einsum_depth_map_.find(instruction);
CHECK(depth_iter != einsum_depth_map_.end());
return depth_iter->second.element(index);
}
int HloValueSemanticsAnalysis::GetHeight(const HloInstruction* instruction,
const ShapeIndex& index) const {
auto height_iter = einsum_height_map_.find(instruction);
CHECK(height_iter != einsum_height_map_.end());
return height_iter->second.element(index);
}
absl::StatusOr<std::unique_ptr<HloValueSemanticsAnalysis>>
HloValueSemanticsAnalysis::Run(
const HloModule& module,
const absl::flat_hash_set<std::string_view>& execution_threads) {
std::unique_ptr<HloValueSemanticsAnalysis> value_semantics_analysis =
absl::WrapUnique(
new HloValueSemanticsAnalysis(module, execution_threads));
value_semantics_analysis->InitializeSendRecvGroups();
TF_RETURN_IF_ERROR(value_semantics_analysis->InitializeEinsumDepth());
TF_RETURN_IF_ERROR(value_semantics_analysis->InitializeEinsumHeight());
value_semantics_analysis->AnnotateWeights();
TF_RETURN_IF_ERROR(
value_semantics_analysis->RunOnComputation(*module.entry_computation()));
return value_semantics_analysis;
}
absl::Status HloValueSemanticsAnalysis::InitializeEinsumDepth() {
TF_ASSIGN_OR_RETURN(
std::unique_ptr<EinsumDepthAnalysis> einsum_depth_analysis,
EinsumDepthAnalysis::Run(*module_.entry_computation(),
*send_recv_group_map_));
einsum_depth_map_ = einsum_depth_analysis->GetEinsumDepthMap();
return absl::OkStatus();
}
absl::Status HloValueSemanticsAnalysis::InitializeEinsumHeight() {
TF_ASSIGN_OR_RETURN(
std::unique_ptr<EinsumHeightAnalysis> einsum_height_analysis,
EinsumHeightAnalysis::Run(*module_.entry_computation(),
*send_recv_group_map_));
einsum_height_map_ = einsum_height_analysis->GetEinsumHeightMap();
return absl::OkStatus();
}
void HloValueSemanticsAnalysis::InitializeSendRecvGroups() {
send_recv_group_map_ = std::make_unique<SendRecvGroupMap>(module_);
}
bool HloValueSemanticsAnalysis::HasSemanticsFor(
const HloInstruction* instruction) const {
return value_semantics_.contains(instruction);
}
absl::StatusOr<HloInstruction*>
HloValueSemanticsAnalysis::GetMatchingSendOrRecv(
HloInstruction* send_or_recv) const {
return send_recv_group_map_->GetMatchingSendOrRecv(send_or_recv);
}
HloValueSemantics::Id HloValueSemanticsAnalysis::NextId() { return next_id_++; }
const HloValueSemantics* HloValueSemanticsAnalysis::NewHloValueSemantics(
HloValueSemanticLabel label, const HloPosition& origin) {
HloValueSemantics::Id id = NextId();
auto inserted = value_semantics_map_.insert(std::make_pair(
id, std::make_unique<HloValueSemantics>(id, label, origin)));
return inserted.first->second.get();
}
const ShapeTree<const HloValueSemantics*>&
HloValueSemanticsAnalysis::GetInstructionSemantics(
const HloInstruction* instruction) const {
auto semantics_iter = value_semantics_.find(instruction);
CHECK(semantics_iter != value_semantics_.end())
<< "instruction: " << instruction->ToString();
return semantics_iter->second;
}
void HloValueSemanticsAnalysis::DeepCopyHloValueSemantics(
ShapeTree<const HloValueSemantics*>& copy_to,
const ShapeTree<const HloValueSemantics*>& copy_from,
const ShapeIndex& source_index, const ShapeIndex& destination_index) {
copy_to.ForEachMutableElement(
[this, ©_from, &source_index, &destination_index](
const ShapeIndex& index, const HloValueSemantics** semantics) {
if (index.size() < destination_index.size()) {
return;
}
bool in_subtree_to_copy = true;
for (int i = 0; i < destination_index.size(); ++i) {
if (index[i] != destination_index[i]) {
in_subtree_to_copy = false;
break;
}
}
if (!in_subtree_to_copy) {
return;
}
ShapeIndex full_source_index = source_index;
for (int i = destination_index.size(); i < index.size(); ++i) {
full_source_index.push_back(index[i]);
}
const HloValueSemantics* source_semantics =
copy_from.element(full_source_index);
*semantics = NewHloValueSemantics(source_semantics->label(),
source_semantics->origin());
});
}
void HloValueSemanticsAnalysis::DeepCopyHloValueSemantics(
const HloInstruction* target,
const ShapeTree<const HloValueSemantics*>& copy_from,
const ShapeIndex& source_index) {
auto semantics_iter = value_semantics_.find(target);
if (semantics_iter != value_semantics_.end()) {
DeleteHloValueSemantics(semantics_iter->second);
DeepCopyHloValueSemantics(semantics_iter->second, copy_from, source_index,
{});
return;
}
ShapeTree<const HloValueSemantics*> semantics_shape_tree(target->shape(),
nullptr);
DeepCopyHloValueSemantics(semantics_shape_tree, copy_from, source_index, {});
value_semantics_[target] = std::move(semantics_shape_tree);
}
void HloValueSemanticsAnalysis::SetHloValueSemantics(
const HloInstruction* target,
const ShapeTree<const HloValueSemantics*>& semantics) {
auto semantics_iter = value_semantics_.find(target);
if (semantics_iter != value_semantics_.end()) {
DeleteHloValueSemantics(semantics_iter->second);
}
value_semantics_[target] = semantics;
}
void HloValueSemanticsAnalysis::DeleteHloValueSemantics(
const HloValueSemantics* to_delete) {
value_semantics_map_.erase(to_delete->id());
}
void HloValueSemanticsAnalysis::DeleteHloValueSemantics(
const ShapeTree<const HloValueSemantics*>& to_delete) {
to_delete.ForEachElement(
[this](const ShapeIndex& index, const HloValueSemantics* semantics) {
DeleteHloValueSemantics(semantics);
});
}
void HloValueSemanticsAnalysis::AnnotateWeights() {
const HloComputation* entry_computation = module_.entry_computation();
for (HloInstruction* parameter :
entry_computation->parameter_instructions()) {
ShapeTree<const HloValueSemantics*> semantics_shape_tree(parameter->shape(),
nullptr);
semantics_shape_tree.ForEachMutableElement(
[this, &semantics_shape_tree, parameter](
const ShapeIndex& index, const HloValueSemantics** semantics) {
if (!semantics_shape_tree.IsLeaf(index)) {
*semantics = NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {parameter, index});
}
*semantics = NewHloValueSemantics(HloValueSemanticLabel::kWeight,
{parameter, index});
});
value_semantics_[parameter] = std::move(semantics_shape_tree);
}
}
absl::Status HloValueSemanticsAnalysis::RunOnComputation(
const HloComputation& computation,
absl::Span<const HloInstruction* const> operands) {
CHECK_EQ(computation.num_parameters(), operands.size());
for (int i = 0; i < computation.num_parameters(); ++i) {
auto semantics_iter = value_semantics_.find(operands[i]);
CHECK(semantics_iter != value_semantics_.end());
DeepCopyHloValueSemantics(computation.parameter_instructions()[i],
semantics_iter->second);
}
return RunOnComputation(computation);
}
absl::Status HloValueSemanticsAnalysis::RunOnComputation(
const HloComputation& computation) {
if (HloInstruction::IsThreadIncluded(computation.execution_thread(),
execution_threads_)) {
HloValueSemanticsPropagation propagation(this);
return propagation.Run(computation);
}
return absl::OkStatus();
}
HloValueSemanticsPropagation::HloValueSemanticsPropagation(
HloValueSemanticsAnalysis* analysis)
: analysis_(analysis) {}
absl::Status HloValueSemanticsPropagation::Run(
const HloComputation& computation) {
TF_RETURN_IF_ERROR(computation.root_instruction()->Accept(this));
for (HloInstruction* instruction : computation.instructions()) {
if (instruction->user_count() == 0) {
TF_RETURN_IF_ERROR(instruction->Accept(this));
}
}
return absl::OkStatus();
}
HloValueSemantics HloValueSemanticsPropagation::CopySemantics(
const HloValueSemantics& semantics) const {
return HloValueSemantics(semantics.label(), semantics.origin());
}
HloValueSemantics HloValueSemanticsPropagation::CopySemanticsWithNewOrigin(
const HloValueSemantics& semantics, HloInstruction* new_origin,
const ShapeIndex& index) const {
return HloValueSemantics(semantics.label(), {new_origin, index});
}
const HloValueSemantics* HloValueSemanticsPropagation::AddSemantics(
const HloValueSemantics& semantics) {
return analysis_->NewHloValueSemantics(semantics.label(), semantics.origin());
}
std::vector<HloValueSemanticsPropagation::EinsumAndOperandIndex>
HloValueSemanticsPropagation::FindEinsumsWhereOriginDependsOnOther(
const HloValueSemantics& semantics, const HloPosition& origin_dependence,
bool recursive) const {
std::vector<HloPosition> stack;
absl::flat_hash_set<HloPosition> visited;
std::vector<HloValueSemanticsPropagation::EinsumAndOperandIndex>
dependent_einsums;
stack.push_back(semantics.origin());
while (!stack.empty()) {
HloPosition origin = stack.back();
stack.pop_back();
if (visited.contains(origin)) {
continue;
}
visited.insert(origin);
absl::Span<const HloInstruction* const> operands =
origin.instruction->operands();
if (origin.instruction->opcode() == HloOpcode::kDynamicUpdateSlice) {
operands = operands.subspan(0, 2);
}
if (origin.instruction->opcode() == HloOpcode::kDynamicSlice) {
operands = operands.subspan(0, 1);
}
bool is_einsum = origin.instruction->opcode() == HloOpcode::kDot ||
origin.instruction->opcode() == HloOpcode::kConvolution;
bool found_einsum = false;
if (is_einsum) {
for (int64_t operand_index = 0; operand_index < operands.size();
++operand_index) {
const HloInstruction* origin_operand = operands[operand_index];
const HloValueSemantics* origin_operand_semantics =
analysis_->GetSemantics(origin_operand);
if (origin_operand_semantics->origin() == origin_dependence) {
dependent_einsums.push_back({origin.instruction, operand_index});
found_einsum = true;
}
}
}
if (!found_einsum && recursive) {
for (int64_t operand_index = 0; operand_index < operands.size();
++operand_index) {
const HloInstruction* origin_operand = operands[operand_index];
const HloValueSemantics* origin_operand_semantics =
analysis_->GetSemantics(origin_operand);
stack.push_back(origin_operand_semantics->origin());
}
}
}
return dependent_einsums;
}
bool HloValueSemanticsPropagation::OriginDependsOn(
const HloValueSemantics& semantics, const HloPosition& origin_dependence,
bool recursive) const {
auto dependent_einsums = FindEinsumsWhereOriginDependsOnOther(
semantics, origin_dependence, recursive);
return !dependent_einsums.empty();
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::ComputeSemanticsFromStaticAndOther(
const HloValueSemantics& static_semantics,
const HloValueSemantics& other_semantics,
HloInstruction* instruction) const {
CHECK(static_semantics.label() == HloValueSemanticLabel::kStatic)
<< __func__ << ", : " << static_semantics.ToString();
if (other_semantics.label() == HloValueSemanticLabel::kStatic) {
return CopySemanticsWithNewOrigin(other_semantics, instruction);
}
bool is_dot_or_convolution = instruction->opcode() == HloOpcode::kDot ||
instruction->opcode() == HloOpcode::kConvolution;
if (is_dot_or_convolution &&
other_semantics.label() == HloValueSemanticLabel::kActivationGradient) {
return MaybeCreateGradientSemantics(
instruction, HloValueSemanticLabel::kActivationGradient);
}
return CopySemantics(other_semantics);
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::ComputeSemanticsFromRandomAndOther(
const HloValueSemantics& random_semantics,
const HloValueSemantics& other_semantics,
HloInstruction* instruction) const {
CHECK(random_semantics.label() == HloValueSemanticLabel::kRandom);
CHECK(other_semantics.label() != HloValueSemanticLabel::kStatic);
if (other_semantics.label() == HloValueSemanticLabel::kRandom) {
return CopySemanticsWithNewOrigin(other_semantics, instruction);
}
return CopySemantics(other_semantics);
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::MaybeCreateGradientSemantics(
HloInstruction* gradient_candidate,
HloValueSemanticLabel fallback_label) const {
int gradient_depth = analysis_->GetDepth(gradient_candidate, {});
if (gradient_depth < 0) {
return HloValueSemantics(HloValueSemanticLabel::kActivation,
{gradient_candidate, {}});
}
if (gradient_depth == 0) {
return HloValueSemantics(HloValueSemanticLabel::kWeightGradient,
{gradient_candidate, {}});
}
return HloValueSemantics(fallback_label, {gradient_candidate, {}});
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::ComputeSemanticsFromWeightAndOther(
const HloValueSemantics& weight_semantics,
const HloValueSemantics& other_semantics,
HloInstruction* instruction) const {
CHECK(weight_semantics.label() == HloValueSemanticLabel::kWeight);
CHECK(other_semantics.label() != HloValueSemanticLabel::kStatic &&
other_semantics.label() != HloValueSemanticLabel::kRandom);
bool is_dot_or_convolution = instruction->opcode() == HloOpcode::kDot ||
instruction->opcode() == HloOpcode::kConvolution;
if (other_semantics.label() == HloValueSemanticLabel::kWeight) {
if (!is_dot_or_convolution) {
if (weight_semantics.origin() == other_semantics.origin()) {
return CopySemantics(other_semantics);
}
return CopySemanticsWithNewOrigin(other_semantics, instruction);
}
return HloValueSemantics(HloValueSemanticLabel::kActivation,
{instruction, {}});
}
if (!is_dot_or_convolution) {
return CopySemantics(other_semantics);
}
if (other_semantics.label() == HloValueSemanticLabel::kActivation) {
int instruction_depth = analysis_->GetDepth(instruction, {});
auto dependent_einsums = FindEinsumsWhereOriginDependsOnOther(
other_semantics, weight_semantics.origin(), true);
bool all_dependent_einsums_immediately_proceeds_instruction =
absl::c_all_of(dependent_einsums,
[instruction_depth,
this](const EinsumAndOperandIndex& dependent_einsum) {
int dependent_einsum_depth =
analysis_->GetDepth(dependent_einsum.einsum, {});
return dependent_einsum_depth > 0 &&
dependent_einsum_depth == instruction_depth + 1;
});
if (!dependent_einsums.empty() &&
all_dependent_einsums_immediately_proceeds_instruction) {
return MaybeCreateGradientSemantics(
instruction, HloValueSemanticLabel::kActivationGradient);
}
return CopySemanticsWithNewOrigin(other_semantics, instruction);
}
if (other_semantics.label() == HloValueSemanticLabel::kActivationGradient) {
return MaybeCreateGradientSemantics(
instruction, HloValueSemanticLabel::kActivationGradient);
}
CHECK(other_semantics.label() == HloValueSemanticLabel::kWeightGradient);
return CopySemantics(other_semantics);
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::ComputeSemanticsFromActivationAndOther(
const HloValueSemantics& activation_semantics,
const HloValueSemantics& other_semantics,
HloInstruction* instruction) const {
CHECK(activation_semantics.label() == HloValueSemanticLabel::kActivation);
CHECK(other_semantics.label() != HloValueSemanticLabel::kStatic &&
other_semantics.label() != HloValueSemanticLabel::kRandom &&
other_semantics.label() != HloValueSemanticLabel::kWeight);
bool is_dot_or_convolution = instruction->opcode() == HloOpcode::kDot ||
instruction->opcode() == HloOpcode::kConvolution;
if (!is_dot_or_convolution) {
if (activation_semantics.origin() == other_semantics.origin()) {
return CopySemantics(other_semantics);
}
return CopySemanticsWithNewOrigin(other_semantics, instruction);
}
if (other_semantics.label() == HloValueSemanticLabel::kActivation) {
bool other_depends_on_activation = OriginDependsOn(
other_semantics, activation_semantics.origin(), true);
bool activation_depends_on_other =
OriginDependsOn(activation_semantics, other_semantics.origin(),
true);
CHECK(!other_depends_on_activation || !activation_depends_on_other);
if (other_depends_on_activation || activation_depends_on_other) {
return MaybeCreateGradientSemantics(instruction,
HloValueSemanticLabel::kActivation);
}
return CopySemanticsWithNewOrigin(other_semantics, instruction);
}
if (other_semantics.label() == HloValueSemanticLabel::kActivationGradient) {
return MaybeCreateGradientSemantics(
instruction, HloValueSemanticLabel::kActivationGradient);
}
CHECK(other_semantics.label() == HloValueSemanticLabel::kWeightGradient)
<< "instruction: " << instruction->ToString()
<< ", semantics: " << other_semantics.ToString()
<< ", expected: WeightGradient.";
return CopySemantics(other_semantics);
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::ComputeSemanticsFromActivationGradientAndOther(
const HloValueSemantics& activation_gradient_semantics,
const HloValueSemantics& other_semantics,
HloInstruction* instruction) const {
CHECK(activation_gradient_semantics.label() ==
HloValueSemanticLabel::kActivationGradient);
CHECK(other_semantics.label() != HloValueSemanticLabel::kStatic &&
other_semantics.label() != HloValueSemanticLabel::kRandom &&
other_semantics.label() != HloValueSemanticLabel::kWeight &&
other_semantics.label() != HloValueSemanticLabel::kActivation);
if (other_semantics.label() == HloValueSemanticLabel::kActivationGradient) {
if (other_semantics.origin() == activation_gradient_semantics.origin()) {
return CopySemantics(activation_gradient_semantics);
}
return CopySemanticsWithNewOrigin(other_semantics, instruction);
}
CHECK(other_semantics.label() == HloValueSemanticLabel::kWeightGradient);
return CopySemantics(other_semantics);
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::ComputeSemanticsFromWeightGradientAndOther(
const HloValueSemantics& weight_gradient_semantics,
const HloValueSemantics& other_semantics,
HloInstruction* instruction) const {
CHECK(weight_gradient_semantics.label() ==
HloValueSemanticLabel::kWeightGradient);
CHECK(other_semantics.label() != HloValueSemanticLabel::kStatic &&
other_semantics.label() != HloValueSemanticLabel::kRandom &&
other_semantics.label() != HloValueSemanticLabel::kWeight &&
other_semantics.label() != HloValueSemanticLabel::kActivation &&
other_semantics.label() != HloValueSemanticLabel::kActivationGradient);
return CopySemantics(weight_gradient_semantics);
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::MergeSemanticsForAnInstruction(
HloInstruction* instruction,
std::vector<HloValueSemantics>& semantics_vec) const {
while (semantics_vec.size() >= 2) {
absl::Span<const HloValueSemantics> operand_list =
absl::MakeConstSpan(semantics_vec).subspan(semantics_vec.size() - 2, 2);
auto find_operand_index_with_label =
[&operand_list](HloValueSemanticLabel label) -> std::optional<int64_t> {
auto iter = absl::c_find_if(operand_list,
[label](const HloValueSemantics& operand) {
return operand.label() == label;
});
return (iter != operand_list.end())
? std::optional<int64_t>(
std::distance(operand_list.begin(), iter))
: std::nullopt;
};
auto replace_operands_semantics_with =
[&semantics_vec](const HloValueSemantics& result_semantics) {
semantics_vec.pop_back();
semantics_vec.pop_back();
semantics_vec.push_back(result_semantics);
};
if (auto index =
find_operand_index_with_label(HloValueSemanticLabel::kStatic)) {
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromStaticAndOther(
operand_list[*index], operand_list[1 - *index], instruction));
replace_operands_semantics_with(semantics);
continue;
}
if (auto index =
find_operand_index_with_label(HloValueSemanticLabel::kRandom)) {
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromRandomAndOther(
operand_list[*index], operand_list[1 - *index], instruction));
replace_operands_semantics_with(semantics);
continue;
}
if (auto index =
find_operand_index_with_label(HloValueSemanticLabel::kWeight)) {
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromWeightAndOther(
operand_list[*index], operand_list[1 - *index], instruction));
replace_operands_semantics_with(semantics);
continue;
}
if (auto index =
find_operand_index_with_label(HloValueSemanticLabel::kActivation)) {
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromActivationAndOther(
operand_list[*index], operand_list[1 - *index], instruction));
replace_operands_semantics_with(semantics);
continue;
}
if (auto index = find_operand_index_with_label(
HloValueSemanticLabel::kActivationGradient)) {
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromActivationGradientAndOther(
operand_list[*index], operand_list[1 - *index], instruction));
replace_operands_semantics_with(semantics);
continue;
}
if (auto index = find_operand_index_with_label(
HloValueSemanticLabel::kWeightGradient)) {
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromWeightGradientAndOther(
operand_list[*index], operand_list[1 - *index], instruction));
replace_operands_semantics_with(semantics);
continue;
}
if (operand_list[0].label() == HloValueSemanticLabel::kTupleOrToken &&
operand_list[1].label() == HloValueSemanticLabel::kTupleOrToken) {
HloValueSemantics semantics =
CopySemanticsWithNewOrigin(operand_list[0], instruction);
replace_operands_semantics_with(semantics);
continue;
}
LOG(FATAL) << "We don't expect to handle operands of label "
<< HloValueSemanticLabelToString(operand_list[0].label())
<< " and "
<< HloValueSemanticLabelToString(operand_list[1].label())
<< " in ComputeSemanticsFromOperands. Instruction: "
<< instruction->name()
<< " should be handled in its own handler instead of the "
"default handler.";
}
VLOG(3) << __func__
<< ", result semantics: " << semantics_vec.back().ToString();
return semantics_vec.back();
}
absl::StatusOr<HloValueSemantics>
HloValueSemanticsPropagation::ComputeSemanticsFromOperands(
HloInstruction* instruction, absl::Span<const int64_t> operand_indices,
absl::Span<const ShapeIndex> operand_shape_indices) const {
CHECK(!operand_indices.empty());
CHECK(operand_shape_indices.empty() ||
operand_indices.size() == operand_shape_indices.size());
VLOG(3) << __func__ << ", instruction: " << instruction->ToString();
std::vector<HloValueSemantics> semantics_vec;
for (int64_t operand_index : operand_indices) {
const HloInstruction* operand = instruction->operand(operand_index);
const HloValueSemantics* operand_semantics = analysis_->GetSemantics(
operand, operand_shape_indices.empty()
? ShapeIndex()
: operand_shape_indices[operand_index]);
auto operand_height_iter = analysis_->GetEinsumHeightMap().find(operand);
CHECK(operand_height_iter != analysis_->GetEinsumHeightMap().end())
<< "operand: " << operand->name();
VLOG(3) << __func__ << ", operand_index: " << operand_index
<< ", operand: " << operand->name()
<< ", operand_semantics: " << operand_semantics->ToString()
<< ", height: " << ToString(operand_height_iter->second);
semantics_vec.push_back(*operand_semantics);
}
return MergeSemanticsForAnInstruction(instruction, semantics_vec);
}
#define RETURN_IF_ALREADY_PROPAGATED(instruction) \
if (analysis_->HasSemanticsFor(instruction)) { \
return absl::OkStatus(); \
}
absl::Status HloValueSemanticsPropagation::DefaultAction(
HloInstruction* instruction) {
RETURN_IF_ALREADY_PROPAGATED(instruction);
std::vector<int64_t> operand_indices(instruction->operand_count());
std::iota(operand_indices.begin(), operand_indices.end(), 0);
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromOperands(instruction, operand_indices));
if (instruction->shape().IsTuple()) {
ShapeTree<const HloValueSemantics*> semantics_shape_tree(
instruction->shape(), nullptr);
semantics_shape_tree.ForEachMutableElement(
[this, &semantics, &semantics_shape_tree, instruction](
const ShapeIndex& index, const HloValueSemantics** semantics_ptr) {
if (semantics_shape_tree.IsLeaf(index)) {
HloValueSemantics sub_semantics =
CopySemanticsWithNewOrigin(semantics, instruction, index);
*semantics_ptr = AddSemantics(sub_semantics);
} else {
HloValueSemantics sub_semantics(
HloValueSemanticLabel::kTupleOrToken, {instruction, index});
*semantics_ptr = AddSemantics(sub_semantics);
}
});
analysis_->SetHloValueSemantics(instruction, semantics_shape_tree);
} else {
const HloValueSemantics* semantics_ptr = AddSemantics(semantics);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(
instruction->shape(), semantics_ptr);
analysis_->SetHloValueSemantics(instruction, semantics_shape_tree);
}
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleParameter(
HloInstruction* parameter) {
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleConstant(
HloInstruction* constant) {
RETURN_IF_ALREADY_PROPAGATED(constant);
const HloValueSemantics* constant_semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kStatic, {constant, {}});
ShapeTree<const HloValueSemantics*> semantics_shape_tree(constant->shape(),
constant_semantics);
analysis_->SetHloValueSemantics(constant, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleIota(HloInstruction* iota) {
RETURN_IF_ALREADY_PROPAGATED(iota);
const HloValueSemantics* semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kStatic, {iota, {}});
ShapeTree<const HloValueSemantics*> semantics_shape_tree(iota->shape(),
semantics);
analysis_->SetHloValueSemantics(iota, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandlePartitionId(
HloInstruction* partition_id) {
RETURN_IF_ALREADY_PROPAGATED(partition_id);
const HloValueSemantics* semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kStatic, {partition_id, {}});
ShapeTree<const HloValueSemantics*> semantics_shape_tree(
partition_id->shape(), semantics);
analysis_->SetHloValueSemantics(partition_id, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleReplicaId(
HloInstruction* replica_id) {
RETURN_IF_ALREADY_PROPAGATED(replica_id);
const HloValueSemantics* semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kStatic, {replica_id, {}});
ShapeTree<const HloValueSemantics*> semantics_shape_tree(replica_id->shape(),
semantics);
analysis_->SetHloValueSemantics(replica_id, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleRngBitGenerator(
HloInstruction* rng_bit_generator) {
const HloValueSemantics* semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kRandom, {rng_bit_generator, {}});
ShapeTree<const HloValueSemantics*> rbg_semantics_tree(
rng_bit_generator->shape(), semantics);
analysis_->SetHloValueSemantics(rng_bit_generator, rbg_semantics_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleClamp(HloInstruction* clamp) {
RETURN_IF_ALREADY_PROPAGATED(clamp);
const ShapeTree<const HloValueSemantics*>& operand_semantics =
analysis_->GetInstructionSemantics(clamp->operand(1));
analysis_->DeepCopyHloValueSemantics(clamp, operand_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleTuple(HloInstruction* tuple) {
RETURN_IF_ALREADY_PROPAGATED(tuple);
return HandleTupleLike(tuple);
}
absl::Status HloValueSemanticsPropagation::HandleGetTupleElement(
HloInstruction* get_tuple_element) {
RETURN_IF_ALREADY_PROPAGATED(get_tuple_element);
const HloInstruction* tuple = get_tuple_element->operand(0);
int64_t tuple_index = get_tuple_element->tuple_index();
const ShapeTree<const HloValueSemantics*>& tuple_semantics =
analysis_->GetInstructionSemantics(tuple);
TF_ASSIGN_OR_RETURN(
ShapeTree<const HloValueSemantics*> tuple_element_semantics,
tuple_semantics.SubShapeTree({tuple_index}));
analysis_->DeepCopyHloValueSemantics(get_tuple_element,
tuple_element_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleCall(HloInstruction* call) {
RETURN_IF_ALREADY_PROPAGATED(call);
HloComputation* computation = call->called_computations()[0];
TF_RETURN_IF_ERROR(
analysis_->RunOnComputation(*computation, call->operands()));
const ShapeTree<const HloValueSemantics*>& root_semantics =
analysis_->GetInstructionSemantics(computation->root_instruction());
analysis_->DeepCopyHloValueSemantics(call, root_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleFusion(
HloInstruction* fusion) {
return HandleCall(fusion);
}
absl::Status HloValueSemanticsPropagation::HandleWhile(
HloInstruction* xla_while) {
RETURN_IF_ALREADY_PROPAGATED(xla_while);
TF_RETURN_IF_ERROR(analysis_->RunOnComputation(*xla_while->while_condition(),
xla_while->operands()));
HloComputation* computation = xla_while->while_body();
TF_RETURN_IF_ERROR(
analysis_->RunOnComputation(*computation, xla_while->operands()));
const ShapeTree<const HloValueSemantics*>& root_semantics =
analysis_->GetInstructionSemantics(computation->root_instruction());
analysis_->DeepCopyHloValueSemantics(xla_while, root_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleCustomCall(
HloInstruction* custom_call) {
RETURN_IF_ALREADY_PROPAGATED(custom_call);
if (custom_call->custom_call_target() == "Sharding" ||
custom_call->custom_call_target() == "SPMDFullToShardShape" ||
custom_call->custom_call_target() == "SPMDShardToFullShape") {
const ShapeTree<const HloValueSemantics*>& operand_semantics =
analysis_->GetInstructionSemantics(custom_call->operand(0));
analysis_->DeepCopyHloValueSemantics(custom_call, operand_semantics);
return absl::OkStatus();
}
return Unimplemented("Unimplemented custom-call: %s",
custom_call->custom_call_target());
}
absl::Status HloValueSemanticsPropagation::HandleConditional(
HloInstruction* conditional) {
RETURN_IF_ALREADY_PROPAGATED(conditional);
std::vector<ShapeTree<const HloValueSemantics*>> semantics_tree_vec;
for (int i = 0; i < conditional->called_computations().size(); ++i) {
HloComputation* computation = conditional->called_computations()[i];
TF_RETURN_IF_ERROR(analysis_->RunOnComputation(
*computation, {conditional->operands()[i + 1]}));
const ShapeTree<const HloValueSemantics*>& root_semantics =
analysis_->GetInstructionSemantics(computation->root_instruction());
semantics_tree_vec.push_back(root_semantics);
}
std::vector<HloValueSemantics> merged_semantics_leaves;
TF_RETURN_IF_ERROR(semantics_tree_vec[0].ForEachElementWithStatus(
[&](const ShapeIndex& index,
const HloValueSemantics* semantics) -> absl::Status {
std::vector<HloValueSemantics> semantics_vector;
semantics_vector.reserve(semantics_tree_vec.size());
for (size_t i = 0; i < semantics_tree_vec.size(); ++i) {
semantics_vector.push_back(
*(semantics_tree_vec[i].find(index)->second));
}
TF_ASSIGN_OR_RETURN(
HloValueSemantics merged,
MergeSemanticsForAnInstruction(conditional, semantics_vector));
merged_semantics_leaves.push_back(merged);
return absl::OkStatus();
}));
ShapeTree<const HloValueSemantics*> merged_semantics(conditional->shape());
int idx = 0;
merged_semantics.ForEachMutableElement(
[&](const ShapeIndex& index,
const HloValueSemantics** semantics) -> void {
*semantics = &merged_semantics_leaves[idx++];
});
analysis_->DeepCopyHloValueSemantics(conditional, merged_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleSelect(
HloInstruction* select) {
RETURN_IF_ALREADY_PROPAGATED(select);
TF_ASSIGN_OR_RETURN(HloValueSemantics semantics,
ComputeSemanticsFromOperands(select, {1, 2}));
const HloValueSemantics* semantics_ptr = AddSemantics(semantics);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(select->shape(),
semantics_ptr);
analysis_->SetHloValueSemantics(select, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleConcatenate(
HloInstruction* concatenate) {
RETURN_IF_ALREADY_PROPAGATED(concatenate);
const ShapeTree<const HloValueSemantics*>& operand_semantics =
analysis_->GetInstructionSemantics(concatenate->operand(0));
analysis_->DeepCopyHloValueSemantics(concatenate, operand_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleDynamicSlice(
HloInstruction* dynamic_slice) {
RETURN_IF_ALREADY_PROPAGATED(dynamic_slice);
const HloInstruction* dynamic_slice_operand = dynamic_slice->operand(0);
const HloValueSemantics* operand_semantics =
analysis_->GetSemantics(dynamic_slice_operand);
const HloValueSemantics* semantics = AddSemantics(*operand_semantics);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(
dynamic_slice->shape(), semantics);
analysis_->SetHloValueSemantics(dynamic_slice, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleDynamicUpdateSlice(
HloInstruction* dynamic_update_slice) {
RETURN_IF_ALREADY_PROPAGATED(dynamic_update_slice);
TF_ASSIGN_OR_RETURN(
HloValueSemantics semantics,
ComputeSemanticsFromOperands(dynamic_update_slice, {0, 1}));
const HloValueSemantics* semantics_ptr = AddSemantics(semantics);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(
dynamic_update_slice->shape(), semantics_ptr);
analysis_->SetHloValueSemantics(dynamic_update_slice, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleCopyStart(
HloInstruction* copy_start) {
return HandleCollectiveOrCopyStart(copy_start);
}
absl::Status HloValueSemanticsPropagation::HandleCopyDone(
HloInstruction* copy_done) {
return HandleCollectiveOrCopyDone(copy_done);
}
absl::Status HloValueSemanticsPropagation::HandleCollectiveOrCopyStart(
HloInstruction* op_start) {
RETURN_IF_ALREADY_PROPAGATED(op_start);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(op_start->shape());
const ShapeTree<const HloValueSemantics*>& operand_semantics_shape_tree =
analysis_->GetInstructionSemantics(op_start->operand(0));
analysis_->DeepCopyHloValueSemantics(semantics_shape_tree,
operand_semantics_shape_tree, {}, {0});
analysis_->DeepCopyHloValueSemantics(semantics_shape_tree,
operand_semantics_shape_tree, {}, {1});
semantics_shape_tree.ForEachMutableElement(
[this, op_start](const ShapeIndex& shape_index,
const HloValueSemantics** semantics) {
if (shape_index.empty()) {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {op_start, {}});
}
if (shape_index == ShapeIndex{2}) {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kRandom, {op_start, shape_index});
}
if (shape_index == ShapeIndex{3}) {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kRandom, {op_start, shape_index});
}
});
analysis_->SetHloValueSemantics(op_start, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleCollectiveOrCopyDone(
HloInstruction* op_done) {
RETURN_IF_ALREADY_PROPAGATED(op_done);
const ShapeTree<const HloValueSemantics*>& operand_semantics_shape_tree =
analysis_->GetInstructionSemantics(op_done->operand(0));
analysis_->DeepCopyHloValueSemantics(op_done, operand_semantics_shape_tree,
{1});
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleAllGatherStart(
HloInstruction* all_gather_start) {
return HandleCollectiveOrCopyStart(all_gather_start);
}
absl::Status HloValueSemanticsPropagation::HandleAllGatherDone(
HloInstruction* all_gather_done) {
return HandleCollectiveOrCopyDone(all_gather_done);
}
absl::Status HloValueSemanticsPropagation::HandleCollectivePermuteStart(
HloInstruction* collective_permute_start) {
return HandleCollectiveOrCopyStart(collective_permute_start);
}
absl::Status HloValueSemanticsPropagation::HandleCollectivePermuteDone(
HloInstruction* collective_permute_done) {
return HandleCollectiveOrCopyDone(collective_permute_done);
}
absl::Status HloValueSemanticsPropagation::HandleGather(
HloInstruction* gather) {
RETURN_IF_ALREADY_PROPAGATED(gather);
const ShapeTree<const HloValueSemantics*>& operand_semantics_shape_tree =
analysis_->GetInstructionSemantics(gather->operand(0));
analysis_->DeepCopyHloValueSemantics(gather, operand_semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleScatter(
HloInstruction* scatter) {
RETURN_IF_ALREADY_PROPAGATED(scatter);
TF_ASSIGN_OR_RETURN(HloValueSemantics semantics,
ComputeSemanticsFromOperands(scatter, {0, 2}));
const HloValueSemantics* semantics_ptr = AddSemantics(semantics);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(scatter->shape(),
semantics_ptr);
analysis_->SetHloValueSemantics(scatter, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleAfterAll(
HloInstruction* after_all) {
RETURN_IF_ALREADY_PROPAGATED(after_all);
const HloValueSemantics* semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {after_all, {}});
ShapeTree<const HloValueSemantics*> semantics_shape_tree(after_all->shape(),
semantics);
analysis_->SetHloValueSemantics(after_all, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleAllReduce(
HloInstruction* all_reduce) {
RETURN_IF_ALREADY_PROPAGATED(all_reduce);
if (all_reduce->shape().IsArray()) {
return DefaultAction(all_reduce);
}
CHECK(all_reduce->shape().IsTuple());
return HandleTupleLike(all_reduce);
}
absl::Status HloValueSemanticsPropagation::HandleAsyncStart(
HloInstruction* async_start) {
RETURN_IF_ALREADY_PROPAGATED(async_start);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(async_start->shape(),
nullptr);
HloComputation* computation = async_start->async_wrapped_computation();
const bool is_thread_included = HloInstruction::IsThreadIncluded(
computation->execution_thread(), analysis_->execution_threads_);
if (is_thread_included) {
TF_RETURN_IF_ERROR(
analysis_->RunOnComputation(*computation, async_start->operands()));
const ShapeTree<const HloValueSemantics*>& root_semantics =
analysis_->GetInstructionSemantics(computation->root_instruction());
analysis_->DeepCopyHloValueSemantics(semantics_shape_tree, root_semantics,
{}, {1});
}
for (int operand_index = 0; operand_index < async_start->operand_count();
++operand_index) {
HloInstruction* operand = async_start->mutable_operand(operand_index);
const ShapeTree<const HloValueSemantics*>& operand_semantics_tree =
analysis_->GetInstructionSemantics(operand);
analysis_->DeepCopyHloValueSemantics(
semantics_shape_tree, operand_semantics_tree, {}, {0, operand_index});
}
semantics_shape_tree.ForEachMutableElement(
[&semantics_shape_tree, this, async_start, is_thread_included](
const ShapeIndex& index, const HloValueSemantics** semantics_ptr) {
if (!semantics_shape_tree.IsLeaf(index)) {
*semantics_ptr = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {async_start, {}});
return;
}
if ((!is_thread_included && index.front() == 1) || index.front() == 2 ||
index.front() == 3) {
*semantics_ptr = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kRandom, {async_start, {}});
}
});
analysis_->SetHloValueSemantics(async_start, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleAsyncDone(
HloInstruction* async_done) {
RETURN_IF_ALREADY_PROPAGATED(async_done);
const ShapeTree<const HloValueSemantics*>& operand_semantics_tree =
analysis_->GetInstructionSemantics(async_done->operand(0));
analysis_->DeepCopyHloValueSemantics(async_done, operand_semantics_tree, {1});
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleInfeed(
HloInstruction* infeed) {
RETURN_IF_ALREADY_PROPAGATED(infeed);
ShapeTree<const HloValueSemantics*> semantics_shape_tree(infeed->shape(),
nullptr);
semantics_shape_tree.ForEachMutableElement(
[this, &semantics_shape_tree, infeed](
const ShapeIndex& shape_index, const HloValueSemantics** semantics) {
if (semantics_shape_tree.IsLeaf(shape_index)) {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kWeight, {infeed, shape_index});
} else {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {infeed, shape_index});
}
});
analysis_->SetHloValueSemantics(infeed, semantics_shape_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleOutfeed(
HloInstruction* outfeed) {
RETURN_IF_ALREADY_PROPAGATED(outfeed);
const HloValueSemantics* semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {outfeed, {}});
ShapeTree<const HloValueSemantics*> outfeed_semantics_tree(outfeed->shape(),
semantics);
analysis_->SetHloValueSemantics(outfeed, outfeed_semantics_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleDomain(
HloInstruction* domain) {
RETURN_IF_ALREADY_PROPAGATED(domain);
HloInstruction* domain_operand = domain->mutable_operand(0);
const ShapeTree<const HloValueSemantics*>& operand_semantics =
analysis_->GetInstructionSemantics(domain_operand);
analysis_->DeepCopyHloValueSemantics(domain, operand_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleOptimizationBarrier(
HloInstruction* opt_barrier) {
RETURN_IF_ALREADY_PROPAGATED(opt_barrier);
HloInstruction* opt_barrier_operand = opt_barrier->mutable_operand(0);
const ShapeTree<const HloValueSemantics*>& operand_semantics =
analysis_->GetInstructionSemantics(opt_barrier_operand);
analysis_->DeepCopyHloValueSemantics(opt_barrier, operand_semantics);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleSend(HloInstruction* send) {
RETURN_IF_ALREADY_PROPAGATED(send);
ShapeTree<const HloValueSemantics*> semantics_tree(send->shape(), nullptr);
HloInstruction* source_buffer = send->mutable_operand(0);
const ShapeTree<const HloValueSemantics*>& source_buffer_semantics =
analysis_->GetInstructionSemantics(source_buffer);
analysis_->DeepCopyHloValueSemantics(semantics_tree, source_buffer_semantics,
{}, {0});
semantics_tree.ForEachMutableElement(
[this, send, &semantics_tree](const ShapeIndex& index,
const HloValueSemantics** semantics) {
if (!index.empty()) {
if (index.front() == 1 && semantics_tree.IsLeaf(index)) {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kRandom, {send, index});
return;
}
if (index.front() == 0) {
return;
}
}
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {send, index});
});
analysis_->SetHloValueSemantics(send, semantics_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleRecv(HloInstruction* recv) {
RETURN_IF_ALREADY_PROPAGATED(recv);
TF_ASSIGN_OR_RETURN(HloInstruction * send,
analysis_->GetMatchingSendOrRecv(recv));
TF_RETURN_IF_ERROR(send->Accept(this));
ShapeTree<const HloValueSemantics*> semantics_tree(recv->shape(), nullptr);
const ShapeTree<const HloValueSemantics*>& send_buffer_semantics =
analysis_->GetInstructionSemantics(send);
analysis_->DeepCopyHloValueSemantics(semantics_tree, send_buffer_semantics,
{0}, {0});
semantics_tree.ForEachMutableElement(
[this, recv, &semantics_tree](const ShapeIndex& index,
const HloValueSemantics** semantics) {
if (!index.empty()) {
if (index.front() == 1 && semantics_tree.IsLeaf(index)) {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kRandom, {recv, index});
return;
}
if (index.front() == 0) {
return;
}
}
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {recv, index});
});
analysis_->SetHloValueSemantics(recv, semantics_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleSendDone(
HloInstruction* send_done) {
RETURN_IF_ALREADY_PROPAGATED(send_done);
const HloValueSemantics* semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {send_done, {}});
ShapeTree<const HloValueSemantics*> send_done_semantics_tree(
send_done->shape(), semantics);
analysis_->SetHloValueSemantics(send_done, send_done_semantics_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleRecvDone(
HloInstruction* recv_done) {
RETURN_IF_ALREADY_PROPAGATED(recv_done);
ShapeTree<const HloValueSemantics*> semantics_tree(recv_done->shape(),
nullptr);
HloInstruction* recv = recv_done->mutable_operand(0);
const ShapeTree<const HloValueSemantics*>& recv_semantics =
analysis_->GetInstructionSemantics(recv);
analysis_->DeepCopyHloValueSemantics(semantics_tree, recv_semantics, {0},
{0});
semantics_tree.ForEachMutableElement(
[this, recv_done](const ShapeIndex& index,
const HloValueSemantics** semantics) {
if (!index.empty() && index.front() == 0) {
return;
}
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {recv_done, index});
});
analysis_->SetHloValueSemantics(recv_done, semantics_tree);
return absl::OkStatus();
}
absl::Status HloValueSemanticsPropagation::HandleTupleLike(
HloInstruction* tuple_like) {
ShapeTree<const HloValueSemantics*> semantics_shape_tree(tuple_like->shape(),
nullptr);
for (int operand_index = 0; operand_index < tuple_like->operand_count();
++operand_index) {
const HloInstruction* operand = tuple_like->operand(operand_index);
const ShapeTree<const HloValueSemantics*>& operand_semantics =
analysis_->GetInstructionSemantics(operand);
analysis_->DeepCopyHloValueSemantics(
semantics_shape_tree, operand_semantics, {}, {operand_index});
}
semantics_shape_tree.ForEachMutableElement(
[tuple_like, this](const ShapeIndex& index,
const HloValueSemantics** semantics) {
if (index.empty()) {
*semantics = analysis_->NewHloValueSemantics(
HloValueSemanticLabel::kTupleOrToken, {tuple_like, {}});
return;
}
});
analysis_->SetHloValueSemantics(tuple_like, semantics_shape_tree);
return absl::OkStatus();
}
} | #include "xla/service/hlo_value_semantics_analysis.h"
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "absl/log/log.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
const char kMnistHlo[] = R"(
HloModule MnistTrainingLoopWithInfeed.140, entry_computation_layout={(f32[784,128]{1,0:T(8,128)},f32[128]{0:T(256)},f32[128,32]{1,0:T(8,128)},f32[32]{0:T(256)},f32[32,10]{1,0:T(8,128)},f32[10]{0:T(256)})->(f32[784,128]{1,0:T(8,128)}, f32[128]{0:T(256)}, f32[128,32]{1,0:T(8,128)}, f32[32]{0:T(256)}, f32[32,10]{1,0:T(8,128)}, f32[10]{0:T(256)})}
relu.9 {
x.10 = f32[] parameter(0)
constant.11 = f32[] constant(0)
ROOT maximum.12 = f32[] maximum(x.10, constant.11)
}
max_F32.17 {
lhs.18 = f32[] parameter(0)
rhs.19 = f32[] parameter(1)
ROOT maximum.20 = f32[] maximum(lhs.18, rhs.19)
}
add_F32.1 {
lhs.22 = f32[] parameter(0)
rhs.23 = f32[] parameter(1)
ROOT add.24 = f32[] add(lhs.22, rhs.23)
}
relu_gradients.29 {
activation.30 = f32[] parameter(0)
constant.32 = f32[] constant(0)
compare.33 = pred[] compare(activation.30, constant.32), direction=GT
backprop.31 = f32[] parameter(1)
ROOT select.34 = f32[] select(compare.33, backprop.31, constant.32)
}
body.49 {
after-all.51 = token[] after-all()
infeed.52 = ((f32[100,784]{1,0}, f32[100,10]{1,0}, pred[]), token[]) infeed(after-all.51)
get.53 = (f32[100,784]{1,0}, f32[100,10]{1,0}, pred[]) get-tuple-element(infeed.52), index=0
get.54 = f32[100,784]{1,0} get-tuple-element(get.53), index=0
prev.50 = (f32[784,128]{1,0}, f32[128]{0}, f32[128,32]{1,0}, f32[32]{0}, f32[32,10]{1,0}, f32[10]{0}, pred[]) parameter(0)
get.57 = f32[784,128]{1,0} get-tuple-element(prev.50), index=0
dot.63 = f32[100,128]{1,0} dot(get.54, get.57), lhs_contracting_dims={1}, rhs_contracting_dims={0}
get.58 = f32[128]{0} get-tuple-element(prev.50), index=1
broadcast.64 = f32[100,128]{1,0} broadcast(get.58), dimensions={1}
add.65 = f32[100,128]{1,0} add(dot.63, broadcast.64)
map.66 = f32[100,128]{1,0} map(add.65), dimensions={0,1}, to_apply=relu.9
get.59 = f32[128,32]{1,0} get-tuple-element(prev.50), index=2
dot.67 = f32[100,32]{1,0} dot(map.66, get.59), lhs_contracting_dims={1}, rhs_contracting_dims={0}
get.60 = f32[32]{0} get-tuple-element(prev.50), index=3
broadcast.68 = f32[100,32]{1,0} broadcast(get.60), dimensions={1}
add.69 = f32[100,32]{1,0} add(dot.67, broadcast.68)
map.70 = f32[100,32]{1,0} map(add.69), dimensions={0,1}, to_apply=relu.9
get.61 = f32[32,10]{1,0} get-tuple-element(prev.50), index=4
dot.71 = f32[100,10]{1,0} dot(map.70, get.61), lhs_contracting_dims={1}, rhs_contracting_dims={0}
get.62 = f32[10]{0} get-tuple-element(prev.50), index=5
broadcast.72 = f32[100,10]{1,0} broadcast(get.62), dimensions={1}
add.73 = f32[100,10]{1,0} add(dot.71, broadcast.72)
constant.74 = f32[] constant(-inf)
reduce.75 = f32[100]{0} reduce(add.73, constant.74), dimensions={1}, to_apply=max_F32.17
broadcast.76 = f32[100,10]{1,0} broadcast(reduce.75), dimensions={0}
subtract.77 = f32[100,10]{1,0} subtract(add.73, broadcast.76)
exponential.78 = f32[100,10]{1,0} exponential(subtract.77)
constant.79 = f32[] constant(0)
reduce.80 = f32[100]{0} reduce(exponential.78, constant.79), dimensions={1}, to_apply=add_F32.1
broadcast.81 = f32[100,10]{1,0} broadcast(reduce.80), dimensions={0}
divide.82 = f32[100,10]{1,0} divide(exponential.78, broadcast.81)
get.55 = f32[100,10]{1,0} get-tuple-element(get.53), index=1
subtract.83 = f32[100,10]{1,0} subtract(divide.82, get.55)
transpose.88 = f32[10,32]{0,1} transpose(get.61), dimensions={1,0}
dot.89 = f32[100,32]{1,0} dot(subtract.83, transpose.88), lhs_contracting_dims={1}, rhs_contracting_dims={0}
map.90 = f32[100,32]{1,0} map(map.70, dot.89), dimensions={0,1}, to_apply=relu_gradients.29
transpose.95 = f32[32,128]{0,1} transpose(get.59), dimensions={1,0}
dot.96 = f32[100,128]{1,0} dot(map.90, transpose.95), lhs_contracting_dims={1}, rhs_contracting_dims={0}
map.97 = f32[100,128]{1,0} map(map.66, dot.96), dimensions={0,1}, to_apply=relu_gradients.29
transpose.98 = f32[784,100]{0,1} transpose(get.54), dimensions={1,0}
dot.99 = f32[784,128]{1,0} dot(transpose.98, map.97), lhs_contracting_dims={1}, rhs_contracting_dims={0}
constant.104 = f32[] constant(0.01)
broadcast.105 = f32[784,128]{1,0} broadcast(constant.104), dimensions={}
multiply.106 = f32[784,128]{1,0} multiply(dot.99, broadcast.105)
subtract.107 = f32[784,128]{1,0} subtract(get.57, multiply.106)
reduce.101 = f32[128]{0} reduce(map.97, constant.79), dimensions={0}, to_apply=add_F32.1
broadcast.109 = f32[128]{0} broadcast(constant.104), dimensions={}
multiply.110 = f32[128]{0} multiply(reduce.101, broadcast.109)
subtract.111 = f32[128]{0} subtract(get.58, multiply.110)
transpose.91 = f32[128,100]{0,1} transpose(map.66), dimensions={1,0}
dot.92 = f32[128,32]{1,0} dot(transpose.91, map.90), lhs_contracting_dims={1}, rhs_contracting_dims={0}
broadcast.113 = f32[128,32]{1,0} broadcast(constant.104), dimensions={}
multiply.114 = f32[128,32]{1,0} multiply(dot.92, broadcast.113)
subtract.115 = f32[128,32]{1,0} subtract(get.59, multiply.114)
reduce.94 = f32[32]{0} reduce(map.90, constant.79), dimensions={0}, to_apply=add_F32.1
broadcast.117 = f32[32]{0} broadcast(constant.104), dimensions={}
multiply.118 = f32[32]{0} multiply(reduce.94, broadcast.117)
subtract.119 = f32[32]{0} subtract(get.60, multiply.118)
transpose.84 = f32[32,100]{0,1} transpose(map.70), dimensions={1,0}
dot.85 = f32[32,10]{1,0} dot(transpose.84, subtract.83), lhs_contracting_dims={1}, rhs_contracting_dims={0}
broadcast.121 = f32[32,10]{1,0} broadcast(constant.104), dimensions={}
multiply.122 = f32[32,10]{1,0} multiply(dot.85, broadcast.121)
subtract.123 = f32[32,10]{1,0} subtract(get.61, multiply.122)
reduce.87 = f32[10]{0} reduce(subtract.83, constant.79), dimensions={0}, to_apply=add_F32.1
broadcast.125 = f32[10]{0} broadcast(constant.104), dimensions={}
multiply.126 = f32[10]{0} multiply(reduce.87, broadcast.125)
subtract.127 = f32[10]{0} subtract(get.62, multiply.126)
get.56 = pred[] get-tuple-element(get.53), index=2
ROOT tuple.128 = (f32[784,128]{1,0}, f32[128]{0}, f32[128,32]{1,0}, f32[32]{0}, f32[32,10]{1,0}, f32[10]{0}, pred[]) tuple(subtract.107, subtract.111, subtract.115, subtract.119, subtract.123, subtract.127, get.56)
}
condition.129 {
prev.130 = (f32[784,128]{1,0}, f32[128]{0}, f32[128,32]{1,0}, f32[32]{0}, f32[32,10]{1,0}, f32[10]{0}, pred[]) parameter(0)
ROOT get.131 = pred[] get-tuple-element(prev.130), index=6
}
ENTRY MnistTrainingLoopWithInfeed.140 {
layer1_weights.1 = f32[784,128]{1,0} parameter(0)
layer1_biases.2 = f32[128]{0} parameter(1)
layer2_weights.3 = f32[128,32]{1,0} parameter(2)
layer2_biases.4 = f32[32]{0} parameter(3)
layer3_weights.5 = f32[32,10]{1,0} parameter(4)
layer3_biases.6 = f32[10]{0} parameter(5)
constant.7 = pred[] constant(true)
tuple.8 = (f32[784,128]{1,0}, f32[128]{0}, f32[128,32]{1,0}, f32[32]{0}, f32[32,10]{1,0}, f32[10]{0}, pred[]) tuple(layer1_weights.1, layer1_biases.2, layer2_weights.3, layer2_biases.4, layer3_weights.5, layer3_biases.6, constant.7)
while.132 = (f32[784,128]{1,0}, f32[128]{0}, f32[128,32]{1,0}, f32[32]{0}, f32[32,10]{1,0}, f32[10]{0}, pred[]) while(tuple.8), condition=condition.129, body=body.49
get.133 = f32[784,128]{1,0} get-tuple-element(while.132), index=0
get.134 = f32[128]{0} get-tuple-element(while.132), index=1
get.135 = f32[128,32]{1,0} get-tuple-element(while.132), index=2
get.136 = f32[32]{0} get-tuple-element(while.132), index=3
get.137 = f32[32,10]{1,0} get-tuple-element(while.132), index=4
get.138 = f32[10]{0} get-tuple-element(while.132), index=5
ROOT tuple.139 = (f32[784,128]{1,0}, f32[128]{0}, f32[128,32]{1,0}, f32[32]{0}, f32[32,10]{1,0}, f32[10]{0}) tuple(get.133, get.134, get.135, get.136, get.137, get.138)
}
)";
class HloValueSemanticsAnalysisTest : public HloTestBase {
public:
bool HasLabel(const HloValueSemanticsAnalysis& hlo_value_semantics_analysis,
HloModule* module, absl::string_view instruction_name,
const HloValueSemanticLabel& expected_label) {
HloInstruction* instruction = FindInstruction(module, instruction_name);
const HloValueSemantics* semantics =
hlo_value_semantics_analysis.GetSemantics(instruction);
LOG(INFO) << "instruction: " << instruction->ToString()
<< semantics->ToString();
return semantics->label() == expected_label;
}
bool IsStatic(const HloValueSemanticsAnalysis& hlo_value_semantics_analysis,
HloModule* module, absl::string_view instruction_name) {
return HasLabel(hlo_value_semantics_analysis, module, instruction_name,
HloValueSemanticLabel::kStatic);
}
bool IsWeight(const HloValueSemanticsAnalysis& hlo_value_semantics_analysis,
HloModule* module, absl::string_view instruction_name) {
return HasLabel(hlo_value_semantics_analysis, module, instruction_name,
HloValueSemanticLabel::kWeight);
}
bool IsActivation(
const HloValueSemanticsAnalysis& hlo_value_semantics_analysis,
HloModule* module, absl::string_view instruction_name) {
return HasLabel(hlo_value_semantics_analysis, module, instruction_name,
HloValueSemanticLabel::kActivation);
}
bool IsActivationGradient(
const HloValueSemanticsAnalysis& hlo_value_semantics_analysis,
HloModule* module, absl::string_view instruction_name) {
return HasLabel(hlo_value_semantics_analysis, module, instruction_name,
HloValueSemanticLabel::kActivationGradient);
}
bool IsWeightGradient(
const HloValueSemanticsAnalysis& hlo_value_semantics_analysis,
HloModule* module, absl::string_view instruction_name) {
return HasLabel(hlo_value_semantics_analysis, module, instruction_name,
HloValueSemanticLabel::kWeightGradient);
}
bool IsTupleOrToken(
const HloValueSemanticsAnalysis& hlo_value_semantics_analysis,
HloModule* module, absl::string_view instruction_name) {
return HasLabel(hlo_value_semantics_analysis, module, instruction_name,
HloValueSemanticLabel::kTupleOrToken);
}
};
TEST_F(HloValueSemanticsAnalysisTest, OneMatmul) {
const std::string module_str = R"(
HloModule OneMatmul
region_0.39 {
Arg_0.40 = f32[] parameter(0)
Arg_1.41 = f32[] parameter(1)
ROOT add.42 = f32[] add(Arg_0.40, Arg_1.41)
}
ENTRY entry {
Arg_1.2 = f32[32,128]{1,0} parameter(0), sharding={devices=[2,1]0,1}
Arg_7.8 = f32[4,32]{1,0} parameter(1), sharding={devices=[2,1]0,1}
copy = f32[4,32]{1,0} copy(Arg_7.8), sharding={devices=[2,1]0,1}
dot.0 = f32[4,128]{1,0} dot(copy, Arg_1.2), lhs_contracting_dims={1}, rhs_contracting_dims={0}, sharding={devices=[2,1]0,1}
constant.5 = f32[] constant(0), sharding={replicated}
broadcast.2 = f32[4,128]{1,0} broadcast(constant.5), dimensions={}, sharding={devices=[2,1]0,1}
maximum.33 = f32[4,128]{1,0} maximum(dot.0, broadcast.2), sharding={devices=[2,1]0,1}
compare.34 = pred[4,128]{1,0} compare(dot.0, maximum.33), direction=EQ, sharding={devices=[2,1]0,1}
constant.4 = f32[] constant(1), sharding={replicated}
broadcast.1 = f32[4,128]{1,0} broadcast(constant.4), dimensions={}, sharding={devices=[2,1]0,1}
select.35 = f32[4,128]{1,0} select(compare.34, broadcast.1, broadcast.2), sharding={devices=[2,1]0,1}
dot.2 = f32[32,128]{0,1} dot(copy, select.35), lhs_contracting_dims={0}, rhs_contracting_dims={0}, sharding={devices=[2,1]0,1}
constant.11 = f32[] constant(-0.01), sharding={replicated}
broadcast.12 = f32[32,128]{1,0} broadcast(constant.11), dimensions={}, sharding={devices=[2,1]0,1}
multiply.52 = f32[32,128]{0,1} multiply(dot.2, broadcast.12), sharding={devices=[2,1]0,1}
add.93 = f32[32,128]{1,0} add(Arg_1.2, multiply.52), sharding={devices=[2,1]0,1}
reduce.43 = f32[] reduce(maximum.33, constant.5), dimensions={0,1}, to_apply=region_0.39, sharding={replicated}
ROOT tuple.109 = (f32[32,128]{1,0}, f32[]) tuple(add.93, reduce.43), sharding={{devices=[2,1]0,1}, {replicated}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(
auto module, ParseAndReturnVerifiedModule(module_str, 1,
2));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<HloValueSemanticsAnalysis> hlo_value_semantics_analysis,
HloValueSemanticsAnalysis::Run(*module));
EXPECT_TRUE(IsWeight(*hlo_value_semantics_analysis, module.get(), "copy"));
EXPECT_TRUE(IsWeight(*hlo_value_semantics_analysis, module.get(), "Arg_1.2"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.0"));
EXPECT_TRUE(
IsStatic(*hlo_value_semantics_analysis, module.get(), "select.35"));
EXPECT_TRUE(IsWeight(*hlo_value_semantics_analysis, module.get(), "dot.2"));
}
TEST_F(HloValueSemanticsAnalysisTest, HandleConditional) {
const std::string module_str = R"(
HloModule Module
branch0 {
tparam = f32[4] parameter(0)
tgte1 = f32[4] ceil(tparam)
ROOT tuple = (f32[4], f32[4]) tuple(tparam, tgte1)
}
branch1 {
fparam = f32[4] parameter(0)
%async-start = ((f32[4]), f32[4], s32[]) abs-start(f32[4] fparam), async_execution_thread="parallel_thread"
%async-done = f32[4] abs-done(((f32[4]), f32[4], s32[]) %async-start)
ROOT tuple = (f32[4], f32[4]) tuple(fparam, %async-done)
}
ENTRY entry {
p0 = f32[4] parameter(0)
b0 = s32[] parameter(1)
ROOT conditional = (f32[4], f32[4]) conditional(b0, p0, p0),
branch_computations={branch0, branch1}
}
)";
TF_ASSERT_OK_AND_ASSIGN(
auto module, ParseAndReturnVerifiedModule(module_str, 1,
2));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<HloValueSemanticsAnalysis> hlo_value_semantics_analysis,
HloValueSemanticsAnalysis::Run(*module));
EXPECT_TRUE(IsTupleOrToken(*hlo_value_semantics_analysis, module.get(),
"conditional"));
}
TEST_F(HloValueSemanticsAnalysisTest, TwoMatmuls) {
const std::string module_str = R"(
HloModule TwoMatmuls
region_0.44 {
Arg_0.45 = f32[] parameter(0)
Arg_1.46 = f32[] parameter(1)
ROOT add.47 = f32[] add(Arg_0.45, Arg_1.46)
}
ENTRY entry {
Arg_1.2 = f32[32,128]{1,0} parameter(0), sharding={devices=[2,1]0,1}
Arg_8.9 = f32[4,32]{1,0} parameter(2), sharding={devices=[2,1]0,1}
copy = f32[4,32]{1,0} copy(Arg_8.9), sharding={devices=[2,1]0,1}
dot.0 = f32[4,128]{1,0} dot(copy, Arg_1.2), lhs_contracting_dims={1}, rhs_contracting_dims={0}, sharding={devices=[2,1]0,1}
Arg_2.3 = f32[128,8]{1,0} parameter(1), sharding={devices=[1,2]0,1}
dot.1 = f32[4,8]{1,0} dot(dot.0, Arg_2.3), lhs_contracting_dims={1}, rhs_contracting_dims={0}, sharding={devices=[1,2]0,1}
constant.5 = f32[] constant(0), sharding={replicated}
broadcast.1 = f32[4,8]{1,0} broadcast(constant.5), dimensions={}, sharding={devices=[1,2]0,1}
maximum.38 = f32[4,8]{1,0} maximum(dot.1, broadcast.1), sharding={devices=[1,2]0,1}
compare.39 = pred[4,8]{1,0} compare(dot.1, maximum.38), direction=EQ, sharding={devices=[1,2]0,1}
constant.4 = f32[] constant(1), sharding={replicated}
broadcast.0 = f32[4,8]{1,0} broadcast(constant.4), dimensions={}, sharding={devices=[1,2]0,1}
select.40 = f32[4,8]{1,0} select(compare.39, broadcast.0, broadcast.1), sharding={devices=[1,2]0,1}
dot.2 = f32[4,128]{1,0} dot(select.40, Arg_2.3), lhs_contracting_dims={1}, rhs_contracting_dims={1}, sharding={devices=[2,1]0,1}
dot.5 = f32[32,128]{0,1} dot(copy, dot.2), lhs_contracting_dims={0}, rhs_contracting_dims={0}, sharding={devices=[2,1]0,1}
constant.12 = f32[] constant(-0.01), sharding={replicated}
broadcast.13 = f32[32,128]{1,0} broadcast(constant.12), dimensions={}, sharding={devices=[2,1]0,1}
multiply.68 = f32[32,128]{0,1} multiply(dot.5, broadcast.13), sharding={devices=[2,1]0,1}
add.79 = f32[32,128]{1,0} add(Arg_1.2, multiply.68), sharding={devices=[2,1]0,1}
dot.6 = f32[128,8]{0,1} dot(dot.0, select.40), lhs_contracting_dims={0}, rhs_contracting_dims={0}, sharding={devices=[1,2]0,1}
broadcast.11 = f32[128,8]{1,0} broadcast(constant.12), dimensions={}, sharding={devices=[1,2]0,1}
multiply.69 = f32[128,8]{0,1} multiply(dot.6, broadcast.11), sharding={devices=[1,2]0,1}
add.80 = f32[128,8]{1,0} add(Arg_2.3, multiply.69), sharding={devices=[1,2]0,1}
reduce.48 = f32[] reduce(maximum.38, constant.5), dimensions={0,1}, to_apply=region_0.44, sharding={replicated}
ROOT tuple.95 = (f32[32,128]{1,0}, f32[128,8]{1,0}, f32[]) tuple(add.79, add.80, reduce.48), sharding={{devices=[2,1]0,1}, {devices=[1,2]0,1}, {replicated}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(
auto module, ParseAndReturnVerifiedModule(module_str, 1,
2));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<HloValueSemanticsAnalysis> hlo_value_semantics_analysis,
HloValueSemanticsAnalysis::Run(*module));
EXPECT_FALSE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "copy"));
EXPECT_FALSE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "Arg_1.2"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.0"));
EXPECT_FALSE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "Arg_2.3"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.1"));
EXPECT_TRUE(
IsStatic(*hlo_value_semantics_analysis, module.get(), "select.40"));
EXPECT_TRUE(IsWeight(*hlo_value_semantics_analysis, module.get(), "dot.2"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.5"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.6"));
}
TEST_F(HloValueSemanticsAnalysisTest, RepeatWhile) {
const std::string module_str = R"(
HloModule RepeatWhile
region_0.52 {
arg_tuple.53 = (s32[], f32[4,32]{1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}) parameter(0), sharding={{replicated}, {devices=[2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}}
get-tuple-element.54 = s32[] get-tuple-element(arg_tuple.53), index=0, sharding={replicated}
constant.61 = s32[] constant(1), sharding={replicated}
add.105 = s32[] add(get-tuple-element.54, constant.61), sharding={replicated}
get-tuple-element.55 = f32[4,32]{1,0} get-tuple-element(arg_tuple.53), index=1, sharding={devices=[2,1]0,1}
get-tuple-element.59 = f32[3,32,128]{2,1,0} get-tuple-element(arg_tuple.53), index=5, sharding={devices=[1,2,1]0,1}
constant.69 = s32[] constant(0), sharding={replicated}
compare.70 = pred[] compare(get-tuple-element.54, constant.69), direction=LT, sharding={replicated}
constant.68 = s32[] constant(3), sharding={replicated}
add.71 = s32[] add(get-tuple-element.54, constant.68), sharding={replicated}
select.72 = s32[] select(compare.70, add.71, get-tuple-element.54), sharding={replicated}
dynamic-slice.73 = f32[1,32,128]{2,1,0} dynamic-slice(get-tuple-element.59, select.72, constant.69, constant.69), dynamic_slice_sizes={1,32,128}, sharding={devices=[1,2,1]0,1}
reshape.74 = f32[32,128]{1,0} reshape(dynamic-slice.73), sharding={devices=[2,1]0,1}
dot.0 = f32[4,128]{1,0} dot(get-tuple-element.55, reshape.74), lhs_contracting_dims={1}, rhs_contracting_dims={0}, sharding={devices=[2,1]0,1}
get-tuple-element.60 = f32[3,128,32]{2,1,0} get-tuple-element(arg_tuple.53), index=6, sharding={devices=[1,1,2]0,1}
dynamic-slice.78 = f32[1,128,32]{2,1,0} dynamic-slice(get-tuple-element.60, select.72, constant.69, constant.69), dynamic_slice_sizes={1,128,32}, sharding={devices=[1,1,2]0,1}
reshape.79 = f32[128,32]{1,0} reshape(dynamic-slice.78), sharding={devices=[1,2]0,1}
dot.1 = f32[4,32]{1,0} dot(dot.0, reshape.79), lhs_contracting_dims={1}, rhs_contracting_dims={0}, sharding={devices=[2,1]0,1}
constant.43 = f32[] constant(0), sharding={replicated}
broadcast.2 = f32[4,32]{1,0} broadcast(constant.43), dimensions={}, sharding={devices=[2,1]0,1}
maximum.84 = f32[4,32]{1,0} maximum(dot.1, broadcast.2), sharding={devices=[2,1]0,1}
get-tuple-element.56 = f32[3,4,128]{2,1,0} get-tuple-element(arg_tuple.53), index=2, sharding={devices=[1,2,1]0,1}
reshape.90 = f32[1,4,128]{2,1,0} reshape(dot.0), sharding={devices=[1,2,1]0,1}
dynamic-update-slice.94 = f32[3,4,128]{2,1,0} dynamic-update-slice(get-tuple-element.56, reshape.90, select.72, constant.69, constant.69), sharding={devices=[1,2,1]0,1}
get-tuple-element.57 = f32[3,4,32]{2,1,0} get-tuple-element(arg_tuple.53), index=3, sharding={devices=[1,2,1]0,1}
compare.85 = pred[4,32]{1,0} compare(dot.1, maximum.84), direction=EQ, sharding={devices=[2,1]0,1}
constant.42 = f32[] constant(1), sharding={replicated}
broadcast.1 = f32[4,32]{1,0} broadcast(constant.42), dimensions={}, sharding={devices=[2,1]0,1}
select.86 = f32[4,32]{1,0} select(compare.85, broadcast.1, broadcast.2), sharding={devices=[2,1]0,1}
reshape.95 = f32[1,4,32]{2,1,0} reshape(select.86), sharding={devices=[1,2,1]0,1}
dynamic-update-slice.99 = f32[3,4,32]{2,1,0} dynamic-update-slice(get-tuple-element.57, reshape.95, select.72, constant.69, constant.69), sharding={devices=[1,2,1]0,1}
get-tuple-element.58 = f32[3,4,32]{2,1,0} get-tuple-element(arg_tuple.53), index=4, sharding={devices=[1,2,1]0,1}
reshape.100 = f32[1,4,32]{2,1,0} reshape(get-tuple-element.55), sharding={devices=[1,2,1]0,1}
dynamic-update-slice.104 = f32[3,4,32]{2,1,0} dynamic-update-slice(get-tuple-element.58, reshape.100, select.72, constant.69, constant.69), sharding={devices=[1,2,1]0,1}
ROOT tuple.106 = (s32[], f32[4,32]{1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}) tuple(add.105, maximum.84, dynamic-update-slice.94, dynamic-update-slice.99, dynamic-update-slice.104, get-tuple-element.59, get-tuple-element.60), sharding={{replicated}, {devices=[2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}}
}
region_1.107 {
arg_tuple.108 = (s32[], f32[4,32]{1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}) parameter(0), sharding={{replicated}, {devices=[2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}}
get-tuple-element.109 = s32[] get-tuple-element(arg_tuple.108), index=0, sharding={replicated}
constant.116 = s32[] constant(3)
ROOT compare.117 = pred[] compare(get-tuple-element.109, constant.116), direction=LT
}
region_2.126 {
Arg_0.127 = f32[] parameter(0)
Arg_1.128 = f32[] parameter(1)
ROOT add.129 = f32[] add(Arg_0.127, Arg_1.128)
}
wide.wide.region_3.156.clone.clone {
wide_param.7 = (s32[], f32[4,32]{1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,32]{2,1,0}) parameter(0), sharding={{replicated}, {devices=[1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}}
get-tuple-element.185 = s32[] get-tuple-element(wide_param.7), index=0, sharding={replicated}
constant.34 = s32[] constant(1), sharding={replicated}
add.14 = s32[] add(get-tuple-element.185, constant.34), sharding={replicated}
get-tuple-element.186 = f32[4,32]{1,0} get-tuple-element(wide_param.7), index=1, sharding={devices=[2,1]0,1}
get-tuple-element.190 = f32[3,4,32]{2,1,0} get-tuple-element(wide_param.7), index=5, sharding={devices=[1,2,1]0,1}
constant.35 = s32[] constant(3), sharding={replicated}
subtract.3 = s32[] subtract(constant.35, get-tuple-element.185), sharding={replicated}
constant.6..sunk.4 = s32[] constant(-1), sharding={replicated}
add.15 = s32[] add(subtract.3, constant.6..sunk.4), sharding={replicated}
constant.36 = s32[] constant(0), sharding={replicated}
compare.7 = pred[] compare(add.15, constant.36), direction=LT, sharding={replicated}
constant.26..sunk.1 = s32[] constant(2), sharding={replicated}
add.16 = s32[] add(subtract.3, constant.26..sunk.1), sharding={replicated}
select.4 = s32[] select(compare.7, add.16, add.15), sharding={replicated}
dynamic-slice.15 = f32[1,4,32]{2,1,0} dynamic-slice(get-tuple-element.190, select.4, constant.36, constant.36), dynamic_slice_sizes={1,4,32}, sharding={devices=[1,2,1]0,1}
reshape.21 = f32[4,32]{1,0} reshape(dynamic-slice.15), sharding={devices=[2,1]0,1}
multiply.3 = f32[4,32]{1,0} multiply(get-tuple-element.186, reshape.21), sharding={devices=[2,1]0,1}
get-tuple-element.192 = f32[3,128,32]{2,1,0} get-tuple-element(wide_param.7), index=7, sharding={devices=[1,1,2]0,1}
dynamic-slice.16 = f32[1,128,32]{2,1,0} dynamic-slice(get-tuple-element.192, select.4, constant.36, constant.36), dynamic_slice_sizes={1,128,32}, sharding={devices=[1,1,2]0,1}
reshape.22 = f32[128,32]{1,0} reshape(dynamic-slice.16), sharding={devices=[1,2]0,1}
dot.20 = f32[4,128]{1,0} dot(multiply.3, reshape.22), lhs_contracting_dims={1}, rhs_contracting_dims={1}, sharding={devices=[2,1]0,1}
get-tuple-element.191 = f32[3,32,128]{2,1,0} get-tuple-element(wide_param.7), index=6, sharding={devices=[1,2,1]0,1}
dynamic-slice.17 = f32[1,32,128]{2,1,0} dynamic-slice(get-tuple-element.191, select.4, constant.36, constant.36), dynamic_slice_sizes={1,32,128}, sharding={devices=[1,2,1]0,1}
reshape.23 = f32[32,128]{1,0} reshape(dynamic-slice.17), sharding={devices=[2,1]0,1}
dot.21 = f32[4,32]{1,0} dot(dot.20, reshape.23), lhs_contracting_dims={1}, rhs_contracting_dims={1}, sharding={devices=[1,2]0,1}
get-tuple-element.187 = f32[3,32,128]{2,1,0} get-tuple-element(wide_param.7), index=2, sharding={devices=[1,2,1]0,1}
get-tuple-element.193 = f32[3,4,32]{2,1,0} get-tuple-element(wide_param.7), index=8, sharding={devices=[1,2,1]0,1}
dynamic-slice.18 = f32[1,4,32]{2,1,0} dynamic-slice(get-tuple-element.193, select.4, constant.36, constant.36), dynamic_slice_sizes={1,4,32}, sharding={devices=[1,2,1]0,1}
reshape.24 = f32[4,32]{1,0} reshape(dynamic-slice.18), sharding={devices=[2,1]0,1}
dot.22 = f32[32,128]{0,1} dot(reshape.24, dot.20), lhs_contracting_dims={0}, rhs_contracting_dims={0}, sharding={devices=[2,1]0,1}
reshape.25 = f32[1,32,128]{2,1,0} reshape(dot.22), sharding={devices=[1,2,1]0,1}
dynamic-update-slice.6 = f32[3,32,128]{2,1,0} dynamic-update-slice(get-tuple-element.187, reshape.25, select.4, constant.36, constant.36), sharding={devices=[1,2,1]0,1}
get-tuple-element.188 = f32[3,128,32]{2,1,0} get-tuple-element(wide_param.7), index=3, sharding={devices=[1,1,2]0,1}
get-tuple-element.189 = f32[3,4,128]{2,1,0} get-tuple-element(wide_param.7), index=4, sharding={devices=[1,2,1]0,1}
dynamic-slice.19 = f32[1,4,128]{2,1,0} dynamic-slice(get-tuple-element.189, select.4, constant.36, constant.36), dynamic_slice_sizes={1,4,128}, sharding={devices=[1,2,1]0,1}
reshape.26 = f32[4,128]{1,0} reshape(dynamic-slice.19), sharding={devices=[2,1]0,1}
dot.23 = f32[128,32]{0,1} dot(reshape.26, multiply.3), lhs_contracting_dims={0}, rhs_contracting_dims={0}, sharding={devices=[1,2]0,1}
reshape.27 = f32[1,128,32]{2,1,0} reshape(dot.23), sharding={devices=[1,1,2]0,1}
dynamic-update-slice.7 = f32[3,128,32]{2,1,0} dynamic-update-slice(get-tuple-element.188, reshape.27, select.4, constant.36, constant.36), sharding={devices=[1,1,2]0,1}
ROOT tuple.19 = (s32[], f32[4,32]{1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,32]{2,1,0}) tuple(add.14, dot.21, dynamic-update-slice.6, dynamic-update-slice.7, get-tuple-element.189, get-tuple-element.190, get-tuple-element.191, get-tuple-element.192, get-tuple-element.193), sharding={{replicated}, {devices=[1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}}
}
wide.wide.region_4.218.clone.clone {
wide_param.6 = (s32[], f32[4,32]{1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,32]{2,1,0}) parameter(0), sharding={{replicated}, {devices=[1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}}
get-tuple-element.184 = s32[] get-tuple-element(wide_param.6), index=0, sharding={replicated}
constant.28 = s32[] constant(3)
ROOT compare.6 = pred[] compare(get-tuple-element.184, constant.28), direction=LT
}
ENTRY entry {
Arg_1.2 = f32[3,32,128]{2,1,0} parameter(0), sharding={devices=[1,2,1]0,1}
constant.45 = s32[] constant(0), sharding={replicated}
constant.23 = f32[] constant(1), sharding={replicated}
broadcast.24 = f32[4,32]{1,0} broadcast(constant.23), dimensions={}, sharding={devices=[1,2]0,1}
constant.21 = f32[] constant(0), sharding={replicated}
broadcast.22 = f32[3,32,128]{2,1,0} broadcast(constant.21), dimensions={}, sharding={devices=[1,2,1]0,1}
broadcast.20 = f32[3,128,32]{2,1,0} broadcast(constant.21), dimensions={}, sharding={devices=[1,1,2]0,1}
Arg_8.9 = f32[4,32]{1,0} parameter(2), sharding={devices=[2,1]0,1}
copy = f32[4,32]{1,0} copy(Arg_8.9), sharding={devices=[2,1]0,1}
broadcast.28 = f32[3,4,128]{2,1,0} broadcast(constant.21), dimensions={}, sharding={devices=[1,2,1]0,1}
broadcast.26 = f32[3,4,32]{2,1,0} broadcast(constant.21), dimensions={}, sharding={devices=[1,2,1]0,1}
Arg_2.3 = f32[3,128,32]{2,1,0} parameter(1), sharding={devices=[1,1,2]0,1}
tuple.42 = (s32[], f32[4,32]{1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}) tuple(constant.45, copy, broadcast.28, broadcast.26, broadcast.26, Arg_1.2, Arg_2.3), sharding={{replicated}, {devices=[2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}}
while.118 = (s32[], f32[4,32]{1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}) while(tuple.42), condition=region_1.107, body=region_0.52, sharding={{replicated}, {devices=[2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}}
get-tuple-element.179 = f32[3,4,128]{2,1,0} get-tuple-element(while.118), index=2, sharding={devices=[1,2,1]0,1}
get-tuple-element.180 = f32[3,4,32]{2,1,0} get-tuple-element(while.118), index=3, sharding={devices=[1,2,1]0,1}
get-tuple-element.183 = f32[3,4,32]{2,1,0} get-tuple-element(while.118), index=4, sharding={devices=[1,2,1]0,1}
tuple.18 = (s32[], f32[4,32]{1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,32]{2,1,0}) tuple(constant.45, broadcast.24, broadcast.22, broadcast.20, get-tuple-element.179, get-tuple-element.180, Arg_1.2, Arg_2.3, get-tuple-element.183), sharding={{replicated}, {devices=[1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}}
while.3 = (s32[], f32[4,32]{1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,128]{2,1,0}, f32[3,4,32]{2,1,0}, f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[3,4,32]{2,1,0}) while(tuple.18), condition=wide.wide.region_4.218.clone.clone, body=wide.wide.region_3.156.clone.clone, sharding={{replicated}, {devices=[1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {devices=[1,2,1]0,1}}
get-tuple-element.234 = f32[3,32,128]{2,1,0} get-tuple-element(while.3), index=2, sharding={devices=[1,2,1]0,1}
constant.16 = f32[] constant(-0.01), sharding={replicated}
broadcast.17 = f32[3,32,128]{2,1,0} broadcast(constant.16), dimensions={}, sharding={devices=[1,2,1]0,1}
multiply.243 = f32[3,32,128]{2,1,0} multiply(get-tuple-element.234, broadcast.17), sharding={devices=[1,2,1]0,1}
add.255 = f32[3,32,128]{2,1,0} add(Arg_1.2, multiply.243), sharding={devices=[1,2,1]0,1}
get-tuple-element.235 = f32[3,128,32]{2,1,0} get-tuple-element(while.3), index=3, sharding={devices=[1,1,2]0,1}
broadcast.15 = f32[3,128,32]{2,1,0} broadcast(constant.16), dimensions={}, sharding={devices=[1,1,2]0,1}
multiply.244 = f32[3,128,32]{2,1,0} multiply(get-tuple-element.235, broadcast.15), sharding={devices=[1,1,2]0,1}
add.256 = f32[3,128,32]{2,1,0} add(Arg_2.3, multiply.244), sharding={devices=[1,1,2]0,1}
get-tuple-element.120 = f32[4,32]{1,0} get-tuple-element(while.118), index=1, sharding={devices=[2,1]0,1}
reduce.130 = f32[] reduce(get-tuple-element.120, constant.21), dimensions={0,1}, to_apply=region_2.126, sharding={replicated}
ROOT tuple.271 = (f32[3,32,128]{2,1,0}, f32[3,128,32]{2,1,0}, f32[]) tuple(add.255, add.256, reduce.130), sharding={{devices=[1,2,1]0,1}, {devices=[1,1,2]0,1}, {replicated}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(
auto module, ParseAndReturnVerifiedModule(module_str, 1,
2));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<HloValueSemanticsAnalysis> hlo_value_semantics_analysis,
HloValueSemanticsAnalysis::Run(*module));
EXPECT_TRUE(IsWeight(*hlo_value_semantics_analysis, module.get(),
"get-tuple-element.55"));
EXPECT_TRUE(
IsWeight(*hlo_value_semantics_analysis, module.get(), "reshape.74"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.0"));
EXPECT_TRUE(
IsWeight(*hlo_value_semantics_analysis, module.get(), "reshape.79"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.1"));
EXPECT_TRUE(
IsWeight(*hlo_value_semantics_analysis, module.get(), "reshape.22"));
EXPECT_TRUE(
IsStatic(*hlo_value_semantics_analysis, module.get(), "reshape.95"));
EXPECT_TRUE(IsStatic(*hlo_value_semantics_analysis, module.get(),
"dynamic-update-slice.99"));
EXPECT_TRUE(IsStatic(*hlo_value_semantics_analysis, module.get(),
"get-tuple-element.180"));
EXPECT_TRUE(IsStatic(*hlo_value_semantics_analysis, module.get(),
"get-tuple-element.190"));
EXPECT_TRUE(
IsStatic(*hlo_value_semantics_analysis, module.get(), "reshape.21"));
EXPECT_TRUE(
IsStatic(*hlo_value_semantics_analysis, module.get(), "multiply.3"));
EXPECT_TRUE(IsWeight(*hlo_value_semantics_analysis, module.get(), "dot.20"));
EXPECT_TRUE(
IsWeight(*hlo_value_semantics_analysis, module.get(), "reshape.23"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.21"));
EXPECT_TRUE(
IsWeight(*hlo_value_semantics_analysis, module.get(), "reshape.24"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.22"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "reshape.26"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.23"));
}
TEST_F(HloValueSemanticsAnalysisTest, ConvWithClamp) {
const std::string module_str = R"(
HloModule ConvWithClamp
ENTRY entry {
constant.123 = bf16[]{:T(256)} constant(127)
constant.127 = bf16[]{:T(256)} constant(-128)
arg_0 = bf16[128,14,14,1024]{3,0,2,1:T(8,128)(2,1)} parameter(0)
broadcast.819 = bf16[1,1,1024,512]{3,2,1,0:T(8,128)(2,1)} broadcast(constant.127), dimensions={}
arg_1 = bf16[1,1,1024,512]{3,2,1,0:T(8,128)(2,1)} parameter(1)
broadcast.818 = bf16[1,1,1024,512]{3,2,1,0:T(8,128)(2,1)} broadcast(constant.123), dimensions={}
clamp.42 = bf16[1,1,1024,512]{3,2,1,0:T(8,128)(2,1)} clamp(broadcast.819, arg_1, broadcast.818)
round-nearest-even.42 = bf16[1,1,1024,512]{3,2,1,0:T(8,128)(2,1)} round-nearest-even(clamp.42)
convert.219 = s8[1,1,1024,512]{3,2,1,0:T(8,128)(4,1)} convert(round-nearest-even.42)
ROOT convolution.43 = bf16[128,14,14,512]{3,0,2,1:T(8,128)(2,1)} convolution(arg_0, convert.219), window={size=1x1}, dim_labels=b01f_01io->b01f
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(module_str,
1,
1));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<HloValueSemanticsAnalysis> hlo_value_semantics_analysis,
HloValueSemanticsAnalysis::Run(*module));
EXPECT_TRUE(
IsWeight(*hlo_value_semantics_analysis, module.get(), "convert.219"));
}
TEST_F(HloValueSemanticsAnalysisTest, MnistTrainingLoop) {
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kMnistHlo,
1,
1));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<HloValueSemanticsAnalysis> hlo_value_semantics_analysis,
HloValueSemanticsAnalysis::Run(*module));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.63"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.67"));
EXPECT_TRUE(
IsActivation(*hlo_value_semantics_analysis, module.get(), "dot.71"));
EXPECT_TRUE(
IsWeightGradient(*hlo_value_semantics_analysis, module.get(), "dot.85"));
EXPECT_TRUE(IsActivationGradient(*hlo_value_semantics_analysis, module.get(),
"dot.89"));
EXPECT_TRUE(
IsWeightGradient(*hlo_value_semantics_analysis, module.get(), "dot.92"));
EXPECT_TRUE(IsActivationGradient(*hlo_value_semantics_analysis, module.get(),
"dot.96"));
EXPECT_TRUE(
IsWeightGradient(*hlo_value_semantics_analysis, module.get(), "dot.99"));
}
class EinsumDepthAnalysisTest : public HloTestBase {
public:
int GetInstructionDepth(const EinsumDepthMap& depth_map,
HloComputation* computation, absl::string_view name) {
HloInstruction* instruction = computation->GetInstructionWithName(name);
auto depth_iter = depth_map.find(instruction);
EXPECT_NE(depth_iter, depth_map.end());
return depth_iter->second.element({});
}
};
TEST_F(EinsumDepthAnalysisTest, MnistTrainingLoop) {
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kMnistHlo,
1,
1));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<EinsumDepthAnalysis> einsum_depth_analysis,
EinsumDepthAnalysis::Run(*module->entry_computation(),
SendRecvGroupMap(*module)));
const EinsumDepthMap& einsum_depth_map =
einsum_depth_analysis->GetEinsumDepthMap();
HloComputation* computation = module->GetComputationWithName("body.49");
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.63"), 5);
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.67"), 4);
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.71"), 3);
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.89"), 2);
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.96"), 1);
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.92"), 0);
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.99"), 0);
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "dot.85"), 0);
}
TEST_F(EinsumDepthAnalysisTest, HandleConditional) {
const char* const hlo_string = R"(
HloModule Module
branch0 {
tparam = f32[4] parameter(0)
ROOT tgte1 = f32[4] ceil(tparam)
}
branch1 {
fparam = f32[4] parameter(0)
%async-start = ((f32[4]), f32[4], s32[]) abs-start(f32[4] fparam), async_execution_thread="parallel_thread"
ROOT %async-done = f32[4] abs-done(((f32[4]), f32[4], s32[]) %async-start)
}
branch2 {
sparam = f32[4] parameter(0)
ROOT sgte1 = f32[4] ceil(sparam)
}
ENTRY entry {
p0 = f32[4] parameter(0)
b0 = s32[] parameter(1)
ROOT conditional = f32[4] conditional(b0, p0, p0, p0),
branch_computations={branch0, branch1, branch2}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<EinsumDepthAnalysis> einsum_depth_analysis,
EinsumDepthAnalysis::Run(*module->entry_computation(),
SendRecvGroupMap(*module)));
const EinsumDepthMap& einsum_depth_map =
einsum_depth_analysis->GetEinsumDepthMap();
HloComputation* computation = module->GetComputationWithName("entry");
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "conditional"),
0);
}
TEST_F(EinsumDepthAnalysisTest, HandleAfterAll) {
const char* const hlo_string = R"(
ENTRY entry {
after-all.1 = token[] after-all()
parameter.1 = f32[] parameter(0)
send.1 = (f32[], u32[], token[]) send(parameter.1, after-all.1), channel_id=1, is_host_transfer=true, frontend_attributes={_xla_host_transfer_handler_name="tf_rendezvous",_xla_host_transfer_rendezvous="rendezvous1"}
send-done.1 = token[] send-done(send.1), channel_id=1, is_host_transfer=true, frontend_attributes={_xla_host_transfer_handler_name="tf_rendezvous",_xla_host_transfer_rendezvous="rendezvous1"}
ROOT after-all.2 = token[] after-all(send-done.1), frontend_attributes={_xla_host_transfer_handler_name="tf_rendezvous",_xla_host_transfer_rendezvous="rendezvous1"}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<EinsumDepthAnalysis> einsum_depth_analysis,
EinsumDepthAnalysis::Run(*module->entry_computation(),
SendRecvGroupMap(*module)));
const EinsumDepthMap& einsum_depth_map =
einsum_depth_analysis->GetEinsumDepthMap();
HloComputation* computation = module->GetComputationWithName("entry");
EXPECT_EQ(GetInstructionDepth(einsum_depth_map, computation, "after-all.2"),
0);
}
class EinsumHeightAnalysisTest : public HloTestBase {
public:
int GetInstructionHeight(const EinsumHeightMap& height_map,
HloComputation* computation,
absl::string_view name) {
HloInstruction* instruction = computation->GetInstructionWithName(name);
auto height_iter = height_map.find(instruction);
EXPECT_NE(height_iter, height_map.end());
return height_iter->second.element({});
}
};
TEST_F(EinsumHeightAnalysisTest, MnistTrainingLoop) {
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kMnistHlo,
1,
1));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<EinsumHeightAnalysis> einsum_height_analysis,
EinsumHeightAnalysis::Run(*module->entry_computation(),
SendRecvGroupMap(*module)));
const EinsumHeightMap& einsum_height_map =
einsum_height_analysis->GetEinsumHeightMap();
HloComputation* computation = module->GetComputationWithName("body.49");
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.63"), 1);
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.67"), 2);
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.71"), 3);
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.89"), 4);
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.96"), 5);
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.92"), 5);
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.99"), 6);
EXPECT_EQ(GetInstructionHeight(einsum_height_map, computation, "dot.85"), 4);
}
TEST_F(HloValueSemanticsAnalysisTest,
HandleIncompleteForeignThreadComputation) {
constexpr std::string_view hlo = R"(
HloModule Module
ENTRY entry {
foreign-call-start = ((), s32[], s32[]) custom-call-start(), custom_call_target="ThreadSpecificCustomCall", async_execution_thread="foreign_thread"
ROOT foreign-call-done = s32[] custom-call-done(foreign-call-start)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<HloValueSemanticsAnalysis> hlo_value_semantics_analysis,
HloValueSemanticsAnalysis::Run(
*module,
{HloInstruction::kMainExecutionThread}));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/hlo_value_semantics_analysis.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/hlo_value_semantics_analysis_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
e0c0dc3d-b684-49ac-9164-5f32170d6e03 | cpp | tensorflow/tensorflow | graph_runner | tensorflow/core/common_runtime/graph_runner.cc | tensorflow/core/common_runtime/graph_runner_test.cc | #define EIGEN_USE_THREADS
#include "tensorflow/core/common_runtime/graph_runner.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/executor.h"
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/common_runtime/memory_types.h"
#include "tensorflow/core/common_runtime/rendezvous_mgr.h"
#include "tensorflow/core/common_runtime/single_threaded_cpu_device.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace {
class SimpleRendezvous : public RendezvousInterface {
public:
explicit SimpleRendezvous() {}
Status Send(const ParsedKey& parsed, const Args& send_args, const Tensor& val,
const bool is_dead) override {
if (is_dead) {
return errors::Internal("Send of a dead tensor");
}
mutex_lock l(mu_);
string edge_name(parsed.edge_name);
if (table_.count(edge_name) > 0) {
return errors::Internal("Send of an already sent tensor");
}
table_[edge_name] = val;
return absl::OkStatus();
}
void RecvAsync(const ParsedKey& parsed, const Args& recv_args,
DoneCallback done) override {
Tensor tensor;
Status status = absl::OkStatus();
{
string key(parsed.edge_name);
mutex_lock l(mu_);
if (table_.count(key) <= 0) {
status = errors::Internal("Did not find key ", key);
} else {
tensor = table_[key];
}
}
done(status, Args{}, recv_args, tensor, false);
}
void StartAbort(const Status& status) override {}
private:
typedef std::unordered_map<string, Tensor> Table;
mutex mu_;
Table table_ TF_GUARDED_BY(mu_);
};
}
GraphRunner::GraphRunner(Env* env)
: device_deleter_(NewSingleThreadedCpuDevice(env)),
device_(device_deleter_.get()) {}
GraphRunner::GraphRunner(Device* device) : device_(device) {}
GraphRunner::~GraphRunner() {}
Status GraphRunner::Run(Graph* graph, FunctionLibraryRuntime* function_library,
const NamedTensorList& inputs,
const std::vector<string>& output_names,
std::vector<Tensor>* outputs) {
if (device_ == nullptr) {
return errors::NotFound("Cannot find a device for GraphRunner.");
}
if (function_library && function_library->device() &&
function_library->device()->device_type() != device_->device_type()) {
VLOG(1) << "Cannot run on: " << device_->device_type()
<< " with a function library for a "
<< function_library->device()->device_type() << " device.";
function_library = nullptr;
}
std::unique_ptr<Graph> graph_to_run(new Graph(graph->op_registry()));
CopyGraph(*graph, graph_to_run.get());
SimpleRendezvous rendez;
std::vector<string> input_names;
for (const auto& in : inputs) {
const string& tensor_name = in.first;
input_names.emplace_back(tensor_name);
string full_key = Rendezvous::CreateKey("/device:CPU:0", 1, "/device:CPU:1",
tensor_name, FrameAndIter(0, 0));
Rendezvous::ParsedKey parsed;
TF_RETURN_IF_ERROR(Rendezvous::ParseKey(full_key, &parsed));
TF_RETURN_IF_ERROR(rendez.Send(parsed, Rendezvous::Args(), in.second,
false ));
}
subgraph::RewriteGraphMetadata metadata;
TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(
graph_to_run.get(), input_names, output_names, {} ,
device_->attributes(), false , &metadata));
auto runner = [](Executor::Args::Closure c) { c(); };
LocalExecutorParams params;
params.device = device_;
params.function_library = function_library;
const int producer = graph_to_run->versions().producer();
params.create_kernel = [this, function_library, producer](
const std::shared_ptr<const NodeProperties>& props,
OpKernel** kernel) {
return CreateNonCachedKernel(device_, function_library, props, producer,
kernel);
};
params.delete_kernel = [](OpKernel* kernel) { delete kernel; };
Executor* executor;
TF_RETURN_IF_ERROR(NewLocalExecutor(params, *graph_to_run, &executor));
std::unique_ptr<Executor> executor_unref(executor);
Executor::Args args;
args.step_id = LogMemory::CONSTANT_FOLDING_STEP_ID;
args.runner = runner;
args.rendezvous = &rendez;
args.collective_executor = nullptr;
CancellationManager cancellation_manager;
args.cancellation_manager = &cancellation_manager;
if (function_library != nullptr) {
args.session_config = function_library->config_proto();
}
TF_RETURN_IF_ERROR(executor->Run(args));
outputs->resize(output_names.size());
for (size_t i = 0; i < output_names.size(); ++i) {
const string& output_key =
Rendezvous::CreateKey("/device:CPU:0", 1, "/device:CPU:1",
output_names[i], FrameAndIter(0, 0));
Rendezvous::ParsedKey parsed;
TF_RETURN_IF_ERROR(Rendezvous::ParseKey(output_key, &parsed));
bool is_dead;
Tensor output_tensor;
TF_RETURN_IF_ERROR(
rendez.Recv(parsed, Rendezvous::Args(), &output_tensor, &is_dead));
(*outputs)[i] = tensor::DeepCopy(output_tensor);
}
return absl::OkStatus();
}
} | #include <map>
#include <string>
#include <unordered_map>
#include <vector>
#include "tensorflow/core/common_runtime/graph_runner.h"
#include "tensorflow/cc/framework/scope.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/testlib.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace {
TEST(GraphRunnerTest, SingleConst) {
Scope root = Scope::NewRootScope();
auto c = ops::Const(root, 42.0f);
GraphRunner graph_runner(Env::Default());
std::vector<Tensor> outputs;
Status s = graph_runner.Run(root.graph(), nullptr, {}, {c.name()}, &outputs);
TF_ASSERT_OK(s);
test::ExpectEqual(test::AsScalar(42.0f), outputs[0]);
}
TEST(GraphRunnerTest, DeepCopy) {
Scope root = Scope::NewRootScope();
auto p1 = ops::Placeholder(root.WithOpName("p1"), DT_FLOAT);
auto p2 = ops::Placeholder(root.WithOpName("p2"), DT_FLOAT);
auto add = ops::Add(root.WithOpName("add"), p1, p2);
Tensor p1_data(DT_FLOAT, TensorShape({}));
Tensor p2_data(DT_FLOAT, TensorShape({}));
p1_data.scalar<float>()() = 1.0f;
p2_data.scalar<float>()() = 2.0f;
std::vector<std::pair<string, Tensor>> inputs = {{"p1:0", p1_data},
{"p2:0", p2_data}};
std::vector<Tensor> outputs;
{
GraphRunner graph_runner(Env::Default());
Status s =
graph_runner.Run(root.graph(), nullptr, inputs, {"add:0"}, &outputs);
TF_ASSERT_OK(s);
}
test::ExpectEqual(test::AsScalar(3.0f), outputs[0]);
}
TEST(GraphRunnerTest, MultiFetchConst) {
Scope root = Scope::NewRootScope();
auto c = ops::Const(root, 42.0f);
auto pi = ops::Const(root, 3.14f);
GraphRunner graph_runner(Env::Default());
std::vector<Tensor> outputs;
Status s = graph_runner.Run(root.graph(), nullptr, {}, {c.name(), pi.name()},
&outputs);
TF_ASSERT_OK(s);
test::ExpectEqual(test::AsScalar(42.0f), outputs[0]);
test::ExpectEqual(test::AsScalar(3.14f), outputs[1]);
}
TEST(GraphRunnerTest, FeedAndFetch) {
Scope root = Scope::NewRootScope();
auto p1 = ops::Placeholder(root.WithOpName("p1"), DT_FLOAT);
auto p2 = ops::Placeholder(root.WithOpName("p2"), DT_FLOAT);
auto add = ops::Add(root.WithOpName("add"), p1, p2);
Tensor p1_data(DT_FLOAT, TensorShape({}));
Tensor p2_data(DT_FLOAT, TensorShape({}));
p1_data.scalar<float>()() = 1.0f;
p2_data.scalar<float>()() = 2.0f;
std::vector<std::pair<string, Tensor>> inputs = {{"p1:0", p1_data},
{"p2:0", p2_data}};
GraphRunner graph_runner(Env::Default());
std::vector<Tensor> outputs;
Status s =
graph_runner.Run(root.graph(), nullptr, inputs, {"add:0"}, &outputs);
TF_ASSERT_OK(s);
test::ExpectEqual(test::AsScalar(3.0f), outputs[0]);
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/common_runtime/graph_runner.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/core/common_runtime/graph_runner_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
f048a1a5-6f7c-4d47-b8b9-224c351315fd | cpp | google/leveldb | cache | util/cache.cc | util/cache_test.cc | #include "leveldb/cache.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include "port/port.h"
#include "port/thread_annotations.h"
#include "util/hash.h"
#include "util/mutexlock.h"
namespace leveldb {
Cache::~Cache() {}
namespace {
struct LRUHandle {
void* value;
void (*deleter)(const Slice&, void* value);
LRUHandle* next_hash;
LRUHandle* next;
LRUHandle* prev;
size_t charge;
size_t key_length;
bool in_cache;
uint32_t refs;
uint32_t hash;
char key_data[1];
Slice key() const {
assert(next != this);
return Slice(key_data, key_length);
}
};
class HandleTable {
public:
HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); }
~HandleTable() { delete[] list_; }
LRUHandle* Lookup(const Slice& key, uint32_t hash) {
return *FindPointer(key, hash);
}
LRUHandle* Insert(LRUHandle* h) {
LRUHandle** ptr = FindPointer(h->key(), h->hash);
LRUHandle* old = *ptr;
h->next_hash = (old == nullptr ? nullptr : old->next_hash);
*ptr = h;
if (old == nullptr) {
++elems_;
if (elems_ > length_) {
Resize();
}
}
return old;
}
LRUHandle* Remove(const Slice& key, uint32_t hash) {
LRUHandle** ptr = FindPointer(key, hash);
LRUHandle* result = *ptr;
if (result != nullptr) {
*ptr = result->next_hash;
--elems_;
}
return result;
}
private:
uint32_t length_;
uint32_t elems_;
LRUHandle** list_;
LRUHandle** FindPointer(const Slice& key, uint32_t hash) {
LRUHandle** ptr = &list_[hash & (length_ - 1)];
while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) {
ptr = &(*ptr)->next_hash;
}
return ptr;
}
void Resize() {
uint32_t new_length = 4;
while (new_length < elems_) {
new_length *= 2;
}
LRUHandle** new_list = new LRUHandle*[new_length];
memset(new_list, 0, sizeof(new_list[0]) * new_length);
uint32_t count = 0;
for (uint32_t i = 0; i < length_; i++) {
LRUHandle* h = list_[i];
while (h != nullptr) {
LRUHandle* next = h->next_hash;
uint32_t hash = h->hash;
LRUHandle** ptr = &new_list[hash & (new_length - 1)];
h->next_hash = *ptr;
*ptr = h;
h = next;
count++;
}
}
assert(elems_ == count);
delete[] list_;
list_ = new_list;
length_ = new_length;
}
};
class LRUCache {
public:
LRUCache();
~LRUCache();
void SetCapacity(size_t capacity) { capacity_ = capacity; }
Cache::Handle* Insert(const Slice& key, uint32_t hash, void* value,
size_t charge,
void (*deleter)(const Slice& key, void* value));
Cache::Handle* Lookup(const Slice& key, uint32_t hash);
void Release(Cache::Handle* handle);
void Erase(const Slice& key, uint32_t hash);
void Prune();
size_t TotalCharge() const {
MutexLock l(&mutex_);
return usage_;
}
private:
void LRU_Remove(LRUHandle* e);
void LRU_Append(LRUHandle* list, LRUHandle* e);
void Ref(LRUHandle* e);
void Unref(LRUHandle* e);
bool FinishErase(LRUHandle* e) EXCLUSIVE_LOCKS_REQUIRED(mutex_);
size_t capacity_;
mutable port::Mutex mutex_;
size_t usage_ GUARDED_BY(mutex_);
LRUHandle lru_ GUARDED_BY(mutex_);
LRUHandle in_use_ GUARDED_BY(mutex_);
HandleTable table_ GUARDED_BY(mutex_);
};
LRUCache::LRUCache() : capacity_(0), usage_(0) {
lru_.next = &lru_;
lru_.prev = &lru_;
in_use_.next = &in_use_;
in_use_.prev = &in_use_;
}
LRUCache::~LRUCache() {
assert(in_use_.next == &in_use_);
for (LRUHandle* e = lru_.next; e != &lru_;) {
LRUHandle* next = e->next;
assert(e->in_cache);
e->in_cache = false;
assert(e->refs == 1);
Unref(e);
e = next;
}
}
void LRUCache::Ref(LRUHandle* e) {
if (e->refs == 1 && e->in_cache) {
LRU_Remove(e);
LRU_Append(&in_use_, e);
}
e->refs++;
}
void LRUCache::Unref(LRUHandle* e) {
assert(e->refs > 0);
e->refs--;
if (e->refs == 0) {
assert(!e->in_cache);
(*e->deleter)(e->key(), e->value);
free(e);
} else if (e->in_cache && e->refs == 1) {
LRU_Remove(e);
LRU_Append(&lru_, e);
}
}
void LRUCache::LRU_Remove(LRUHandle* e) {
e->next->prev = e->prev;
e->prev->next = e->next;
}
void LRUCache::LRU_Append(LRUHandle* list, LRUHandle* e) {
e->next = list;
e->prev = list->prev;
e->prev->next = e;
e->next->prev = e;
}
Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) {
MutexLock l(&mutex_);
LRUHandle* e = table_.Lookup(key, hash);
if (e != nullptr) {
Ref(e);
}
return reinterpret_cast<Cache::Handle*>(e);
}
void LRUCache::Release(Cache::Handle* handle) {
MutexLock l(&mutex_);
Unref(reinterpret_cast<LRUHandle*>(handle));
}
Cache::Handle* LRUCache::Insert(const Slice& key, uint32_t hash, void* value,
size_t charge,
void (*deleter)(const Slice& key,
void* value)) {
MutexLock l(&mutex_);
LRUHandle* e =
reinterpret_cast<LRUHandle*>(malloc(sizeof(LRUHandle) - 1 + key.size()));
e->value = value;
e->deleter = deleter;
e->charge = charge;
e->key_length = key.size();
e->hash = hash;
e->in_cache = false;
e->refs = 1;
std::memcpy(e->key_data, key.data(), key.size());
if (capacity_ > 0) {
e->refs++;
e->in_cache = true;
LRU_Append(&in_use_, e);
usage_ += charge;
FinishErase(table_.Insert(e));
} else {
e->next = nullptr;
}
while (usage_ > capacity_ && lru_.next != &lru_) {
LRUHandle* old = lru_.next;
assert(old->refs == 1);
bool erased = FinishErase(table_.Remove(old->key(), old->hash));
if (!erased) {
assert(erased);
}
}
return reinterpret_cast<Cache::Handle*>(e);
}
bool LRUCache::FinishErase(LRUHandle* e) {
if (e != nullptr) {
assert(e->in_cache);
LRU_Remove(e);
e->in_cache = false;
usage_ -= e->charge;
Unref(e);
}
return e != nullptr;
}
void LRUCache::Erase(const Slice& key, uint32_t hash) {
MutexLock l(&mutex_);
FinishErase(table_.Remove(key, hash));
}
void LRUCache::Prune() {
MutexLock l(&mutex_);
while (lru_.next != &lru_) {
LRUHandle* e = lru_.next;
assert(e->refs == 1);
bool erased = FinishErase(table_.Remove(e->key(), e->hash));
if (!erased) {
assert(erased);
}
}
}
static const int kNumShardBits = 4;
static const int kNumShards = 1 << kNumShardBits;
class ShardedLRUCache : public Cache {
private:
LRUCache shard_[kNumShards];
port::Mutex id_mutex_;
uint64_t last_id_;
static inline uint32_t HashSlice(const Slice& s) {
return Hash(s.data(), s.size(), 0);
}
static uint32_t Shard(uint32_t hash) { return hash >> (32 - kNumShardBits); }
public:
explicit ShardedLRUCache(size_t capacity) : last_id_(0) {
const size_t per_shard = (capacity + (kNumShards - 1)) / kNumShards;
for (int s = 0; s < kNumShards; s++) {
shard_[s].SetCapacity(per_shard);
}
}
~ShardedLRUCache() override {}
Handle* Insert(const Slice& key, void* value, size_t charge,
void (*deleter)(const Slice& key, void* value)) override {
const uint32_t hash = HashSlice(key);
return shard_[Shard(hash)].Insert(key, hash, value, charge, deleter);
}
Handle* Lookup(const Slice& key) override {
const uint32_t hash = HashSlice(key);
return shard_[Shard(hash)].Lookup(key, hash);
}
void Release(Handle* handle) override {
LRUHandle* h = reinterpret_cast<LRUHandle*>(handle);
shard_[Shard(h->hash)].Release(handle);
}
void Erase(const Slice& key) override {
const uint32_t hash = HashSlice(key);
shard_[Shard(hash)].Erase(key, hash);
}
void* Value(Handle* handle) override {
return reinterpret_cast<LRUHandle*>(handle)->value;
}
uint64_t NewId() override {
MutexLock l(&id_mutex_);
return ++(last_id_);
}
void Prune() override {
for (int s = 0; s < kNumShards; s++) {
shard_[s].Prune();
}
}
size_t TotalCharge() const override {
size_t total = 0;
for (int s = 0; s < kNumShards; s++) {
total += shard_[s].TotalCharge();
}
return total;
}
};
}
Cache* NewLRUCache(size_t capacity) { return new ShardedLRUCache(capacity); }
} | #include "leveldb/cache.h"
#include <vector>
#include "gtest/gtest.h"
#include "util/coding.h"
namespace leveldb {
static std::string EncodeKey(int k) {
std::string result;
PutFixed32(&result, k);
return result;
}
static int DecodeKey(const Slice& k) {
assert(k.size() == 4);
return DecodeFixed32(k.data());
}
static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }
static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); }
class CacheTest : public testing::Test {
public:
static void Deleter(const Slice& key, void* v) {
current_->deleted_keys_.push_back(DecodeKey(key));
current_->deleted_values_.push_back(DecodeValue(v));
}
static constexpr int kCacheSize = 1000;
std::vector<int> deleted_keys_;
std::vector<int> deleted_values_;
Cache* cache_;
CacheTest() : cache_(NewLRUCache(kCacheSize)) { current_ = this; }
~CacheTest() { delete cache_; }
int Lookup(int key) {
Cache::Handle* handle = cache_->Lookup(EncodeKey(key));
const int r = (handle == nullptr) ? -1 : DecodeValue(cache_->Value(handle));
if (handle != nullptr) {
cache_->Release(handle);
}
return r;
}
void Insert(int key, int value, int charge = 1) {
cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter));
}
Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) {
return cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter);
}
void Erase(int key) { cache_->Erase(EncodeKey(key)); }
static CacheTest* current_;
};
CacheTest* CacheTest::current_;
TEST_F(CacheTest, HitAndMiss) {
ASSERT_EQ(-1, Lookup(100));
Insert(100, 101);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(200, 201);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(100, 102);
ASSERT_EQ(102, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
}
TEST_F(CacheTest, Erase) {
Erase(200);
ASSERT_EQ(0, deleted_keys_.size());
Insert(100, 101);
Insert(200, 201);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1, deleted_keys_.size());
}
TEST_F(CacheTest, EntriesArePinned) {
Insert(100, 101);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));
Insert(100, 102);
Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));
ASSERT_EQ(0, deleted_keys_.size());
cache_->Release(h1);
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(1, deleted_keys_.size());
cache_->Release(h2);
ASSERT_EQ(2, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[1]);
ASSERT_EQ(102, deleted_values_[1]);
}
TEST_F(CacheTest, EvictionPolicy) {
Insert(100, 101);
Insert(200, 201);
Insert(300, 301);
Cache::Handle* h = cache_->Lookup(EncodeKey(300));
for (int i = 0; i < kCacheSize + 100; i++) {
Insert(1000 + i, 2000 + i);
ASSERT_EQ(2000 + i, Lookup(1000 + i));
ASSERT_EQ(101, Lookup(100));
}
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(301, Lookup(300));
cache_->Release(h);
}
TEST_F(CacheTest, UseExceedsCacheSize) {
std::vector<Cache::Handle*> h;
for (int i = 0; i < kCacheSize + 100; i++) {
h.push_back(InsertAndReturnHandle(1000 + i, 2000 + i));
}
for (int i = 0; i < h.size(); i++) {
ASSERT_EQ(2000 + i, Lookup(1000 + i));
}
for (int i = 0; i < h.size(); i++) {
cache_->Release(h[i]);
}
}
TEST_F(CacheTest, HeavyEntries) {
const int kLight = 1;
const int kHeavy = 10;
int added = 0;
int index = 0;
while (added < 2 * kCacheSize) {
const int weight = (index & 1) ? kLight : kHeavy;
Insert(index, 1000 + index, weight);
added += weight;
index++;
}
int cached_weight = 0;
for (int i = 0; i < index; i++) {
const int weight = (i & 1 ? kLight : kHeavy);
int r = Lookup(i);
if (r >= 0) {
cached_weight += weight;
ASSERT_EQ(1000 + i, r);
}
}
ASSERT_LE(cached_weight, kCacheSize + kCacheSize / 10);
}
TEST_F(CacheTest, NewId) {
uint64_t a = cache_->NewId();
uint64_t b = cache_->NewId();
ASSERT_NE(a, b);
}
TEST_F(CacheTest, Prune) {
Insert(1, 100);
Insert(2, 200);
Cache::Handle* handle = cache_->Lookup(EncodeKey(1));
ASSERT_TRUE(handle);
cache_->Prune();
cache_->Release(handle);
ASSERT_EQ(100, Lookup(1));
ASSERT_EQ(-1, Lookup(2));
}
TEST_F(CacheTest, ZeroSizeCache) {
delete cache_;
cache_ = NewLRUCache(0);
Insert(1, 100);
ASSERT_EQ(-1, Lookup(1));
}
} | https://github.com/google/leveldb/blob/23e35d792b9154f922b8b575b12596a4d8664c65/util/cache.cc | https://github.com/google/leveldb/blob/23e35d792b9154f922b8b575b12596a4d8664c65/util/cache_test.cc | 23e35d792b9154f922b8b575b12596a4d8664c65 |
0edc4c8a-f0c9-41bf-9ec3-d20068361023 | cpp | google/cel-cpp | logical_function_registrar | eval/public/logical_function_registrar.cc | eval/public/logical_function_registrar_test.cc | #include "eval/public/logical_function_registrar.h"
#include "absl/status/status.h"
#include "eval/public/cel_function_registry.h"
#include "eval/public/cel_options.h"
#include "runtime/standard/logical_functions.h"
namespace google::api::expr::runtime {
absl::Status RegisterLogicalFunctions(CelFunctionRegistry* registry,
const InterpreterOptions& options) {
return cel::RegisterLogicalFunctions(registry->InternalGetRegistry(),
ConvertToRuntimeOptions(options));
}
} | #include "eval/public/logical_function_registrar.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/arena.h"
#include "absl/base/no_destructor.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "eval/public/activation.h"
#include "eval/public/cel_expr_builder_factory.h"
#include "eval/public/cel_expression.h"
#include "eval/public/cel_options.h"
#include "eval/public/cel_value.h"
#include "eval/public/portable_cel_function_adapter.h"
#include "eval/public/testing/matchers.h"
#include "internal/testing.h"
#include "parser/parser.h"
namespace google::api::expr::runtime {
namespace {
using google::api::expr::v1alpha1::Expr;
using google::api::expr::v1alpha1::SourceInfo;
using ::absl_testing::StatusIs;
using ::testing::HasSubstr;
struct TestCase {
std::string test_name;
std::string expr;
absl::StatusOr<CelValue> result = CelValue::CreateBool(true);
};
const CelError* ExampleError() {
static absl::NoDestructor<absl::Status> error(
absl::InternalError("test example error"));
return &*error;
}
void ExpectResult(const TestCase& test_case) {
auto parsed_expr = parser::Parse(test_case.expr);
ASSERT_OK(parsed_expr);
const Expr& expr_ast = parsed_expr->expr();
const SourceInfo& source_info = parsed_expr->source_info();
InterpreterOptions options;
options.short_circuiting = true;
std::unique_ptr<CelExpressionBuilder> builder =
CreateCelExpressionBuilder(options);
ASSERT_OK(RegisterLogicalFunctions(builder->GetRegistry(), options));
ASSERT_OK(builder->GetRegistry()->Register(
PortableUnaryFunctionAdapter<CelValue, CelValue::StringHolder>::Create(
"toBool", false,
[](google::protobuf::Arena*, CelValue::StringHolder holder) -> CelValue {
if (holder.value() == "true") {
return CelValue::CreateBool(true);
} else if (holder.value() == "false") {
return CelValue::CreateBool(false);
}
return CelValue::CreateError(ExampleError());
})));
ASSERT_OK_AND_ASSIGN(auto cel_expression,
builder->CreateExpression(&expr_ast, &source_info));
Activation activation;
google::protobuf::Arena arena;
ASSERT_OK_AND_ASSIGN(auto value,
cel_expression->Evaluate(activation, &arena));
if (!test_case.result.ok()) {
EXPECT_TRUE(value.IsError());
EXPECT_THAT(*value.ErrorOrDie(),
StatusIs(test_case.result.status().code(),
HasSubstr(test_case.result.status().message())));
return;
}
EXPECT_THAT(value, test::EqualsCelValue(*test_case.result));
}
using BuiltinFuncParamsTest = testing::TestWithParam<TestCase>;
TEST_P(BuiltinFuncParamsTest, StandardFunctions) { ExpectResult(GetParam()); }
INSTANTIATE_TEST_SUITE_P(
BuiltinFuncParamsTest, BuiltinFuncParamsTest,
testing::ValuesIn<TestCase>({
{"LogicalNotOfTrue", "!true", CelValue::CreateBool(false)},
{"LogicalNotOfFalse", "!false", CelValue::CreateBool(true)},
{"NotStrictlyFalseTrue", "[true, true, true].all(x, x)",
CelValue::CreateBool(true)},
{"NotStrictlyFalseErrorShortcircuit",
"['true', 'false', 'error'].all(x, toBool(x))",
CelValue::CreateBool(false)},
{"NotStrictlyFalseError", "['true', 'true', 'error'].all(x, toBool(x))",
CelValue::CreateError(ExampleError())},
{"NotStrictlyFalseFalse", "[false, false, false].all(x, x)",
CelValue::CreateBool(false)},
}),
[](const testing::TestParamInfo<BuiltinFuncParamsTest::ParamType>& info) {
return info.param.test_name;
});
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/logical_function_registrar.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/eval/public/logical_function_registrar_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
cf22b863-770e-44ee-9819-8cef360eb2f4 | cpp | abseil/abseil-cpp | crc_memcpy | absl/crc/internal/crc_memcpy.h | absl/crc/internal/crc_memcpy_test.cc | #ifndef ABSL_CRC_INTERNAL_CRC_MEMCPY_H_
#define ABSL_CRC_INTERNAL_CRC_MEMCPY_H_
#include <cstddef>
#include <memory>
#include "absl/base/config.h"
#include "absl/crc/crc32c.h"
#include "absl/crc/internal/crc32_x86_arm_combined_simd.h"
#if defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD)
#define ABSL_INTERNAL_HAVE_X86_64_ACCELERATED_CRC_MEMCPY_ENGINE 1
#elif defined(ABSL_CRC_INTERNAL_HAVE_ARM_SIMD)
#define ABSL_INTERNAL_HAVE_ARM_ACCELERATED_CRC_MEMCPY_ENGINE 1
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace crc_internal {
class CrcMemcpyEngine {
public:
virtual ~CrcMemcpyEngine() = default;
virtual crc32c_t Compute(void* __restrict dst, const void* __restrict src,
std::size_t length, crc32c_t initial_crc) const = 0;
protected:
CrcMemcpyEngine() = default;
};
class CrcMemcpy {
public:
static crc32c_t CrcAndCopy(void* __restrict dst, const void* __restrict src,
std::size_t length,
crc32c_t initial_crc = crc32c_t{0},
bool non_temporal = false) {
static const ArchSpecificEngines engines = GetArchSpecificEngines();
auto* engine = non_temporal ? engines.non_temporal : engines.temporal;
return engine->Compute(dst, src, length, initial_crc);
}
static std::unique_ptr<CrcMemcpyEngine> GetTestEngine(int vector,
int integer);
private:
struct ArchSpecificEngines {
CrcMemcpyEngine* temporal;
CrcMemcpyEngine* non_temporal;
};
static ArchSpecificEngines GetArchSpecificEngines();
};
class FallbackCrcMemcpyEngine : public CrcMemcpyEngine {
public:
FallbackCrcMemcpyEngine() = default;
FallbackCrcMemcpyEngine(const FallbackCrcMemcpyEngine&) = delete;
FallbackCrcMemcpyEngine operator=(const FallbackCrcMemcpyEngine&) = delete;
crc32c_t Compute(void* __restrict dst, const void* __restrict src,
std::size_t length, crc32c_t initial_crc) const override;
};
class CrcNonTemporalMemcpyEngine : public CrcMemcpyEngine {
public:
CrcNonTemporalMemcpyEngine() = default;
CrcNonTemporalMemcpyEngine(const CrcNonTemporalMemcpyEngine&) = delete;
CrcNonTemporalMemcpyEngine operator=(const CrcNonTemporalMemcpyEngine&) =
delete;
crc32c_t Compute(void* __restrict dst, const void* __restrict src,
std::size_t length, crc32c_t initial_crc) const override;
};
class CrcNonTemporalMemcpyAVXEngine : public CrcMemcpyEngine {
public:
CrcNonTemporalMemcpyAVXEngine() = default;
CrcNonTemporalMemcpyAVXEngine(const CrcNonTemporalMemcpyAVXEngine&) = delete;
CrcNonTemporalMemcpyAVXEngine operator=(
const CrcNonTemporalMemcpyAVXEngine&) = delete;
crc32c_t Compute(void* __restrict dst, const void* __restrict src,
std::size_t length, crc32c_t initial_crc) const override;
};
inline crc32c_t Crc32CAndCopy(void* __restrict dst, const void* __restrict src,
std::size_t length,
crc32c_t initial_crc = crc32c_t{0},
bool non_temporal = false) {
return CrcMemcpy::CrcAndCopy(dst, src, length, initial_crc, non_temporal);
}
}
ABSL_NAMESPACE_END
}
#endif | #include "absl/crc/internal/crc_memcpy.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "absl/crc/crc32c.h"
#include "absl/memory/memory.h"
#include "absl/random/distributions.h"
#include "absl/random/random.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace {
enum CrcEngine {
ACCELERATED = 0,
NONTEMPORAL = 1,
FALLBACK = 2,
};
template <size_t max_size>
class CrcMemcpyTest : public testing::Test {
protected:
CrcMemcpyTest() {
source_ = std::make_unique<char[]>(kSize);
destination_ = std::make_unique<char[]>(kSize);
}
static constexpr size_t kAlignment = 16;
static constexpr size_t kMaxCopySize = max_size;
static constexpr size_t kSize = kAlignment + kMaxCopySize;
std::unique_ptr<char[]> source_;
std::unique_ptr<char[]> destination_;
absl::BitGen gen_;
};
typedef CrcMemcpyTest<4500> CrcSmallTest;
typedef CrcMemcpyTest<(1 << 24)> CrcLargeTest;
template <typename ParamsT>
class EngineParamTestTemplate : public CrcSmallTest,
public ::testing::WithParamInterface<ParamsT> {
protected:
EngineParamTestTemplate() {
if (GetParam().crc_engine_selector == FALLBACK) {
engine_ = std::make_unique<absl::crc_internal::FallbackCrcMemcpyEngine>();
} else if (GetParam().crc_engine_selector == NONTEMPORAL) {
engine_ =
std::make_unique<absl::crc_internal::CrcNonTemporalMemcpyEngine>();
} else {
engine_ = absl::crc_internal::CrcMemcpy::GetTestEngine(
GetParam().vector_lanes, GetParam().integer_lanes);
}
}
ParamsT GetParam() const {
return ::testing::WithParamInterface<ParamsT>::GetParam();
}
std::unique_ptr<absl::crc_internal::CrcMemcpyEngine> engine_;
};
struct TestParams {
CrcEngine crc_engine_selector = ACCELERATED;
int vector_lanes = 0;
int integer_lanes = 0;
};
using EngineParamTest = EngineParamTestTemplate<TestParams>;
TEST_P(EngineParamTest, SmallCorrectnessCheckSourceAlignment) {
constexpr size_t kTestSizes[] = {0, 100, 255, 512, 1024, 4000, kMaxCopySize};
for (size_t source_alignment = 0; source_alignment < kAlignment;
source_alignment++) {
for (auto size : kTestSizes) {
char* base_data = static_cast<char*>(source_.get()) + source_alignment;
for (size_t i = 0; i < size; i++) {
*(base_data + i) =
static_cast<char>(absl::Uniform<unsigned char>(gen_));
}
SCOPED_TRACE(absl::StrCat("engine=<", GetParam().vector_lanes, ",",
GetParam().integer_lanes, ">, ", "size=", size,
", source_alignment=", source_alignment));
absl::crc32c_t initial_crc =
absl::crc32c_t{absl::Uniform<uint32_t>(gen_)};
absl::crc32c_t experiment_crc =
engine_->Compute(destination_.get(), source_.get() + source_alignment,
size, initial_crc);
int mem_comparison =
memcmp(destination_.get(), source_.get() + source_alignment, size);
SCOPED_TRACE(absl::StrCat("Error in memcpy of size: ", size,
" with source alignment: ", source_alignment));
ASSERT_EQ(mem_comparison, 0);
absl::crc32c_t baseline_crc = absl::ExtendCrc32c(
initial_crc,
absl::string_view(
static_cast<char*>(source_.get()) + source_alignment, size));
ASSERT_EQ(baseline_crc, experiment_crc);
}
}
}
TEST_P(EngineParamTest, SmallCorrectnessCheckDestAlignment) {
constexpr size_t kTestSizes[] = {0, 100, 255, 512, 1024, 4000, kMaxCopySize};
for (size_t dest_alignment = 0; dest_alignment < kAlignment;
dest_alignment++) {
for (auto size : kTestSizes) {
char* base_data = static_cast<char*>(source_.get());
for (size_t i = 0; i < size; i++) {
*(base_data + i) =
static_cast<char>(absl::Uniform<unsigned char>(gen_));
}
SCOPED_TRACE(absl::StrCat("engine=<", GetParam().vector_lanes, ",",
GetParam().integer_lanes, ">, ", "size=", size,
", destination_alignment=", dest_alignment));
absl::crc32c_t initial_crc =
absl::crc32c_t{absl::Uniform<uint32_t>(gen_)};
absl::crc32c_t experiment_crc =
engine_->Compute(destination_.get() + dest_alignment, source_.get(),
size, initial_crc);
int mem_comparison =
memcmp(destination_.get() + dest_alignment, source_.get(), size);
SCOPED_TRACE(absl::StrCat("Error in memcpy of size: ", size,
" with dest alignment: ", dest_alignment));
ASSERT_EQ(mem_comparison, 0);
absl::crc32c_t baseline_crc = absl::ExtendCrc32c(
initial_crc,
absl::string_view(static_cast<char*>(source_.get()), size));
ASSERT_EQ(baseline_crc, experiment_crc);
}
}
}
INSTANTIATE_TEST_SUITE_P(EngineParamTest, EngineParamTest,
::testing::Values(
TestParams{ACCELERATED, 3, 0},
TestParams{ACCELERATED, 1, 2},
TestParams{ACCELERATED, 1, 0},
TestParams{FALLBACK, 0, 0},
TestParams{NONTEMPORAL, 0, 0}));
} | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/crc_memcpy.h | https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/crc_memcpy_test.cc | 03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4 |
5cf01089-e79f-4ce7-a37b-9125f745fbbb | cpp | tensorflow/tensorflow | convolution_transposed | tensorflow/lite/delegates/gpu/common/tasks/convolution_transposed.cc | tensorflow/lite/delegates/gpu/cl/kernels/convolution_transposed_test.cc | #include "tensorflow/lite/delegates/gpu/common/tasks/convolution_transposed.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/substitute.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/task/weights_layout.h"
#include "tensorflow/lite/delegates/gpu/common/task/work_group_picking.h"
namespace tflite {
namespace gpu {
namespace {
bool UseBufferForWeights(const GpuInfo& gpu_info) {
return gpu_info.IsMali() || gpu_info.IsApple() || gpu_info.IsAMD();
}
}
ConvolutionTransposed::ConvolutionTransposed(
const OperationDef& definition, const ConvolutionTransposedAttributes& attr,
const GpuInfo& gpu_info)
: GPUOperation(definition),
stride_(attr.stride.w, attr.stride.h, 1, 1),
block_size_(2, 2, 1, 2) {
if (UseBufferForWeights(gpu_info)) {
if (gpu_info.IsApple()) {
weights_layout_ = WeightsLayout::kOSpatialIOGroupO4I4;
} else {
weights_layout_ = WeightsLayout::kOSpatialIOGroupI4O4;
}
} else {
if (gpu_info.IsApple()) {
weights_layout_ = WeightsLayout::k2DX4O4YIsSpatialIAndXIsOOGroupI4;
} else {
weights_layout_ = WeightsLayout::k2DX4I4YIsSpatialIAndXIsOOGroupO4;
}
}
const bool is_f16 = definition.precision == CalculationsPrecision::F16;
if (gpu_info.IsMali()) {
if (gpu_info.mali_info.IsMidgard()) {
block_size_ = is_f16 ? int4(2, 1, 1, 2) : int4(2, 1, 1, 1);
} else {
block_size_ = is_f16 ? int4(2, 2, 1, 2) : int4(2, 2, 1, 1);
}
compiler_options_.push_back(CompilerOptions::kClFastRelaxedMath);
}
const int dst_depth = DivideRoundUp(attr.weights.shape.o, 4);
if (dst_depth == 1 || dst_depth == 3) {
if (!gpu_info.IsMali()) {
block_size_.y *= block_size_.w;
}
block_size_.w = 1;
}
args_.AddInt("stride_x", stride_.x);
args_.AddInt("stride_y", stride_.y);
args_.AddInt("padding_x", attr.padding.prepended.w);
args_.AddInt("padding_y", attr.padding.prepended.h);
args_.AddInt("kernel_size_x", attr.weights.shape.w);
args_.AddInt("kernel_size_y", attr.weights.shape.h);
code_ = GenerateConvolutionTransposedCode(definition_, gpu_info, block_size_);
}
ConvolutionTransposed::ConvolutionTransposed(
const OperationDef& definition,
const ConvolutionTransposed3DAttributes& attr, const GpuInfo& gpu_info)
: GPUOperation(definition),
stride_(attr.stride.w, attr.stride.h, attr.stride.d, 1),
block_size_(2, 2, 1, 2) {
if (UseBufferForWeights(gpu_info)) {
if (gpu_info.IsApple()) {
weights_layout_ = WeightsLayout::kOSpatialIOGroupO4I4;
} else {
weights_layout_ = WeightsLayout::kOSpatialIOGroupI4O4;
}
} else {
if (gpu_info.IsApple()) {
weights_layout_ = WeightsLayout::k2DX4O4YIsSpatialIAndXIsOOGroupI4;
} else {
weights_layout_ = WeightsLayout::k2DX4I4YIsSpatialIAndXIsOOGroupO4;
}
}
const bool is_f16 = definition.precision == CalculationsPrecision::F16;
if (gpu_info.IsMali()) {
if (gpu_info.mali_info.IsMidgard()) {
block_size_ = is_f16 ? int4(2, 1, 1, 2) : int4(2, 1, 1, 1);
} else {
block_size_ = is_f16 ? int4(2, 2, 1, 2) : int4(2, 2, 1, 1);
}
compiler_options_.push_back(CompilerOptions::kClFastRelaxedMath);
}
const int dst_depth = DivideRoundUp(attr.weights.shape.o, 4);
if (dst_depth == 1 || dst_depth == 3) {
if (!gpu_info.IsMali()) {
block_size_.y *= block_size_.w;
}
block_size_.w = 1;
}
args_.AddInt("stride_x", stride_.x);
args_.AddInt("stride_y", stride_.y);
args_.AddInt("stride_z", stride_.z);
args_.AddInt("padding_x", attr.padding.prepended.w);
args_.AddInt("padding_y", attr.padding.prepended.h);
args_.AddInt("padding_z", attr.padding.prepended.d);
args_.AddInt("kernel_size_x", attr.weights.shape.w);
args_.AddInt("kernel_size_y", attr.weights.shape.h);
args_.AddInt("kernel_size_z", attr.weights.shape.d);
args_.AddInt("grid_size_y");
code_ = GenerateConvolutionTransposedCode(definition_, gpu_info, block_size_);
}
std::string ConvolutionTransposed::GenerateConvolutionTransposedCode(
const OperationDef& op_def, const GpuInfo& gpu_info,
const int4& block_size) {
AddSrcTensor("src_tensor", op_def.src_tensors[0]);
AddDstTensor("dst_tensor", op_def.dst_tensors[0]);
if (op_def.src_tensors.size() != 1) {
if (weights_layout_ == WeightsLayout::kOSpatialIOGroupI4O4 ||
weights_layout_ == WeightsLayout::kOSpatialIOGroupO4I4) {
BufferDescriptor desc;
desc.element_type = op_def.src_tensors[1].GetDataType();
desc.element_size = 4;
desc.memory_type = MemoryType::GLOBAL;
AddSrcBuffer("weights", desc);
} else {
for (int i = 0; i < 4; ++i) {
const std::string name = "weights" + std::to_string(i);
AddSrcTensor(name, definition_.src_tensors[1 + i]);
}
}
}
const auto& src_def = op_def.src_tensors[0];
std::string c;
const bool weights_are_buffer = UseBufferForWeights(gpu_info);
for (int s = 0; s < block_size.w; ++s) {
std::string f0, f1, f2, f3;
if (weights_are_buffer) {
if (gpu_info.SupportsPointersInKernels()) {
f0 = "weights_cache[" + std::to_string(s * 4 + 0) + "]";
f1 = "weights_cache[" + std::to_string(s * 4 + 1) + "]";
f2 = "weights_cache[" + std::to_string(s * 4 + 2) + "]";
f3 = "weights_cache[" + std::to_string(s * 4 + 3) + "]";
} else {
f0 = "f0";
f1 = "f1";
f2 = "f2";
f3 = "f3";
}
} else {
f0 = "f" + std::to_string(s * 4 + 0);
f1 = "f" + std::to_string(s * 4 + 1);
f2 = "f" + std::to_string(s * 4 + 2);
f3 = "f" + std::to_string(s * 4 + 3);
}
bool use_fma = gpu_info.IsAMD() && gpu_info.IsApiOpenCl();
if (GetWeightsDescription().IsI4O4()) {
switch (op_def.precision) {
case CalculationsPrecision::F32:
case CalculationsPrecision::F16:
if (use_fma) {
c += "#define CONV" + std::to_string(s) + "(R, S) \\\n";
c += "R = fma(" + f0 + ", S.x, R); \\\n";
c += "R = fma(" + f1 + ", S.y, R); \\\n";
c += "R = fma(" + f2 + ", S.z, R); \\\n";
c += "R = fma(" + f3 + ", S.w, R); \n";
} else {
c += "#define CONV" + std::to_string(s) + "(R, S) \\\n";
c += "R += S.x * " + f0 + "; \\\n";
c += "R += S.y * " + f1 + "; \\\n";
c += "R += S.z * " + f2 + "; \\\n";
c += "R += S.w * " + f3 + "; \n";
}
break;
case CalculationsPrecision::F32_F16:
c += "#define CONV" + std::to_string(s) + "(R, S) \\\n";
c += "R += TO_ACCUM_TYPE(S.x * " + f0 + " + S.y * " + f1 +
" + S.z * " + f2 + " + S.w * " + f3 + ");\n";
break;
}
} else {
c += "#define CONV" + std::to_string(s) + "(R, S) \\\n";
c += "R.x += dot(S, " + f0 + "); \\\n";
c += "R.y += dot(S, " + f1 + "); \\\n";
c += "R.z += dot(S, " + f2 + "); \\\n";
c += "R.w += dot(S, " + f3 + "); \n";
}
}
auto generate_id = [&](const std::string& x, const std::string& y,
const std::string& z) {
std::string id;
if (src_def.HasAxis(Axis::WIDTH)) {
id += "_w" + x;
}
if (src_def.HasAxis(Axis::HEIGHT)) {
id += "_h" + y;
}
if (src_def.HasAxis(Axis::DEPTH)) {
id += "_d" + z;
}
return id;
};
auto generate_id_full = [&](const std::string& x, const std::string& y,
const std::string& z, const std::string& s) {
return generate_id(x, y, z) + "_s" + s;
};
auto generate_check = [&](const std::string& x, const std::string& y,
const std::string& z) {
std::string check;
const std::vector<Axis> axes{Axis::WIDTH, Axis::HEIGHT, Axis::DEPTH};
const std::vector<std::string> names{"in_x", "in_y", "in_z"};
const std::vector<std::string> coords{x, y, z};
for (int i = 0; i < axes.size(); ++i) {
const auto& axis = axes[i];
if (src_def.HasAxis(axis) && !src_def.SupportsZeroClamp(axis, gpu_info) &&
block_size[i] != 1) {
if (!check.empty()) {
check += " && ";
}
check += names[i] + coords[i];
}
}
return check;
};
c += "MAIN_FUNCTION($0) {\n";
if (op_def.IsBatchSupported()) {
c += " int linear_id = GLOBAL_ID_0;\n";
c += " int dst_x = (linear_id / args.dst_tensor.Batch());\n";
c += " int B = linear_id % args.dst_tensor.Batch();\n";
c += " args.dst_tensor.SetBatchRef(B);\n";
c += " args.src_tensor.SetBatchRef(B);\n";
} else {
c += " int dst_x = GLOBAL_ID_0;\n";
}
c += " int rem_x = dst_x % args.stride_x;\n";
c += " int ceil_x = dst_x / args.stride_x;\n";
c += " dst_x = ceil_x * args.stride_x * " + std::to_string(block_size.x) +
" + rem_x;\n";
if (src_def.HasAxis(Axis::DEPTH)) {
c += " int linear_id_y = GLOBAL_ID_1;\n";
c += " int dst_y = linear_id_y % args.grid_size_y;\n";
c += " int dst_z = linear_id_y / args.grid_size_y;\n";
c += " int rem_z = dst_z % args.stride_z;\n";
c += " int ceil_z = dst_z / args.stride_z;\n";
c += " dst_z = ceil_z * args.stride_z * " + std::to_string(block_size.z) +
" + rem_z;\n";
c += " if (dst_z >= args.dst_tensor.Depth()) return;\n";
} else {
c += " int dst_y = GLOBAL_ID_1;\n";
}
c += " int rem_y = dst_y % args.stride_y;\n";
c += " int ceil_y = dst_y / args.stride_y;\n";
c += " dst_y = ceil_y * args.stride_y * " + std::to_string(block_size.y) +
" + rem_y;\n";
c += " int dst_s = GLOBAL_ID_2 * " + std::to_string(block_size.w) + ";\n";
c += " if (dst_x >= args.dst_tensor.Width() || dst_y >= "
"args.dst_tensor.Height() || dst_s >= "
"args.dst_tensor.Slices()) return;\n";
if (weights_are_buffer) {
c += " int f_base = dst_s * args.src_tensor.Slices() * args.kernel_size_x "
"* args.kernel_size_y";
if (src_def.HasAxis(Axis::DEPTH)) {
c += " * args.kernel_size_z";
}
c += " * 4;\n";
}
for (int s = 0; s < block_size.w; ++s) {
const std::string sind = std::to_string(s);
for (int z = 0; z < block_size.z; ++z) {
const std::string zind = std::to_string(z);
for (int y = 0; y < block_size.y; ++y) {
const std::string yind = std::to_string(y);
for (int x = 0; x < block_size.x; ++x) {
const std::string xind = std::to_string(x);
c += " ACCUM_FLT4 r" + generate_id_full(xind, yind, zind, sind) +
" = INIT_ACCUM_FLT4(0.0f);\n";
}
}
}
}
c += " int kernel_first_dst_x = dst_x + args.padding_x;\n";
c += " int kernel_first_dst_y = dst_y + args.padding_y;\n";
c += " int kernel_last_dst_x = kernel_first_dst_x - args.kernel_size_x;\n";
c += " int kernel_last_dst_y = kernel_first_dst_y - args.kernel_size_y;\n";
c += " int offset_x = abs(args.padding_x);\n";
c += " int offset_x_strided = offset_x * args.stride_x;\n";
c +=
" int src_x = (kernel_first_dst_x + offset_x_strided) / args.stride_x - "
"offset_x;\n";
c += " int offset_y = abs(args.padding_y);\n";
c += " int offset_y_strided = offset_y * args.stride_y;\n";
c +=
" int src_y = (kernel_first_dst_y + offset_y_strided) / args.stride_y - "
"offset_y;\n";
if (src_def.HasAxis(Axis::DEPTH)) {
c += " int kernel_first_dst_z = dst_z + args.padding_z;\n";
c += " int kernel_last_dst_z = kernel_first_dst_z - args.kernel_size_z;\n";
c += " int offset_z = abs(args.padding_z);\n";
c += " int offset_z_strided = offset_z * args.stride_z;\n";
c += " int src_z = (kernel_first_dst_z + offset_z_strided) / "
"args.stride_z - offset_z;\n";
c += " int src_as_dst_z = src_z * args.stride_z;\n";
c +=
" for (;src_as_dst_z > kernel_last_dst_z; src_z -= 1, src_as_dst_z -= "
"args.stride_z) {\n";
for (int z = 0; z < block_size.z; ++z) {
const std::string zindex = std::to_string(z);
c += " int sz" + zindex + " = src_z + " + zindex + ";\n";
if (!src_def.SupportsZeroClamp(Axis::DEPTH, gpu_info)) {
c += " bool in_z" + zindex + " = sz" + zindex + " >= 0 && sz" +
zindex + " < args.src_tensor.Depth();\n";
if (!src_def.CanReadOutOfBorder(Axis::DEPTH)) {
c += " sz" + zindex + " = clamp(sz" + zindex +
", 0, args.src_tensor.Depth() - 1);\n";
}
}
}
if (block_size.z == 1 &&
!src_def.SupportsZeroClamp(Axis::DEPTH, gpu_info)) {
c += " if (!in_z0) continue;\n";
}
c += " int kernel_z = kernel_first_dst_z - src_as_dst_z;\n";
c += " int src_as_dst_y = src_y * args.stride_y;\n";
c += " int src_y_copy = src_y;\n";
c += " for (;src_as_dst_y > kernel_last_dst_y; src_y_copy -= 1, "
"src_as_dst_y -= args.stride_y) {\n";
} else {
c += " int src_as_dst_y = src_y * args.stride_y;\n";
c += " for (;src_as_dst_y > kernel_last_dst_y; src_y -= 1, src_as_dst_y "
"-= args.stride_y) {\n";
}
for (int y = 0; y < block_size.y; ++y) {
const std::string yindex = std::to_string(y);
const std::string src_y =
src_def.HasAxis(Axis::DEPTH) ? "src_y_copy" : "src_y";
c += " int sy" + yindex + " = " + src_y + " + " + yindex + ";\n";
if (!src_def.SupportsZeroClamp(Axis::HEIGHT, gpu_info)) {
c += " bool in_y" + yindex + " = sy" + yindex + " >= 0 && sy" +
yindex + " < args.src_tensor.Height();\n";
if (!src_def.CanReadOutOfBorder(Axis::HEIGHT)) {
c += " sy" + yindex + " = clamp(sy" + yindex +
", 0, args.src_tensor.Height() - 1);\n";
}
}
}
if (block_size.y == 1 && !src_def.SupportsZeroClamp(Axis::HEIGHT, gpu_info)) {
c += " if (!in_y0) continue;\n";
}
c += " int kernel_y = kernel_first_dst_y - src_as_dst_y;\n";
c += " int src_as_dst_x = src_x * args.stride_x;\n";
c += " int src_x_copy = src_x;\n";
c += " for (;src_as_dst_x > kernel_last_dst_x; src_x_copy -= 1, "
"src_as_dst_x "
"-= args.stride_x) {\n";
for (int x = 0; x < block_size.x; ++x) {
const std::string xindex = std::to_string(x);
c += " int sx" + xindex + " = src_x_copy + " + xindex + ";\n";
if (!src_def.SupportsZeroClamp(Axis::WIDTH, gpu_info)) {
c += " bool in_x" + xindex + " = sx" + xindex + " >= 0 && sx" +
xindex + " < args.src_tensor.Width();\n";
if (!src_def.CanReadOutOfBorder(Axis::WIDTH)) {
c += " sx" + xindex + " = clamp(sx" + xindex +
", 0, args.src_tensor.Width() - 1);\n";
}
}
}
if (block_size.x == 1 && !src_def.SupportsZeroClamp(Axis::WIDTH, gpu_info)) {
c += " if (!in_x0) continue;\n";
}
for (int z = 0; z < block_size.z; ++z) {
const std::string zind = std::to_string(z);
for (int y = 0; y < block_size.y; ++y) {
const std::string yind = std::to_string(y);
for (int x = 0; x < block_size.x; ++x) {
const std::string xind = std::to_string(x);
const std::string id = generate_id(xind, yind, zind);
const std::string check = generate_check(xind, yind, zind);
std::string coords = "sx" + xind + ", sy" + yind;
if (src_def.HasAxis(Axis::DEPTH)) {
coords += ", sz" + zind;
}
if (src_def.IsLinear()) {
c += " int addr" + id + " = args.src_tensor.GetAddress(" +
coords + ", 0);\n";
if (src_def.ReturnsZeroForNegOneRead(gpu_info)) {
c += " addr" + id + " = select(-1, addr" + id + ", (" + check +
"));\n";
c += " int ds" + id +
" = select(0, args.src_tensor.SliceStride(), (" + check +
"));\n";
}
}
}
}
}
if (src_def.IsLinear() && !src_def.ReturnsZeroForNegOneRead(gpu_info)) {
c += " int ds = args.src_tensor.SliceStride();\n";
}
c += " int kernel_x = kernel_first_dst_x - src_as_dst_x;\n";
if (src_def.HasAxis(Axis::DEPTH)) {
c += " int kernel_index = (kernel_z * args.kernel_size_y + kernel_y) "
"* args.kernel_size_x + kernel_x;\n";
} else {
c += " int kernel_index = kernel_y * args.kernel_size_x + kernel_x;\n";
}
if (weights_are_buffer) {
c += " int f_offset = f_base + kernel_index * "
"args.src_tensor.Slices() * " +
std::to_string(block_size.w * 4) + ";\n";
} else {
c += " int x_c = kernel_index * args.src_tensor.Slices();\n";
}
c += " for (int s = 0; s < args.src_tensor.Slices(); ++s) {\n";
const bool conditional_read = gpu_info.IsMali();
for (int z = 0; z < block_size.z; ++z) {
const std::string zind = std::to_string(z);
for (int y = 0; y < block_size.y; ++y) {
const std::string yind = std::to_string(y);
for (int x = 0; x < block_size.x; ++x) {
const std::string xind = std::to_string(x);
const std::string id = generate_id(xind, yind, zind);
std::string address;
if (src_def.IsLinear()) {
address = "addr" + id;
} else {
address = "sx" + xind + ", sy" + yind;
if (src_def.HasAxis(Axis::DEPTH)) {
address += ", sz" + zind;
}
address += ", s";
}
if (src_def.ReturnsZeroForNegOneRead(gpu_info)) {
c += " FLT4 src" + id + " = args.src_tensor.Read(" + address +
"); " + address + " += ds" + id + ";\n";
} else {
const std::string check = generate_check(xind, yind, zind);
if (!check.empty()) {
if (conditional_read) {
c += " FLT4 src" + id + " = " + check +
" ? args.src_tensor.Read(" + address +
") : INIT_FLT4(0.0f);\n";
} else {
c += " FLT4 src" + id + " = args.src_tensor.Read(" +
address + ") * INIT_FLT(" + check + ");\n";
}
} else {
c += " FLT4 src" + id + " = args.src_tensor.Read(" +
address + ");\n";
}
if (src_def.IsLinear()) {
c += " addr" + id + " += ds;\n";
}
}
}
}
}
if (weights_are_buffer) {
if (gpu_info.SupportsPointersInKernels()) {
c += " __global FLT4* weights_cache = "
"args.weights.GetPtr(f_offset);\n";
}
} else {
for (int s = 0; s < block_size.w; ++s) {
c += absl::Substitute(
R"( FLT4 f$1 = args.weights0.Read(dst_s + $0, x_c);
FLT4 f$2 = args.weights1.Read(dst_s + $0, x_c);
FLT4 f$3 = args.weights2.Read(dst_s + $0, x_c);
FLT4 f$4 = args.weights3.Read(dst_s + $0, x_c);
)",
s, s * 4 + 0, s * 4 + 1, s * 4 + 2, s * 4 + 3);
}
c += " x_c++;\n";
}
if (weights_are_buffer && !gpu_info.SupportsPointersInKernels()) {
c += " FLT4 f0, f1, f2, f3;\n";
}
for (int s = 0; s < block_size.w; ++s) {
if (weights_are_buffer && !gpu_info.SupportsPointersInKernels()) {
c += " f0 = args.weights.Read(f_offset + " +
std::to_string(s * 4 + 0) + ");\n";
c += " f1 = args.weights.Read(f_offset + " +
std::to_string(s * 4 + 1) + ");\n";
c += " f2 = args.weights.Read(f_offset + " +
std::to_string(s * 4 + 2) + ");\n";
c += " f3 = args.weights.Read(f_offset + " +
std::to_string(s * 4 + 3) + ");\n";
}
const std::string sind = std::to_string(s);
for (int z = 0; z < block_size.z; ++z) {
const std::string zind = std::to_string(z);
for (int y = 0; y < block_size.y; ++y) {
const std::string yind = std::to_string(y);
for (int x = 0; x < block_size.x; ++x) {
const std::string xind = std::to_string(x);
const std::string id = generate_id(xind, yind, zind);
const std::string full_id = generate_id_full(xind, yind, zind, sind);
c += " CONV" + sind + "(r" + full_id + ", src" + id + ");\n";
}
}
}
}
if (weights_are_buffer) {
c += " f_offset += " + std::to_string(block_size.w * 4) + ";\n";
}
c += " }\n";
c += " }\n";
c += " }\n";
if (src_def.HasAxis(Axis::DEPTH)) {
c += " }\n";
}
for (int s = 0; s < block_size.w; ++s) {
const std::string sind = std::to_string(s);
c += " if (dst_s < args.dst_tensor.Slices()) {\n";
c += " FLT4 bias_val = args.biases.Read(dst_s);\n";
for (int z = 0; z < block_size.z; ++z) {
const std::string zind = std::to_string(z);
for (int y = 0; y < block_size.y; ++y) {
const std::string yind = std::to_string(y);
for (int x = 0; x < block_size.x; ++x) {
const std::string xind = std::to_string(x);
const std::string id = generate_id_full(xind, yind, zind, sind);
std::string checks =
"xc < args.dst_tensor.Width() && yc < args.dst_tensor.Height()";
std::string coords = "xc, yc";
c += " {\n";
c += " int xc = dst_x + args.stride_x * " + xind + ";\n";
c += " int yc = dst_y + args.stride_y * " + yind + ";\n";
if (src_def.HasAxis(Axis::DEPTH)) {
c += " int zc = dst_z + args.stride_z * " + zind + ";\n";
checks += " && zc < args.dst_tensor.Depth()";
coords += ", zc";
}
c += " if (" + checks + ") {\n";
c += " FLT4 res = TO_FLT4(r" + id + ") + bias_val;\n";
c += " args.dst_tensor.Write(res, " + coords + ", dst_s);\n";
c += " }\n";
c += " }\n";
}
}
}
c += " }\n";
c += " dst_s++;\n";
}
c += "}\n";
return c;
}
absl::Status ConvolutionTransposed::BindArguments(ArgumentsBinder* args) {
if (definition_.src_tensors[0].HasAxis(Axis::DEPTH)) {
const int aligned_h =
AlignByN(dst_[0]->Height(), stride_.y * block_size_.y);
RETURN_IF_ERROR(
args->SetInt("grid_size_y", DivideRoundUp(aligned_h, block_size_.y)));
}
return absl::OkStatus();
}
int3 ConvolutionTransposed::GetGridSize() const {
const int aligned_w = AlignByN(dst_[0]->Width(), stride_.x * block_size_.x);
const int aligned_h = AlignByN(dst_[0]->Height(), stride_.y * block_size_.y);
const int aligned_d = AlignByN(dst_[0]->Depth(), stride_.z * block_size_.z);
const int grid_x = DivideRoundUp(aligned_w, block_size_.x) * dst_[0]->Batch();
const int grid_y = DivideRoundUp(aligned_h, block_size_.y) *
DivideRoundUp(aligned_d, block_size_.z);
const int grid_z = DivideRoundUp(dst_[0]->Slices(), block_size_.w);
return int3(grid_x, grid_y, grid_z);
}
void ConvolutionTransposed::GetPossibleKernelWorkGroups(
TuningType tuning_type, const GpuInfo& gpu_info,
const KernelInfo& kernel_info, std::vector<int3>* work_groups) const {
GetPossibleWorkGroupsConv(tuning_type, gpu_info, kernel_info, grid_size_,
work_groups);
}
ConvolutionTransposed CreateConvolutionTransposed(
const GpuInfo& gpu_info, const OperationDef& definition,
const ConvolutionTransposedAttributes& attr) {
ConvolutionTransposed result(definition, attr, gpu_info);
result.UploadWeights(attr.weights, UseBufferForWeights(gpu_info));
TensorDescriptor bias_tensor_desc = CreateConstantLinearTensorDescriptor(
gpu_info, definition.src_tensors[0].GetDataType(), attr.bias);
result.args_.AddObject("biases", std::make_unique<TensorDescriptor>(
std::move(bias_tensor_desc)));
return result;
}
ConvolutionTransposed CreateConvolutionTransposed3D(
const GpuInfo& gpu_info, const OperationDef& definition,
const ConvolutionTransposed3DAttributes& attr) {
ConvolutionTransposed result(definition, attr, gpu_info);
result.UploadWeights(attr.weights, UseBufferForWeights(gpu_info));
TensorDescriptor bias_tensor_desc = CreateConstantLinearTensorDescriptor(
gpu_info, definition.src_tensors[0].GetDataType(), attr.bias);
result.args_.AddObject("biases", std::make_unique<TensorDescriptor>(
std::move(bias_tensor_desc)));
return result;
}
ConvolutionTransposed CreateConvolutionTransposedDynamicWeights(
const GpuInfo& gpu_info, const OperationDef& definition,
const ConvolutionTransposedAttributes& attr) {
OperationDef new_def = definition;
new_def.src_tensors = {
definition.src_tensors[0]};
const DataType weights_type = definition.GetDataType();
if (UseBufferForWeights(gpu_info)) {
new_def.src_tensors.push_back(
{weights_type, TensorStorageType::BUFFER, Layout::HWC});
} else {
new_def.src_tensors.push_back(
{weights_type, TensorStorageType::TEXTURE_2D, Layout::HW});
new_def.src_tensors.push_back(
{weights_type, TensorStorageType::TEXTURE_2D, Layout::HW});
new_def.src_tensors.push_back(
{weights_type, TensorStorageType::TEXTURE_2D, Layout::HW});
new_def.src_tensors.push_back(
{weights_type, TensorStorageType::TEXTURE_2D, Layout::HW});
}
ConvolutionTransposed result(new_def, attr, gpu_info);
TensorDescriptor bias_tensor_desc = CreateConstantLinearTensorDescriptor(
gpu_info, definition.src_tensors[0].GetDataType(), attr.bias);
result.args_.AddObject("biases", std::make_unique<TensorDescriptor>(
std::move(bias_tensor_desc)));
return result;
}
}
} | #include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/delegates/gpu/cl/kernels/cl_test.h"
#include "tensorflow/lite/delegates/gpu/common/operations.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/tasks/convolution_transposed_test_util.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
TEST_F(OpenCLOperationTest, ConvolutionTransposedSimpleWeights) {
auto status = ConvolutionTransposedSimpleWeightsTest(&exec_env_);
ASSERT_TRUE(status.ok()) << status.message();
}
TEST_F(OpenCLOperationTest, ConvolutionTransposed) {
auto status = ConvolutionTransposedTest(&exec_env_);
ASSERT_TRUE(status.ok()) << status.message();
}
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/common/tasks/convolution_transposed.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/cl/kernels/convolution_transposed_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
fb36523d-3c6a-4c05-8511-c90aa28acc00 | cpp | tensorflow/tensorflow | resolve_svdf | tensorflow/lite/toco/tensorflow_graph_matching/resolve_svdf.cc | tensorflow/lite/toco/tensorflow_graph_matching/resolve_svdf_test.cc | #include "tensorflow/lite/toco/tensorflow_graph_matching/resolve_svdf.h"
#include <ctype.h>
#include <stddef.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/toco/tensorflow_graph_matching/cluster.h"
#include "tensorflow/lite/toco/tensorflow_graph_matching/cluster_utils.h"
#include "tensorflow/lite/toco/toco_port.h"
#include "tensorflow/lite/toco/toco_types.h"
using tensorflow::GraphDef;
using tensorflow::NodeDef;
namespace toco {
namespace {
void FilterPartitionedConstNodes(
const std::string& const_pattern,
const std::vector<const NodeDef*>& cluster_nodes,
std::vector<const NodeDef*>* const_node_parts) {
for (const NodeDef* node : cluster_nodes) {
std::string node_name_to_upper = node->name();
std::transform(node_name_to_upper.begin(), node_name_to_upper.end(),
node_name_to_upper.begin(), ::toupper);
if (StrContains(node->name(), const_pattern) && node->op() == "Const") {
if (StrContains(node_name_to_upper, "/PART_")) {
const_node_parts->push_back(node);
} else if (StrContains(node->name(), "AXIS") &&
StrContains(node->name(), "CONCAT")) {
const auto& value_attr = node->attr().at("value");
const tensorflow::TensorProto& tensor = value_attr.tensor();
CHECK_EQ(tensor.int_val(0), 0);
}
}
}
std::sort(const_node_parts->begin(), const_node_parts->end(),
[](const NodeDef* a, const NodeDef* b) {
return (a->name().compare(b->name()) < 0 &&
(a->name().size() < b->name().size()));
});
}
}
int SvdfCluster::InferFilterRank() {
for (const NodeDef* node : nodes_) {
if (StrContains(node->name(), "Reshape/shape")) {
const auto& value_attr = node->attr().at("value");
const tensorflow::TensorProto& tensor = value_attr.tensor();
std::vector<int32> shape_values(
tensor.tensor_content().size() / sizeof(int), 0);
port::CopyToBuffer(tensor.tensor_content(),
reinterpret_cast<char*>(shape_values.data()));
CHECK_EQ(shape_values.size(), 3);
CHECK_EQ(shape_values[2], -1);
return shape_values[1];
}
}
return -1;
}
void SvdfCluster::CreateNodes() {
for (const std::string& const_pattern : const_node_patterns_) {
CreateConstNode(const_pattern);
}
std::unique_ptr<tensorflow::NodeDef> svdf_node(new NodeDef);
svdf_node->set_op("Svdf");
svdf_node->set_name(name_);
svdf_node->set_device(device_);
svdf_node->add_input(inputs_[0]);
CHECK(new_nodes_.size() == 3 || new_nodes_.size() == 2);
std::string* weights_feature_input = svdf_node->add_input();
std::string* weights_time_input = svdf_node->add_input();
std::string* bias_input;
if (new_nodes_.size() == 3) {
bias_input = svdf_node->add_input();
}
for (const std::unique_ptr<tensorflow::NodeDef>& node : new_nodes_) {
const std::string node_name = node->name();
if (StrContains(node_name, "SVDF_weights_feature")) {
*weights_feature_input = node_name;
} else if (StrContains(node_name, "SVDF_weights_time")) {
*weights_time_input = node_name;
} else if (StrContains(node_name, "SVDF_bias")) {
CHECK(bias_input) << "Bias input cannot be provided when there are only "
"two Const input nodes!";
*bias_input = node_name;
} else {
LOG(FATAL) << "Unexpected input node for SVDF op! Accepted inputs are: "
"weights_feature, weights_time and bias.";
}
}
const int rank = InferFilterRank();
CHECK_GT(rank, 0);
std::string activation_function =
StrContains(outputs_[0], "Relu") ? "Relu" : "None";
(*svdf_node->mutable_attr())["ActivationFunction"].set_s(activation_function);
(*svdf_node->mutable_attr())["Rank"].set_i(rank);
new_nodes_.push_back(std::move(svdf_node));
}
void SvdfCluster::CreateConstNode(const std::string& const_pattern) {
std::vector<const NodeDef*> const_node_parts;
FilterPartitionedConstNodes(const_pattern, nodes_, &const_node_parts);
if (const_node_parts.empty()) return;
bool transpose_tensor_value =
StrContains(const_pattern, "SVDF_weights_feature");
std::unique_ptr<tensorflow::NodeDef> merged_node(new NodeDef);
MaybeMergeConstNodes(const_node_parts, transpose_tensor_value, merged_node);
new_nodes_.push_back(std::move(merged_node));
}
void SvdfCluster::MaybeMergeConstNodes(
const std::vector<const NodeDef*>& const_node_parts,
bool transpose_tensor_value,
const std::unique_ptr<tensorflow::NodeDef>& merged_node) {
merged_node->set_name(const_node_parts[0]->name());
merged_node->set_op("Const");
merged_node->set_device(const_node_parts[0]->device());
(*merged_node->mutable_attr())["dtype"].set_type(
const_node_parts[0]->attr().at("dtype").type());
int dim0_size = 0;
int dim1_size = 1;
tensorflow::TensorProto* allocated_tensor =
(*merged_node->mutable_attr())["value"].mutable_tensor();
tensorflow::TensorShapeProto* allocated_tensor_shape =
allocated_tensor->mutable_tensor_shape();
auto tensor_shape_dim0 = allocated_tensor_shape->add_dim();
int allocated_content_flat_size = 0;
for (size_t i = 0; i < const_node_parts.size(); i++) {
const auto& value_attr = const_node_parts[i]->attr().at("value");
const tensorflow::TensorProto& tensor = value_attr.tensor();
if (i == 0) {
allocated_tensor->set_dtype(tensor.dtype());
} else {
CHECK_EQ(allocated_tensor->dtype(), tensor.dtype());
}
allocated_content_flat_size += tensor.tensor_content().size();
CHECK(tensor.has_tensor_shape());
const tensorflow::TensorShapeProto shape = tensor.tensor_shape();
dim0_size += shape.dim(0).size();
for (int d = 1; d < shape.dim_size(); d++) {
if (i == 0) {
allocated_tensor_shape->add_dim()->set_size(shape.dim(d).size());
allocated_tensor_shape->set_unknown_rank(shape.unknown_rank());
dim1_size *= shape.dim(d).size();
} else {
CHECK_EQ(shape.dim(d).size(), allocated_tensor_shape->dim(d).size());
CHECK_EQ(allocated_tensor_shape->unknown_rank(), shape.unknown_rank());
}
}
}
std::unique_ptr<char[]> allocated_content(
new char[allocated_content_flat_size]);
char* content_ptr = allocated_content.get();
for (size_t i = 0; i < const_node_parts.size(); i++) {
const auto& value_attr = const_node_parts[i]->attr().at("value");
const tensorflow::TensorProto& tensor = value_attr.tensor();
port::CopyToBuffer(tensor.tensor_content(), content_ptr);
content_ptr += tensor.tensor_content().size();
}
if (transpose_tensor_value) {
std::unique_ptr<float[]> transposed_tensor(
new float[dim0_size * dim1_size]);
Transpose2DTensor(reinterpret_cast<float*>(allocated_content.get()),
dim0_size, dim1_size, transposed_tensor.get());
allocated_tensor_shape->clear_dim();
allocated_tensor_shape->add_dim()->set_size(dim1_size);
allocated_tensor_shape->add_dim()->set_size(dim0_size);
allocated_tensor->set_tensor_content(
std::string(reinterpret_cast<const char*>(transposed_tensor.get()),
allocated_content_flat_size));
} else {
tensor_shape_dim0->set_size(dim0_size);
allocated_tensor->set_tensor_content(
std::string(reinterpret_cast<const char*>(allocated_content.get()),
allocated_content_flat_size));
}
}
std::unique_ptr<Cluster> SvdfClusterFactory::CreateCluster(
const NodeDef& node, const GraphDef& graph_def) const {
std::vector<std::string> node_patterns = {"SVDF_weights_feature",
"SVDF_weights_time", "SVDF_bias"};
std::string node_name_to_upper = node.name();
std::transform(node_name_to_upper.begin(), node_name_to_upper.end(),
node_name_to_upper.begin(), ::toupper);
std::unique_ptr<SvdfCluster> cluster = nullptr;
if (node_name_to_upper.find("SVDF", 0) != std::string::npos) {
size_t weights_pos = node.name().find(node_patterns[0]);
if (weights_pos != std::string::npos) {
size_t cell_pos = node.name().rfind('/', weights_pos - 2) + 1;
std::string cell_name =
node.name().substr(cell_pos, weights_pos - cell_pos - 1);
cluster = std::make_unique<SvdfCluster>();
cluster->SetName(cell_name);
cluster->SetDevice(node.device());
cluster->SetGraphDefInfo(&graph_def);
CHECK(cluster->FindClusterInputsAndOutputs());
for (const std::string& const_pattern : node_patterns) {
cluster->AddConstNodePattern(const_pattern);
}
}
}
return std::move(cluster);
}
} | #include "tensorflow/lite/toco/tensorflow_graph_matching/resolve_svdf.h"
#include <string>
#include <unordered_map>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/toco/tensorflow_graph_matching/cluster.h"
#include "tensorflow/lite/toco/tensorflow_graph_matching/cluster_utils.h"
#include "tensorflow/lite/toco/tensorflow_graph_matching/resolve_cluster.h"
#include "tensorflow/lite/toco/toco_port.h"
using tensorflow::GraphDef;
using tensorflow::NodeDef;
namespace toco {
class ResolveSvdfTest : public ::testing::Test {
public:
ResolveSvdfTest() {
AddNewNode("Input1", "Const", {});
AddNewNode("Svdf1/SVDF_weights_feature/part_0", "Const", {},
{0.1, 0.2, 0.3});
AddNewNode("Svdf1/SVDF_weights_feature/part_0/read", "Identity",
{"Svdf1/SVDF_weights_feature/part_0"});
AddNewNode("Svdf1/SVDF_weights_time/part_0", "Const", {}, {0.1, 0.2, 0.3});
AddNewNode("Svdf1/SVDF_weights_time/part_0/read", "Identity",
{"Svdf1/SVDF_weights_time/part_0"});
AddNewNode("Svdf1/f1", "SVDF_F1",
{"Input1", "Svdf1/SVDF_weights_feature/part_0/read"});
AddNewNode("Svdf1/f2", "SVDF_F2",
{"Svdf1/SVDF_weights_time/part_0/read", "Svdf1/f1"});
AddNewNode("Svdf1/Relu", "Relu", {"Svdf1/f2"});
AddShapeNode("Svdf1/Reshape/shape", {10, 1, -1});
AddNewNode("Output1", "Const", {"Svdf1/Relu"});
AddNewNode("Input2", "Const", {});
AddNewNode("Svdf2/SVDF_weights_feature/part_0", "Const", {},
{0.1, 0.2, 0.3});
AddNewNode("Svdf2/SVDF_weights_feature/part_0/read", "Identity",
{"Svdf2/SVDF_weights_feature/part_0"});
AddNewNode("Svdf2/SVDF_weights_time/part_0", "Const", {}, {0.1, 0.2, 0.3});
AddNewNode("Svdf2/SVDF_weights_time/part_0/read", "Identity",
{"Svdf2/SVDF_weights_time/part_0"});
AddNewNode("Svdf2/f1", "SVDF_F1",
{"Input1", "Svdf2/SVDF_weights_feature/part_0/read"});
AddNewNode("Svdf2/f2", "SVDF_F2",
{"Svdf2/SVDF_weights_time/part_0/read", "Svdf2/f1"});
AddNewNode("Svdf2/Relu", "Relu", {"Svdf2/f2"});
AddShapeNode("Svdf2/Reshape/shape", {10, 2, -1});
AddNewNode("Output2", "Const", {"Svdf2/Relu"});
}
~ResolveSvdfTest() override {}
protected:
void AddNewNode(const std::string& name, const std::string& op,
const std::vector<std::string>& inputs) {
NodeDef* node = graph_.add_node();
node->set_name(name);
node->set_op(op);
node->set_device("");
for (int i = 0; i < inputs.size(); i++) {
node->add_input();
node->set_input(i, inputs[i]);
}
}
void AddNewNode(const std::string& name, const std::string& op,
const std::vector<std::string>& inputs,
const std::vector<float>& values) {
NodeDef* node = graph_.add_node();
node->set_name(name);
node->set_op(op);
node->set_device("");
for (int i = 0; i < inputs.size(); i++) {
node->add_input();
node->set_input(i, inputs[i]);
}
(*node->mutable_attr())["dtype"].set_type(tensorflow::DT_FLOAT);
tensorflow::TensorProto* allocated_tensor = new tensorflow::TensorProto;
tensorflow::TensorShapeProto* allocated_tensor_shape =
new tensorflow::TensorShapeProto;
auto tensor_shape_dim0 = allocated_tensor_shape->add_dim();
tensor_shape_dim0->set_size(values.size());
allocated_tensor->set_allocated_tensor_shape(allocated_tensor_shape);
allocated_tensor->set_tensor_content(
std::string(reinterpret_cast<const char*>(values.data()),
values.size() * sizeof(float)));
(*node->mutable_attr())["value"].set_allocated_tensor(allocated_tensor);
}
void AddShapeNode(const std::string& name, const std::vector<int>& values) {
NodeDef* node = graph_.add_node();
node->set_name(name);
node->set_op("Const");
node->set_device("");
(*node->mutable_attr())["dtype"].set_type(tensorflow::DT_INT32);
tensorflow::TensorProto* allocated_tensor = new tensorflow::TensorProto;
tensorflow::TensorShapeProto* allocated_tensor_shape =
new tensorflow::TensorShapeProto;
auto tensor_shape_dim0 = allocated_tensor_shape->add_dim();
tensor_shape_dim0->set_size(values.size());
allocated_tensor->set_allocated_tensor_shape(allocated_tensor_shape);
allocated_tensor->set_tensor_content(
std::string(reinterpret_cast<const char*>(values.data()),
values.size() * sizeof(int)));
(*node->mutable_attr())["value"].set_allocated_tensor(allocated_tensor);
}
GraphDef graph_;
SvdfClusterFactory svdf_cluster_factory_;
std::vector<std::unique_ptr<Cluster>> clusters_;
};
TEST_F(ResolveSvdfTest, TestTranspose2DTensor) {
static float matrix[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.};
static float expected_transposed_matrix[] = {1., 5., 9., 2., 6., 10.,
3., 7., 11., 4., 8., 12.};
float* transposed_matrix = new float[12];
Transpose2DTensor(matrix, 3, 4, transposed_matrix);
std::vector<float> actual;
actual.insert(
actual.end(), transposed_matrix,
transposed_matrix + sizeof(expected_transposed_matrix) / sizeof(float));
std::vector<float> expected;
expected.insert(expected.end(), expected_transposed_matrix,
expected_transposed_matrix +
sizeof(expected_transposed_matrix) / sizeof(float));
delete[] transposed_matrix;
}
TEST_F(ResolveSvdfTest, TestResolveSvdfFlow) {
std::unordered_map<std::string, bool> is_node_in_cluster;
for (const NodeDef& node : graph_.node()) {
is_node_in_cluster[node.name()] = false;
}
std::vector<std::string> cluster_names;
CHECK(FindCluster(svdf_cluster_factory_, graph_, &is_node_in_cluster,
&clusters_));
for (const std::unique_ptr<Cluster>& cluster : clusters_) {
cluster_names.push_back(cluster->GetName());
cluster->CreateNodes();
}
EXPECT_THAT(cluster_names,
testing::UnorderedElementsAreArray({"Svdf1", "Svdf2"}));
std::vector<std::string> new_node_names;
std::vector<float> content_array(3);
for (const std::unique_ptr<Cluster>& cluster : clusters_) {
CHECK_EQ(cluster->GetNewNodes().size(), 3);
for (const std::unique_ptr<tensorflow::NodeDef>& node :
cluster->GetNewNodes()) {
new_node_names.push_back(node->name());
if (node->op() == "Const") {
CHECK_EQ(node->attr().at("dtype").type(), tensorflow::DT_FLOAT);
toco::port::CopyToBuffer(
node->attr().at("value").tensor().tensor_content(),
reinterpret_cast<char*>(content_array.data()));
EXPECT_THAT(content_array,
testing::UnorderedElementsAreArray({0.1, 0.2, 0.3}));
} else {
if (node->name() == "Svdf1") {
CHECK_EQ(node->attr().at("Rank").i(), 1);
} else if (node->name() == "Svdf2") {
CHECK_EQ(node->attr().at("Rank").i(), 2);
}
CHECK_EQ(node->attr().at("ActivationFunction").s(), "Relu");
}
}
}
EXPECT_THAT(new_node_names, testing::UnorderedElementsAreArray(
{"Svdf2/SVDF_weights_feature/part_0",
"Svdf2/SVDF_weights_time/part_0", "Svdf2",
"Svdf1/SVDF_weights_feature/part_0",
"Svdf1/SVDF_weights_time/part_0", "Svdf1"}));
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/toco/tensorflow_graph_matching/resolve_svdf.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/toco/tensorflow_graph_matching/resolve_svdf_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
e65f0543-478e-4b0b-b8a2-0f371f5de206 | cpp | google/arolla | array | arolla/array/array.cc | arolla/qexpr/operators/array/array_test.cc | #include "arolla/array/array.h"
#include "absl/strings/str_cat.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/repr.h"
namespace arolla {
void FingerprintHasherTraits<ArrayShape>::operator()(
FingerprintHasher* hasher, const ArrayShape& value) const {
hasher->Combine(value.size);
}
ReprToken ReprTraits<ArrayShape>::operator()(const ArrayShape& value) const {
return ReprToken{absl::StrCat("array_shape{size=", value.size, "}")};
}
} | #include "arolla/array/array.h"
#include <optional>
#include <type_traits>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "arolla/array/edge.h"
#include "arolla/memory/frame.h"
#include "arolla/memory/optional_value.h"
#include "arolla/memory/raw_buffer_factory.h"
#include "arolla/qexpr/eval_context.h"
#include "arolla/qexpr/lift_to_optional_operator.h"
#include "arolla/qexpr/lifting.h"
#include "arolla/qexpr/operators.h"
#include "arolla/qexpr/operators/array/lifter.h"
#include "arolla/qexpr/operators/dense_array/lifter.h"
#include "arolla/qexpr/operators/testing/accumulators.h"
#include "arolla/util/meta.h"
#include "arolla/util/text.h"
#include "arolla/util/unit.h"
namespace arolla::testing {
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::testing::ElementsAre;
using ::testing::HasSubstr;
struct TemplatedAddFn {
template <typename T>
T operator()(T a, T b) const {
return a + b;
}
};
struct TemplatedAddOneFn {
template <typename T>
T operator()(T a) const {
return a + 1;
}
};
TEST(LifterTest, SimpleCase) {
Array<int> arr1 = CreateArray<int>({1, {}, 2, 3});
Array<int> arr2 = CreateArray<int>({3, 6, {}, 2});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op = ArrayPointwiseLifter<TemplatedAddFn, meta::type_list<int, int>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, arr1, arr2));
EXPECT_THAT(res, ElementsAre(4, std::nullopt, std::nullopt, 5));
}
struct LogicalOrOp {
using run_on_missing = std::true_type;
bool operator()(bool lhs, bool rhs) const { return lhs || rhs; }
OptionalValue<bool> operator()(const OptionalValue<bool>& lhs,
const OptionalValue<bool>& rhs) const {
if (lhs.present) {
return lhs.value ? true : rhs;
} else if (rhs.present) {
return rhs.value ? true : lhs;
} else {
return OptionalValue<bool>{};
}
}
};
TEST(LifterTest, OptionalBoolResultArrays) {
Array<bool> arr1 = CreateArray<bool>({true, {}, false, true, {}});
Array<bool> arr2 = CreateArray<bool>({false, true, {}, true, {}});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op =
ArrayPointwiseLifter<LogicalOrOp,
meta::type_list<::arolla::OptionalValue<bool>,
::arolla::OptionalValue<bool>>>();
ASSERT_OK_AND_ASSIGN(Array<bool> res, op(&ctx, arr1, arr2));
EXPECT_THAT(res, ElementsAre(true, true, std::nullopt, true, std::nullopt));
}
TEST(LifterTest, OptionalBoolResultArrayAndConst) {
Array<bool> arr1 = Array<bool>(5, std::nullopt);
Array<bool> arr2 = CreateArray<bool>({false, true, {}, true, {}});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op =
ArrayPointwiseLifter<LogicalOrOp,
meta::type_list<::arolla::OptionalValue<bool>,
::arolla::OptionalValue<bool>>>();
ASSERT_OK_AND_ASSIGN(Array<bool> res, op(&ctx, arr1, arr2));
EXPECT_THAT(
res, ElementsAre(std::nullopt, true, std::nullopt, true, std::nullopt));
}
TEST(LifterTest, OptionalBoolResultConstAndConst) {
std::vector<OptionalValue<bool>> cases = {std::nullopt, true, false};
for (OptionalValue<bool> x : cases) {
for (OptionalValue<bool> y : cases) {
Array<bool> arr1 = Array<bool>(1, x);
Array<bool> arr2 = Array<bool>(1, y);
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op = ArrayPointwiseLifter<
LogicalOrOp, meta::type_list<::arolla::OptionalValue<bool>,
::arolla::OptionalValue<bool>>>();
ASSERT_OK_AND_ASSIGN(Array<bool> res, op(&ctx, arr1, arr2));
EXPECT_THAT(res, ElementsAre(LogicalOrOp()(x, y))) << x << " " << y;
}
}
}
TEST(LifterTest, SizeMismatch) {
Array<int> arr1 = CreateArray<int>({1, {}, 2, 3});
Array<int> arr2 = CreateArray<int>({3, 6, {}});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op = ArrayPointwiseLifter<TemplatedAddFn, meta::type_list<int, int>>();
EXPECT_THAT(op(&ctx, arr1, arr2),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("argument sizes mismatch: (4, 3)")));
}
TEST(LifterTest, UnaryOperation) {
Array<int> arr = CreateArray<int>({1, {}, 2, 3});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op = ArrayPointwiseLifter<TemplatedAddOneFn, meta::type_list<int>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, arr));
EXPECT_THAT(res, ElementsAre(2, std::nullopt, 3, 4));
}
struct MyInt {
int value;
friend int operator+(int x, MyInt y) { return y.value + x; }
};
template <typename... Ts>
struct TemplatedVariadicAddFn {
int operator()(Ts... vs) const { return (0 + ... + vs); }
};
TEST(LifterTest, NonLiftableArg) {
Array<int> arr = CreateArray<int>({1, {}, 2, 3});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op = ArrayPointwiseLifter<TemplatedVariadicAddFn<MyInt, int>,
meta::type_list<DoNotLiftTag<MyInt>, int>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, MyInt{5}, arr));
EXPECT_THAT(res, ElementsAre(6, std::nullopt, 7, 8));
}
TEST(LifterTest, NonLiftableArgs) {
Array<int> arr = CreateArray<int>({1, {}, 2, 3});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
{
auto op = ArrayPointwiseLifter<
TemplatedVariadicAddFn<MyInt, MyInt, int>,
meta::type_list<DoNotLiftTag<MyInt>, DoNotLiftTag<MyInt>, int>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, MyInt{3}, MyInt{5}, arr));
EXPECT_THAT(res, ElementsAre(9, std::nullopt, 10, 11));
}
{
auto op = ArrayPointwiseLifter<
TemplatedVariadicAddFn<MyInt, int, MyInt>,
meta::type_list<DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, MyInt{3}, arr, MyInt{5}));
EXPECT_THAT(res, ElementsAre(9, std::nullopt, 10, 11));
}
{
auto op = ArrayPointwiseLifter<
TemplatedVariadicAddFn<int, MyInt, MyInt>,
meta::type_list<int, DoNotLiftTag<MyInt>, DoNotLiftTag<MyInt>>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, arr, MyInt{3}, MyInt{5}));
EXPECT_THAT(res, ElementsAre(9, std::nullopt, 10, 11));
}
{
auto op =
ArrayPointwiseLifter<TemplatedVariadicAddFn<int, MyInt, int>,
meta::type_list<int, DoNotLiftTag<MyInt>, int>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, arr, MyInt{3}, arr));
EXPECT_THAT(res, ElementsAre(5, std::nullopt, 7, 9));
}
{
auto op = ArrayPointwiseLifter<
TemplatedVariadicAddFn<MyInt, int, MyInt, int>,
meta::type_list<DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>, int>>();
ASSERT_OK_AND_ASSIGN(Array<int> res,
op(&ctx, MyInt{5}, arr, MyInt{3}, arr));
EXPECT_THAT(res, ElementsAre(10, std::nullopt, 12, 14));
}
{
auto op = ArrayPointwiseLifter<
TemplatedVariadicAddFn<int, MyInt, int, MyInt>,
meta::type_list<int, DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>>>();
ASSERT_OK_AND_ASSIGN(Array<int> res,
op(&ctx, arr, MyInt{3}, arr, MyInt{5}));
EXPECT_THAT(res, ElementsAre(10, std::nullopt, 12, 14));
}
{
auto op = ArrayPointwiseLifter<
TemplatedVariadicAddFn<int, MyInt, int, MyInt, MyInt>,
meta::type_list<int, DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>,
DoNotLiftTag<MyInt>>>();
ASSERT_OK_AND_ASSIGN(Array<int> res,
op(&ctx, arr, MyInt{3}, arr, MyInt{5}, MyInt{4}));
EXPECT_THAT(res, ElementsAre(14, std::nullopt, 16, 18));
}
}
TEST(LifterTest, ArrayPointwiseLifterOnDenseOp) {
Array<int> arr = CreateArray<int>({1, {}, 2, 3});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op = ArrayPointwiseLifterOnDenseOp<
DenseArrayLifter<TemplatedAddFn, meta::type_list<int, int>>,
OptionalLiftedOperator<TemplatedAddFn, meta::type_list<int, int>>,
meta::type_list<int, int>>();
ASSERT_OK_AND_ASSIGN(Array<int> res, op(&ctx, arr, arr));
EXPECT_THAT(res, ElementsAre(2, std::nullopt, 4, 6));
}
TEST(LifterTest, AggTextAccumulator) {
auto values = CreateArray<Text>(
{Text("w1"), std::nullopt, Text("w3"), Text("w4"), Text("w5")});
auto comments =
CreateArray<Text>({std::nullopt, Text("it is word #2"), std::nullopt,
Text("it is word #4"), std::nullopt});
FrameLayout frame_layout;
RootEvaluationContext root_ctx(&frame_layout, GetHeapBufferFactory());
EvaluationContext ctx(root_ctx);
auto op =
ArrayGroupLifter<AggTextAccumulator, meta::type_list<OptionalValue<Text>>,
meta::type_list<Text, OptionalValue<Text>>>();
ASSERT_OK_AND_ASSIGN(Text res, op(&ctx, Text("prefix:"), values, comments,
ArrayGroupScalarEdge(values.size())));
EXPECT_EQ(res.view(), "prefix:w1\nw3\nw4 (it is word #4)\nw5\n");
}
TEST(LifterTest, ArrayPresenceAndOp) {
EXPECT_THAT(InvokeOperator<Array<int>>(
"core.presence_and", CreateArray<int>({1, 2, 3}),
CreateArray<Unit>({kUnit, std::nullopt, kUnit})),
IsOkAndHolds(ElementsAre(1, std::nullopt, 3)));
EXPECT_THAT(InvokeOperator<Array<int>>(
"core.presence_and", CreateArray<int>({1, 2, std::nullopt}),
CreateArray<Unit>({kUnit, std::nullopt, kUnit})),
IsOkAndHolds(ElementsAre(1, std::nullopt, std::nullopt)));
EXPECT_THAT(InvokeOperator<Array<int>>(
"core.presence_and", CreateArray<int>({1, 2, std::nullopt}),
CreateArray<Unit>({kUnit, kUnit, kUnit})),
IsOkAndHolds(ElementsAre(1, 2, std::nullopt)));
}
} | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/array.cc | https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/array/array_test.cc | 1ca990dbeca224035efdabffecc7f3738df6b52c |
90271454-bf3f-42dc-9c08-ea7578e1c82a | cpp | tensorflow/tensorflow | constants | tensorflow/lite/core/async/interop/c/constants.cc | third_party/xla/xla/hlo/builder/lib/constants_test.cc | #include "tensorflow/lite/core/async/interop/c/constants.h"
extern "C" {
const char kTfLiteSyncTypeNoSyncObj[] = "no_sync_obj";
} | #include "xla/hlo/builder/lib/constants.h"
#include <limits>
#include "xla/hlo/builder/xla_builder.h"
#include "xla/shape_util.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/xla_data.pb.h"
namespace xla {
namespace {
using ConstantsTest = ClientLibraryTestBase;
using ::testing::HasSubstr;
XLA_TEST_F(ConstantsTest, ConstantR0WithTypeS32) {
XlaBuilder builder(TestName());
ConstantR0WithType(&builder, xla::S32, 4);
ComputeAndCompareR0<int32_t>(&builder, 4, {});
}
XLA_TEST_F(ConstantsTest, ConstantR0WithTypeS32DoesNotAcceptFloats) {
XlaBuilder builder(TestName());
ConstantR0WithType(&builder, xla::S32, 4.5);
auto statusor = builder.Build();
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().message(), HasSubstr("Invalid cast"));
}
XLA_TEST_F(ConstantsTest, ConstantR0WithTypeF32) {
XlaBuilder builder(TestName());
ConstantR0WithType(&builder, xla::F32, -7);
ComputeAndCompareR0<float>(&builder, -7, {});
ConstantR0WithType(&builder, xla::F32, 0.5);
ComputeAndCompareR0<float>(&builder, 0.5, {});
}
XLA_TEST_F(ConstantsTest, ScalarLikeS32) {
XlaBuilder builder(TestName());
ScalarLike(ConstantR0<int32_t>(&builder, 42), -3);
ComputeAndCompareR0<int32_t>(&builder, -3, {});
}
XLA_TEST_F(ConstantsTest, ScalarLikeF32) {
XlaBuilder builder(TestName());
ScalarLike(ConstantR0<float>(&builder, 42.75), -3.2);
ComputeAndCompareR0<float>(&builder, -3.2, {});
}
XLA_TEST_F(ConstantsTest, ZeroS32) {
XlaBuilder builder(TestName());
Zero(&builder, S32);
ComputeAndCompareR0<int32_t>(&builder, 0, {});
}
XLA_TEST_F(ConstantsTest, ZeroF32) {
XlaBuilder builder(TestName());
Zero(&builder, F32);
ComputeAndCompareR0<float>(&builder, 0.0, {});
}
XLA_TEST_F(ConstantsTest, ZerosS32) {
XlaBuilder builder(TestName());
Zeros(&builder, ShapeUtil::MakeShape(S32, {2, 2}));
ComputeAndCompareR2<int32_t>(&builder, {{0, 0}, {0, 0}}, {});
}
XLA_TEST_F(ConstantsTest, ZerosLikeF32) {
XlaBuilder builder(TestName());
ZerosLike(ConstantR1<float>(&builder, {1., 2., 3.}));
ComputeAndCompareR1<float>(&builder, {0., 0., 0.}, {});
}
XLA_TEST_F(ConstantsTest, OneS32) {
XlaBuilder builder(TestName());
One(&builder, S32);
ComputeAndCompareR0<int32_t>(&builder, 1, {});
}
XLA_TEST_F(ConstantsTest, OneF32) {
XlaBuilder builder(TestName());
One(&builder, F32);
ComputeAndCompareR0<float>(&builder, 1., {});
}
XLA_TEST_F(ConstantsTest, EpsilonF32) {
XlaBuilder builder(TestName());
Epsilon(&builder, F32);
ComputeAndCompareR0<float>(&builder, std::numeric_limits<float>::epsilon(),
{});
}
XLA_TEST_F(ConstantsTest, MinFiniteValueS32) {
XlaBuilder builder(TestName());
MinFiniteValue(&builder, S32);
ComputeAndCompareR0<int32_t>(&builder, std::numeric_limits<int32_t>::min(),
{});
}
XLA_TEST_F(ConstantsTest, MaxFiniteValueS32) {
XlaBuilder builder(TestName());
MaxFiniteValue(&builder, S32);
ComputeAndCompareR0<int32_t>(&builder, std::numeric_limits<int32_t>::max(),
{});
}
XLA_TEST_F(ConstantsTest, MinFiniteValueF32) {
XlaBuilder builder(TestName());
MinFiniteValue(&builder, F32);
ComputeAndCompareR0<float>(&builder, -std::numeric_limits<float>::max(), {});
}
XLA_TEST_F(ConstantsTest, MaxFiniteValueF32) {
XlaBuilder builder(TestName());
MaxFiniteValue(&builder, F32);
ComputeAndCompareR0<float>(&builder, std::numeric_limits<float>::max(), {});
}
XLA_TEST_F(ConstantsTest, MinValueS32) {
XlaBuilder builder(TestName());
MinValue(&builder, S32);
ComputeAndCompareR0<int32_t>(&builder, std::numeric_limits<int32_t>::min(),
{});
}
XLA_TEST_F(ConstantsTest, MaxValueS32) {
XlaBuilder builder(TestName());
MaxValue(&builder, S32);
ComputeAndCompareR0<int32_t>(&builder, std::numeric_limits<int32_t>::max(),
{});
}
XLA_TEST_F(ConstantsTest, MinValueF32) {
XlaBuilder builder(TestName());
MinValue(&builder, F32);
ComputeAndCompareR0<float>(&builder, -std::numeric_limits<float>::infinity(),
{});
}
XLA_TEST_F(ConstantsTest, MaxValueF32) {
XlaBuilder builder(TestName());
MaxValue(&builder, F32);
ComputeAndCompareR0<float>(&builder, std::numeric_limits<float>::infinity(),
{});
}
XLA_TEST_F(ConstantsTest, NanValueF32) {
XlaBuilder builder(TestName());
NanValue(&builder, F32);
ComputeAndCompareR0<float>(&builder, std::numeric_limits<float>::quiet_NaN(),
{});
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/core/async/interop/c/constants.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/hlo/builder/lib/constants_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
6c55f973-6e2e-407f-b8de-4c527b9f2072 | cpp | tensorflow/tensorflow | pipelined_p2p_rewriter | third_party/xla/xla/service/gpu/transforms/pipelined_p2p_rewriter.cc | third_party/xla/xla/service/gpu/transforms/pipelined_p2p_rewriter_test.cc | #include "xla/service/gpu/transforms/pipelined_p2p_rewriter.h"
#include <cstdint>
#include <optional>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/dfs_hlo_visitor.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/hlo/ir/hlo_schedule.h"
#include "xla/hlo/utils/hlo_query.h"
#include "xla/service/collective_ops_utils.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
namespace {
using CollectiveInComputation =
absl::flat_hash_map<const HloComputation*, bool>;
using InstructionVector = HloInstruction::InstructionVector;
struct PipelinedP2PInfo {
int64_t opnd_start;
int64_t opnd_end;
};
bool IsCollectiveOp(const HloInstruction* op) {
HloOpcode opcode = op->opcode();
if (opcode == HloOpcode::kCustomCall) {
return true;
}
return hlo_query::IsCollectiveCommunicationOp(opcode) ||
opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv;
}
bool MayInvokeCollectiveOp(
const HloInstruction* hlo,
const CollectiveInComputation& collective_in_computation) {
if (IsCollectiveOp(hlo)) {
return true;
}
for (HloComputation* callee : hlo->called_computations()) {
auto collective_in_comp = collective_in_computation.find(callee);
CHECK(collective_in_comp != collective_in_computation.end());
if (collective_in_comp->second) {
return true;
}
}
return false;
}
HloInstruction* FindUniqueGTEUserWithIndex(const HloInstruction* op,
int64_t idx) {
CHECK(op->shape().IsTuple());
HloInstruction* gte = nullptr;
for (auto user : op->users()) {
if (user->opcode() != HloOpcode::kGetTupleElement) {
continue;
}
if (user->tuple_index() == idx) {
if (gte == nullptr) {
gte = user;
} else {
return nullptr;
}
}
}
return gte;
}
bool HasGTEUserWithIndex(const HloInstruction* op, int64_t idx) {
CHECK(op->shape().IsTuple());
for (auto user : op->users()) {
if (user->opcode() != HloOpcode::kGetTupleElement) {
continue;
}
if (user->tuple_index() == idx) {
return true;
}
}
return false;
}
HloInstruction* MaySkipTrivialTuple(HloInstruction* op) {
if (op->opcode() != HloOpcode::kTuple) {
return op;
}
HloInstruction* hidden_op = nullptr;
for (auto opnd : op->mutable_operands()) {
if (opnd->opcode() != HloOpcode::kGetTupleElement) {
return op;
}
if (hidden_op == nullptr) {
hidden_op = opnd->mutable_operand(0);
} else if (opnd->mutable_operand(0) != hidden_op) {
return op;
}
}
return hidden_op;
}
const HloInstruction* MaySkipTrivialTuple(const HloInstruction* op) {
return MaySkipTrivialTuple(const_cast<HloInstruction*>(op));
}
std::optional<PipelinedP2PInfo>
FindConsecutiveAndBalanceBlockOfSendDoneRecvDone(
const HloInstruction* while_init) {
PipelinedP2PInfo pipelined_p2p_info{0, 0};
auto has_started = [&]() {
return pipelined_p2p_info.opnd_start != pipelined_p2p_info.opnd_end;
};
int difference = 0;
for (int64_t i = 0; i < while_init->operand_count(); ++i) {
const HloInstruction* op = while_init->operand(i);
if ((op->opcode() == HloOpcode::kRecvDone ||
op->opcode() == HloOpcode::kSendDone) &&
op->frontend_attributes().map().count(kSendRecvPipelineAttr) > 0) {
if (op->opcode() == HloOpcode::kRecvDone) {
difference++;
} else {
difference--;
}
if (!has_started()) {
pipelined_p2p_info.opnd_start = i;
}
pipelined_p2p_info.opnd_end = i + 1;
} else {
if (has_started()) {
VLOG(10) << "End a consecutive block";
break;
}
}
}
if (difference != 0) {
VLOG(10) << "Mismatch number of SendDone and RecvDone: " << difference;
return std::nullopt;
}
if (has_started()) {
for (int64_t i = pipelined_p2p_info.opnd_end;
i < while_init->operand_count(); ++i) {
const HloInstruction* op = while_init->operand(i);
if (op->opcode() == HloOpcode::kRecvDone ||
op->opcode() == HloOpcode::kSendDone) {
VLOG(10) << "SendDone/RecvDone outside the consecutive block";
return std::nullopt;
break;
}
}
}
if (!has_started()) {
VLOG(10) << "No SendDone/RecvDone in while-init ";
return std::nullopt;
}
return pipelined_p2p_info;
}
std::optional<PipelinedP2PInfo> FindPipelinedP2P(
const HloInstruction* while_op) {
VLOG(10) << "while_op: " << while_op->ToString();
const HloInstruction* while_init = while_op->while_init();
if (while_init->opcode() != HloOpcode::kTuple ||
while_init->user_count() != 1) {
return std::nullopt;
}
const HloComputation* while_body = while_op->while_body();
const HloComputation* while_condition = while_op->while_condition();
if (while_body->num_parameters() != 1 ||
while_condition->num_parameters() != 1) {
return std::nullopt;
}
std::optional<PipelinedP2PInfo> pipelined_p2p_info =
FindConsecutiveAndBalanceBlockOfSendDoneRecvDone(while_init);
if (!pipelined_p2p_info.has_value()) {
return std::nullopt;
}
VLOG(10) << "opnd_start " << pipelined_p2p_info->opnd_start << " opnd_end "
<< pipelined_p2p_info->opnd_end;
for (int64_t i = pipelined_p2p_info->opnd_start;
i < pipelined_p2p_info->opnd_end; ++i) {
const HloInstruction* op = while_init->operand(i);
if (op->opcode() == HloOpcode::kRecvDone) {
if (!FindUniqueGTEUserWithIndex(while_op, i)) {
VLOG(10) << "While result get-tuple-element user with index " << i
<< " not unique";
return std::nullopt;
}
if (!FindUniqueGTEUserWithIndex(while_body->parameter_instruction(0),
i)) {
VLOG(10) << "While-body parameter get-tuple-element user with index "
<< i << " not unique";
return std::nullopt;
}
} else {
CHECK(op->opcode() == HloOpcode::kSendDone);
if (HasGTEUserWithIndex(while_op, i) ||
HasGTEUserWithIndex(while_body->parameter_instruction(0), i)) {
VLOG(10) << "SendDone with index " << i << " has unexpected users";
return std::nullopt;
}
}
}
const HloInstruction* root = while_body->root_instruction();
for (int64_t i = pipelined_p2p_info->opnd_start;
i < pipelined_p2p_info->opnd_end; ++i) {
const HloInstruction* op_init = while_init->operand(i);
const HloInstruction* op_root = root->operand(i);
op_root = MaySkipTrivialTuple(op_root);
if (op_init->opcode() != op_root->opcode()) {
VLOG(10) << "Mismatching opcode, op_init: " << op_init->ToString()
<< " op_root: " << op_root->ToString();
return std::nullopt;
}
}
return pipelined_p2p_info.value();
}
absl::Status RemoveOpFromParent(HloInstruction* op) {
TF_RETURN_IF_ERROR(op->DropAllControlDeps());
TF_RETURN_IF_ERROR(op->parent()->RemoveInstruction(op));
return absl::OkStatus();
}
absl::Status ReplaceOpInSequence(HloInstruction* old_op, HloInstruction* new_op,
HloInstructionSequence& instruction_sequence) {
VLOG(10) << "old_op: " << old_op->ToString();
VLOG(10) << "new_op: " << new_op->ToString();
instruction_sequence.replace_instruction(old_op, new_op);
return RemoveOpFromParent(old_op);
}
absl::Status ReplaceUsesAndUpdateSequence(
HloInstruction* old_op, HloInstruction* new_op,
HloInstructionSequence& instruction_sequence, bool diff_shape = false) {
VLOG(10) << "old_op: " << old_op->ToString();
VLOG(10) << "new_op: " << new_op->ToString();
if (diff_shape) {
TF_RETURN_IF_ERROR(old_op->ReplaceAllUsesWithDifferentShape(new_op));
} else {
TF_RETURN_IF_ERROR(old_op->ReplaceAllUsesWith(new_op));
}
return ReplaceOpInSequence(old_op, new_op, instruction_sequence);
}
absl::Status ReplaceUsesAndUpdateSequence(
const InstructionVector& old_ops, const InstructionVector& new_ops,
HloInstructionSequence& instruction_sequence) {
CHECK(old_ops.size() == new_ops.size());
for (int64_t i = 0; i < old_ops.size(); ++i) {
TF_RETURN_IF_ERROR(ReplaceUsesAndUpdateSequence(old_ops[i], new_ops[i],
instruction_sequence));
}
return absl::OkStatus();
}
absl::Status RemoveDoneOpsAndUpdateSequence(
const InstructionVector& ops,
HloInstructionSequence& instruction_sequence) {
auto remove_op = [&](HloInstruction* op) {
VLOG(10) << "op: " << op->ToString();
TF_RETURN_IF_ERROR(RemoveOpFromParent(op));
instruction_sequence.remove_instruction(op);
return absl::OkStatus();
};
for (auto op : ops) {
if (op->opcode() == HloOpcode::kTuple) {
InstructionVector to_remove;
HloInstruction* tuple_op = op;
op = MaySkipTrivialTuple(tuple_op);
to_remove.push_back(tuple_op);
for (auto opnd : tuple_op->mutable_operands()) {
to_remove.push_back(opnd);
}
for (auto opnd : to_remove) {
TF_RETURN_IF_ERROR(remove_op(opnd));
}
}
TF_RETURN_IF_ERROR(remove_op(op));
}
return absl::OkStatus();
}
bool InsertBeforeFirstCollectiveOp(
const InstructionVector& ops,
const CollectiveInComputation& collective_in_computation,
HloInstructionSequence& instruction_sequence, int64_t& idx,
int64_t& idx_tot) {
bool inserted = false;
while (idx < idx_tot) {
HloInstruction* hlo = instruction_sequence.instructions()[idx];
if (MayInvokeCollectiveOp(hlo, collective_in_computation)) {
for (auto op : ops) {
instruction_sequence.insert_instruction(op, idx);
idx++;
idx_tot++;
}
inserted = true;
break;
}
idx++;
}
return inserted;
}
void CopyInstructionInfo(const HloInstruction* old_op, HloInstruction* new_op) {
new_op->SetAndSanitizeName(absl::StrCat(old_op->name(), ".clone"));
new_op->set_metadata(old_op->metadata());
new_op->add_frontend_attributes(old_op->frontend_attributes());
new_op->CopyBackendConfigFrom(old_op);
}
HloInstruction* CreateRecvDoneFrom(const HloInstruction* old_recv_done,
HloInstruction* recv,
HloComputation* computation) {
HloInstruction* recv_done =
computation->AddInstruction(HloInstruction::CreateRecvDone(
recv, old_recv_done->channel_id().value()));
CopyInstructionInfo(old_recv_done, recv_done);
return recv_done;
}
HloInstruction* CreateSendDoneFrom(const HloInstruction* old_send_done,
HloInstruction* send,
HloComputation* computation) {
HloInstruction* send_done =
computation->AddInstruction(HloInstruction::CreateSendDone(
send, old_send_done->channel_id().value()));
CopyInstructionInfo(old_send_done, send_done);
return send_done;
}
absl::Status RewritePipelinedP2PWhileBody(
const CollectiveInComputation& collective_in_computation,
const std::vector<Shape>& new_parameter_shapes, HloInstruction* while_op,
int64_t opnd_start, int64_t opnd_end) {
HloComputation* computation = while_op->while_body();
HloInstruction* while_init = while_op->while_init();
HloInstruction* root = computation->root_instruction();
HloInstructionSequence& instruction_sequence =
computation->parent()->schedule().GetOrCreateSequence(computation);
HloInstruction* param = computation->parameter_instruction(0);
*param->mutable_shape() = ShapeUtil::MakeTupleShape(new_parameter_shapes);
InstructionVector recv_dones;
InstructionVector new_recv_dones;
InstructionVector new_send_dones;
for (int64_t i = opnd_start; i < opnd_end; ++i) {
const HloInstruction* op = root->operand(i);
op = MaySkipTrivialTuple(op);
if (op->opcode() == HloOpcode::kRecvDone) {
HloInstruction* gte = FindUniqueGTEUserWithIndex(param, i);
CHECK(gte != nullptr);
recv_dones.push_back(gte);
HloInstruction* recv = computation->AddInstruction(
HloInstruction::CreateGetTupleElement(param, i));
HloInstruction* recv_done = CreateRecvDoneFrom(op, recv, computation);
new_recv_dones.push_back(recv_done);
continue;
}
CHECK(op->opcode() == HloOpcode::kSendDone);
HloInstruction* send = computation->AddInstruction(
HloInstruction::CreateGetTupleElement(param, i));
HloInstruction* send_done = CreateSendDoneFrom(op, send, computation);
new_send_dones.push_back(send_done);
}
TF_RETURN_IF_ERROR(ReplaceUsesAndUpdateSequence(recv_dones, new_recv_dones,
instruction_sequence));
InstructionVector done_ops;
InstructionVector new_opnds;
for (int64_t i = 0; i < while_init->operand_count(); ++i) {
HloInstruction* op = root->mutable_operand(i);
if (i >= opnd_start && i < opnd_end) {
new_opnds.push_back(MaySkipTrivialTuple(op)->mutable_operand(0));
done_ops.push_back(op);
} else {
new_opnds.push_back(op);
}
}
HloInstruction* new_root =
computation->AddInstruction(HloInstruction::CreateTuple(new_opnds));
computation->set_root_instruction(new_root,
true);
TF_RETURN_IF_ERROR(computation->RemoveInstruction(root));
instruction_sequence.replace_instruction(root, new_root);
TF_RETURN_IF_ERROR(
RemoveDoneOpsAndUpdateSequence(done_ops, instruction_sequence));
int64_t idx = 0;
int64_t idx_end = instruction_sequence.size();
bool inserted =
InsertBeforeFirstCollectiveOp(new_send_dones, collective_in_computation,
instruction_sequence, idx, idx_end);
CHECK(inserted);
CHECK(idx_end == instruction_sequence.size());
return absl::OkStatus();
}
void RewritePipelinedP2PWhileCond(
const std::vector<Shape>& new_parameter_shapes, HloInstruction* while_op) {
HloComputation* computation = while_op->while_condition();
HloInstruction* param = computation->parameter_instruction(0);
*param->mutable_shape() = ShapeUtil::MakeTupleShape(new_parameter_shapes);
VLOG(10) << computation->ToString();
}
absl::Status TransformLoop(
const PipelinedP2PInfo& pipelined_info,
const CollectiveInComputation& collective_in_computation, int64_t& idx,
int64_t& idx_end, HloInstructionSequence& instruction_sequence,
HloInstruction* while_op) {
HloComputation* computation = while_op->parent();
int64_t opnd_start = pipelined_info.opnd_start;
int64_t opnd_end = pipelined_info.opnd_end;
VLOG(10) << "Transform pipelined while-op " << while_op->ToString();
HloInstruction* while_init = while_op->while_init();
InstructionVector new_while_init_opnds;
std::vector<Shape> new_parameter_shapes;
for (int64_t i = 0; i < while_init->operand_count(); ++i) {
HloInstruction* op = while_init->mutable_operand(i);
if (i >= opnd_start && i < opnd_end) {
new_while_init_opnds.push_back(op->mutable_operand(0));
} else {
new_while_init_opnds.push_back(op);
}
new_parameter_shapes.push_back(new_while_init_opnds.back()->shape());
}
RewritePipelinedP2PWhileCond(new_parameter_shapes, while_op);
TF_RETURN_IF_ERROR(RewritePipelinedP2PWhileBody(
collective_in_computation, new_parameter_shapes, while_op, opnd_start,
opnd_end));
HloInstruction* new_while_init = computation->AddInstruction(
HloInstruction::CreateTuple(new_while_init_opnds), "while-init");
VLOG(10) << "new_while_init: " << new_while_init->ToString();
HloInstruction* new_while_op = computation->AddInstruction(
HloInstruction::CreateWhile(
while_op->while_body()->root_instruction()->shape(),
while_op->while_condition(), while_op->while_body(), new_while_init),
"while-result");
CopyInstructionInfo(while_op, new_while_op);
VLOG(10) << "new_while_op: " << new_while_op->ToString();
InstructionVector recv_dones;
InstructionVector new_recv_dones;
InstructionVector new_send_dones;
InstructionVector done_ops;
for (int64_t i = opnd_start; i < opnd_end; ++i) {
HloInstruction* op = while_init->mutable_operand(i);
done_ops.push_back(op);
if (op->opcode() == HloOpcode::kRecvDone) {
HloInstruction* gte = FindUniqueGTEUserWithIndex(while_op, i);
CHECK(gte != nullptr);
recv_dones.push_back(gte);
HloInstruction* recv = computation->AddInstruction(
HloInstruction::CreateGetTupleElement(new_while_op, i));
HloInstruction* recv_done = computation->AddInstruction(
HloInstruction::CreateRecvDone(recv, op->channel_id().value()));
new_recv_dones.push_back(recv_done);
CopyInstructionInfo(op, recv_done);
continue;
}
CHECK(op->opcode() == HloOpcode::kSendDone);
HloInstruction* send = computation->AddInstruction(
HloInstruction::CreateGetTupleElement(new_while_op, i));
HloInstruction* send_done = computation->AddInstruction(
HloInstruction::CreateSendDone(send, op->channel_id().value()));
new_send_dones.push_back(send_done);
CopyInstructionInfo(op, send_done);
}
TF_RETURN_IF_ERROR(ReplaceUsesAndUpdateSequence(
while_op, new_while_op, instruction_sequence, true));
TF_RETURN_IF_ERROR(
ReplaceOpInSequence(while_init, new_while_init, instruction_sequence));
TF_RETURN_IF_ERROR(ReplaceUsesAndUpdateSequence(recv_dones, new_recv_dones,
instruction_sequence));
TF_RETURN_IF_ERROR(
RemoveDoneOpsAndUpdateSequence(done_ops, instruction_sequence));
int64_t opnd_tot = opnd_end - opnd_start;
CHECK(idx_end == instruction_sequence.size() + opnd_tot);
CHECK(instruction_sequence.instructions()[idx - opnd_tot] == new_while_op);
idx_end -= opnd_tot;
idx = idx - opnd_tot + 1;
bool inserted =
InsertBeforeFirstCollectiveOp(new_send_dones, collective_in_computation,
instruction_sequence, idx, idx_end);
CHECK(idx_end == instruction_sequence.size());
if (!inserted) {
CHECK(idx_end == idx);
idx--;
for (auto send_done : new_send_dones) {
instruction_sequence.insert_instruction(send_done, idx++);
}
}
return absl::OkStatus();
}
absl::StatusOr<bool> ProcessComputation(
HloModule* module, HloComputation* computation,
CollectiveInComputation& collective_in_computation) {
VLOG(10) << "Process compuation " << computation->name();
bool changed = false;
HloInstructionSequence& instruction_sequence =
module->schedule().GetOrCreateSequence(computation);
int64_t idx = 0;
int64_t idx_end = instruction_sequence.size();
while (idx < idx_end) {
HloInstruction* hlo = instruction_sequence.instructions()[idx];
if (MayInvokeCollectiveOp(hlo, collective_in_computation)) {
collective_in_computation[computation] = true;
}
if (hlo->opcode() != HloOpcode::kWhile) {
idx++;
continue;
}
std::optional<PipelinedP2PInfo> pipelined_info = FindPipelinedP2P(hlo);
if (!pipelined_info.has_value()) {
idx++;
continue;
}
TF_RETURN_IF_ERROR(TransformLoop(pipelined_info.value(),
collective_in_computation, idx, idx_end,
instruction_sequence, hlo));
changed = true;
}
return changed;
}
}
absl::StatusOr<bool> PipelinedP2PRewriter::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
bool changed = false;
if (!module->has_schedule()) return changed;
CollectiveInComputation collective_in_computation;
for (auto* computation :
module->MakeComputationPostOrder(execution_threads)) {
if (computation->IsFusionComputation()) {
collective_in_computation[computation] = false;
continue;
}
TF_ASSIGN_OR_RETURN(
bool cur_changed,
ProcessComputation(module, computation, collective_in_computation));
changed |= cur_changed;
}
if (changed) {
TF_RETURN_IF_ERROR(module->schedule().Update());
}
return changed;
}
}
} | #include "xla/service/gpu/transforms/pipelined_p2p_rewriter.h"
#include <gtest/gtest.h>
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/tests/filecheck.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
namespace {
class PipelinedP2pRewriterTest : public HloTestBase {
protected:
void DoFileCheck(const HloModule* module, absl::string_view expected) {
HloPrintOptions options;
options.set_print_operand_shape(false);
options.set_print_result_shape(false);
TF_ASSERT_OK_AND_ASSIGN(bool filecheck_matched,
RunFileCheck(module->ToString(options), expected));
EXPECT_TRUE(filecheck_matched);
}
};
TEST_F(PipelinedP2pRewriterTest, SendRecUnpipelinedNotTransform) {
const char* kModuleStr = R"(
HloModule test
cond {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(%param), index=0
ub = u32[] constant(11)
ROOT result = pred[] compare(count, ub), direction=LT
}
body {
param = (u32[], u32[2]) parameter(0)
count = get-tuple-element(param), index=0
send-data = u32[2] get-tuple-element(param), index=1
after-all.0.n = token[] after-all()
recv.0 = (u32[2], u32[], token[]) recv(after-all.0.n), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{3,0}}",
_xla_send_recv_pipeline="0"
}
send.0 = (u32[2], u32[], token[]) send(send-data, after-all.0.n),
channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{3,0}}",
_xla_send_recv_pipeline="0"
}
recv-done.0 = (u32[2], token[]) recv-done(recv.0), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.0 = token[] send-done(send.0), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
recv-data = u32[2] get-tuple-element(recv-done.0), index=0
c1 = u32[] constant(1)
new_count = u32[] add(count, c1)
r = u32[2] broadcast(c1), dimensions={}
s = u32[2] add(r, recv-data)
ROOT result = (u32[], u32[2]) tuple(new_count, s)
}
ENTRY test_computation {
c0 = u32[] constant(0)
c1 = u32[] constant(1)
r = u32[] replica-id()
a = u32[] add(c1, r)
init = u32[2] broadcast(a), dimensions={}
while_init = (u32[], u32[2]) tuple(c0, init)
while_result = (u32[], u32[2]) while(while_init), body=body, condition=cond,
backend_config={"known_trip_count":{"n":"11"}}
ROOT recv-data = u32[2] get-tuple-element(while_result), index=1
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
PipelinedP2PRewriter rewriter;
TF_ASSERT_OK_AND_ASSIGN(bool changed, rewriter.Run(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(PipelinedP2pRewriterTest, SendRecvPipelined1) {
const char* kModuleStr = R"(
HloModule test, is_scheduled=true
while-cond {
param = (u32[], (f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
ub = u32[] constant(25)
ROOT cond-result = pred[] compare(count, ub), direction=LT
}
while-body {
param = (u32[], (f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
recv-done.q = (f32[1,1024,1024], token[]) get-tuple-element(param), index=1
recv-data = f32[1, 1024, 1024] get-tuple-element(recv-done.q), index=0
c1 = u32[] constant(1)
new-count = u32[] add(count, c1)
replica = u32[] replica-id()
c10 = u32[] constant(10)
sum = u32[] add(replica, c10)
sum2 = u32[] add(sum, count)
conv = f32[] convert(sum2)
p = f32[1, 1024, 1024] broadcast(conv), dimensions={}
b = f32[1, 1024, 1024] add(p, recv-data)
c = f32[1, 1024, 1024] multiply(b, b)
d = f32[1, 1024, 1024] tan(c)
s = f32[1, 1024, 1024] dot(c, d), lhs_batch_dims={0},
lhs_contracting_dims={1}, rhs_batch_dims={0}, rhs_contracting_dims={1}
send-data = f32[1, 1024, 1024] add(c, s)
after-all = token[] after-all()
recv = (f32[1, 1024, 1024], u32[], token[]) recv(after-all), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
send = (f32[1, 1024, 1024], u32[], token[]) send(send-data, after-all),
channel_id=1, frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
recv-done.p = (f32[1,1024,1024], token[]) recv-done(recv), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.p = token[] send-done(send), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
gte.0 = f32[1,1024,1024] get-tuple-element(recv-done.p), index=0
gte.1 = token[] get-tuple-element(recv-done.p), index=1
recv-done-tuple = (f32[1,1024,1024], token[]) tuple(gte.0, gte.1)
ROOT body-result = (u32[], (f32[1,1024,1024], token[]), token[])
tuple(new-count, recv-done-tuple, send-done.p)
}
ENTRY main {
c0 = u32[] constant(0)
f0 = f32[] constant(0.0)
init = f32[1, 1024, 1024] broadcast(f0), dimensions={}
after-all.1 = token[] after-all()
recv.1 = (f32[1, 1024, 1024], u32[], token[]) recv(after-all.1), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
send.1 = (f32[1, 1024, 1024], u32[], token[]) send(init, after-all.1), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
recv-done.1.p = (f32[1,1024,1024], token[]) recv-done(recv.1), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.1.p = token[] send-done(send.1), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
while-init.p = (u32[], (f32[1,1024,1024], token[]), token[])
tuple(c0, recv-done.1.p, send-done.1.p)
while-result.p = (u32[], (f32[1,1024,1024], token[]), token[])
while(while-init.p),
body=while-body, condition=while-cond,
backend_config={"known_trip_count":{"n":"25"}}
recv-done.1.q = (f32[1,1024,1024], token[]) get-tuple-element(while-result.p), index=1
ROOT entry-result = f32[1, 1024, 1024] get-tuple-element(recv-done.1.q), index=0
}
)";
const char* kExpected = R"(
CHECK: %while-body (param.1: (u32[], (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]))) -> (u32[], (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[])) {
CHECK: %param.1 = parameter(0)
CHECK: %get-tuple-element = get-tuple-element(%param.1), index=1
CHECK: %get-tuple-element.1 = get-tuple-element(%param.1), index=2
CHECK: %count.1 = get-tuple-element(%param.1), index=0
CHECK: %recv-done.p.clone = recv-done(%get-tuple-element), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK: %recv-data = get-tuple-element(%recv-done.p.clone), index=0
CHECK: %c1 = constant(1)
CHECK: %new-count = add(%count.1, %c1)
CHECK: %replica = replica-id()
CHECK: %c10 = constant(10)
CHECK: %sum = add(%replica, %c10)
CHECK: %sum2 = add(%sum, %count.1)
CHECK: %conv = convert(%sum2)
CHECK: %p = broadcast(%conv), dimensions={}
CHECK: %b = add(%p, %recv-data)
CHECK: %c = multiply(%b, %b)
CHECK: %d = tan(%c)
CHECK: %s = dot(%c, %d), lhs_batch_dims={0}, lhs_contracting_dims={1}, rhs_batch_dims={0}, rhs_contracting_dims={1}
CHECK: %send-data = add(%c, %s)
CHECK: %after-all = after-all()
CHECK: %send-done.p.clone = send-done(%get-tuple-element.1), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK{LITERAL}: %recv = recv(%after-all), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}}}
CHECK{LITERAL}: %send = send(%send-data, %after-all), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}}}
CHECK: ROOT %tuple = tuple(%new-count, %recv, %send)
CHECK: }
CHECK: %while-cond (param: (u32[], (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]))) -> pred[] {
CHECK: %param = parameter(0)
CHECK: %count = get-tuple-element(%param), index=0
CHECK: %ub = constant(25)
CHECK: ROOT %cond-result = compare(%count, %ub), direction=LT
CHECK: }
CHECK: ENTRY %main () -> f32[1,1024,1024] {
CHECK: %c0 = constant(0)
CHECK: %f0 = constant(0)
CHECK: %init = broadcast(%f0), dimensions={}
CHECK: %after-all.1 = after-all()
CHECK{LITERAL}: %recv.1 = recv(%after-all.1), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}}}
CHECK{LITERAL}: %send.1 = send(%init, %after-all.1), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}, {3,4}}}
CHECK: %while-init = tuple(%c0, %recv.1, %send.1)
CHECK: %while-result.p.clone = while(%while-init), condition=%while-cond, body=%while-body,
CHECK-SAME{LITERAL}: backend_config={"known_trip_count":{"n":"25"}}
CHECK: %get-tuple-element.2 = get-tuple-element(%while-result.p.clone), index=1
CHECK: %get-tuple-element.3 = get-tuple-element(%while-result.p.clone), index=2
CHECK: %recv-done.1.p.clone = recv-done(%get-tuple-element.2), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK: %send-done.1.p.clone = send-done(%get-tuple-element.3), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK: ROOT %entry-result = get-tuple-element(%recv-done.1.p.clone), index=0
CHECK: })";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
PipelinedP2PRewriter rewriter;
TF_ASSERT_OK_AND_ASSIGN(bool changed, rewriter.Run(module.get()));
EXPECT_TRUE(changed);
DoFileCheck(module.get(), kExpected);
}
TEST_F(PipelinedP2pRewriterTest, SendRecvTwoPipelinedWhileLoops) {
const char* kModuleStr = R"(
HloModule test, is_scheduled=true
while-cond {
param = (u32[], (f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
ub = u32[] constant(25)
ROOT cond-result = pred[] compare(count, ub), direction=LT
}
while-body {
param = (u32[], (f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
recv-done.q = (f32[1,1024,1024], token[]) get-tuple-element(param), index=1
send-data = f32[1, 1024, 1024] get-tuple-element(recv-done.q), index=0
c1 = u32[] constant(1)
new-count = u32[] add(count, c1)
after-all = token[] after-all()
recv = (f32[1, 1024, 1024], u32[], token[]) recv(after-all), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
send = (f32[1, 1024, 1024], u32[], token[]) send(send-data, after-all),
channel_id=1, frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
recv-done.p = (f32[1,1024,1024], token[]) recv-done(recv), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.p = token[] send-done(send), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
gte.0 = f32[1,1024,1024] get-tuple-element(recv-done.p), index=0
gte.1 = token[] get-tuple-element(recv-done.p), index=1
recv-done-tuple = (f32[1,1024,1024], token[]) tuple(gte.0, gte.1)
ROOT body-result = (u32[], (f32[1,1024,1024], token[]), token[])
tuple(new-count, recv-done-tuple, send-done.p)
}
while-cond-2 {
param = (u32[], (f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
ub = u32[] constant(25)
ROOT cond-result = pred[] compare(count, ub), direction=LT
}
while-body-2 {
param = (u32[], (f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
recv-done.q = (f32[1,1024,1024], token[]) get-tuple-element(param), index=1
send-data = f32[1, 1024, 1024] get-tuple-element(recv-done.q), index=0
c1 = u32[] constant(1)
new-count = u32[] add(count, c1)
after-all = token[] after-all()
recv = (f32[1, 1024, 1024], u32[], token[]) recv(after-all), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
send = (f32[1, 1024, 1024], u32[], token[]) send(send-data, after-all),
channel_id=1, frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
recv-done.p = (f32[1,1024,1024], token[]) recv-done(recv), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.p = token[] send-done(send), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
gte.0 = f32[1,1024,1024] get-tuple-element(recv-done.p), index=0
gte.1 = token[] get-tuple-element(recv-done.p), index=1
recv-done-tuple = (f32[1,1024,1024], token[]) tuple(gte.0, gte.1)
ROOT body-result = (u32[], (f32[1,1024,1024], token[]), token[])
tuple(new-count, recv-done-tuple, send-done.p)
}
ENTRY main {
c0 = u32[] constant(0)
f0 = f32[] constant(0.0)
init = f32[1, 1024, 1024] broadcast(f0), dimensions={}
after-all.1 = token[] after-all()
recv.1 = (f32[1, 1024, 1024], u32[], token[]) recv(after-all.1), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
send.1 = (f32[1, 1024, 1024], u32[], token[]) send(init, after-all.1), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
recv-done.1.p = (f32[1,1024,1024], token[]) recv-done(recv.1), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.1.p = token[] send-done(send.1), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
while-init.p = (u32[], (f32[1,1024,1024], token[]), token[])
tuple(c0, recv-done.1.p, send-done.1.p)
while-result.p = (u32[], (f32[1,1024,1024], token[]), token[])
while(while-init.p),
body=while-body, condition=while-cond,
backend_config={"known_trip_count":{"n":"25"}}
recv-done.1.q = (f32[1,1024,1024], token[]) get-tuple-element(while-result.p), index=1
after-all-2.1 = token[] after-all()
recv-2.1 = (f32[1, 1024, 1024], u32[], token[]) recv(after-all-2.1), channel_id=2,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
send-2.1 = (f32[1, 1024, 1024], u32[], token[]) send(recv-done.1.q, after-all-2.1), channel_id=2,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}, {3,4}}",
_xla_send_recv_pipeline="0"
}
recv-done-2.1.p = (f32[1,1024,1024], token[]) recv-done(recv-2.1), channel_id=2,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done-2.1.p = token[] send-done(send-2.1), channel_id=2,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
while-init-2.p = (u32[], (f32[1,1024,1024], token[]), token[])
tuple(c0, recv-done-2.1.p, send-done-2.1.p)
while-result-2.p = (u32[], (f32[1,1024,1024], token[]), token[])
while(while-init-2.p),
body=while-body-2, condition=while-cond-2,
backend_config={"known_trip_count":{"n":"25"}}
recv-done-2.1.q = (f32[1,1024,1024], token[]) get-tuple-element(while-result-2.p), index=1
ROOT entry-result = f32[1, 1024, 1024] get-tuple-element(recv-done-2.1.q), index=0
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
PipelinedP2PRewriter rewriter;
TF_ASSERT_OK_AND_ASSIGN(bool changed, rewriter.Run(module.get()));
EXPECT_TRUE(changed);
}
TEST_F(PipelinedP2pRewriterTest, SendRecvPipelined2) {
const char* kModuleStr = R"(
HloModule test, is_scheduled=true
while-cond {
param = (u32[], (f32[1,1024,1024], token[]), token[],
(f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
ub = u32[] constant(25)
ROOT cond-result = pred[] compare(count, ub), direction=LT
}
while-body {
param = (u32[], (f32[1,1024,1024], token[]), token[],
(f32[1,1024,1024], token[]), token[]) parameter(0)
count = get-tuple-element(param), index=0
recv-done.0.q = (f32[1,1024,1024], token[]) get-tuple-element(param), index=1
recv-data.0 = f32[1, 1024, 1024] get-tuple-element(recv-done.0.q), index=0
recv-done.1.q = (f32[1,1024,1024], token[]) get-tuple-element(param), index=3
recv-data.1 = f32[1, 1024, 1024] get-tuple-element(recv-done.1.q), index=0
replica = u32[] replica-id()
constant0 = u32[] constant(0)
compare0 = pred[] compare(replica, constant0), direction=EQ
compare = pred[1, 1024, 1024] broadcast(compare0), dimensions={}
recv-data = f32[1, 1024, 1024] select(compare, recv-data.0, recv-data.1)
c1 = u32[] constant(1)
new-count = u32[] add(count, c1)
c10 = u32[] constant(10)
sum = u32[] add(replica, c10)
sum2 = u32[] add(sum, count)
conv = f32[] convert(sum2)
p = f32[1, 1024, 1024] broadcast(conv), dimensions={}
b = f32[1, 1024, 1024] add(p, recv-data)
c = f32[1, 1024, 1024] multiply(b, b)
d = f32[1, 1024, 1024] tan(c)
s = f32[1, 1024, 1024] dot(c, d), lhs_batch_dims={0},
lhs_contracting_dims={1}, rhs_batch_dims={0}, rhs_contracting_dims={1}
send-data = f32[1, 1024, 1024] add(c, s)
after-all = token[] after-all()
recv = (f32[1, 1024, 1024], u32[], token[]) recv(after-all), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{3,0}}",
_xla_send_recv_pipeline="0"
}
send = (f32[1, 1024, 1024], u32[], token[]) send(send-data, after-all),
channel_id=1, frontend_attributes={
_xla_send_recv_source_target_pairs="{{3,0}}",
_xla_send_recv_pipeline="0"
}
recv-done.p = (f32[1,1024,1024], token[]) recv-done(recv), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.p = token[] send-done(send), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
after-all.1 = token[] after-all()
recv.1 = (f32[1, 1024, 1024], u32[], token[]) recv(after-all.1), channel_id=2,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}}",
_xla_send_recv_pipeline="1"
}
send.1 = (f32[1, 1024, 1024], u32[], token[]) send(send-data, after-all.1),
channel_id=2, frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}}",
_xla_send_recv_pipeline="1"
}
recv-done.1.p = (f32[1,1024,1024], token[]) recv-done(recv.1), channel_id=2,
frontend_attributes={
_xla_send_recv_pipeline="1"
}
send-done.1.p = token[] send-done(send.1), channel_id=2,
frontend_attributes={
_xla_send_recv_pipeline="1"
}
ROOT body-result = (u32[], (f32[1,1024,1024], token[]), token[],
(f32[1,1024,1024], token[]), token[])
tuple(new-count, recv-done.p, send-done.p, recv-done.1.p, send-done.1.p)
}
ENTRY main {
c0 = u32[] constant(0)
f0 = f32[] constant(0.0)
init = f32[1, 1024, 1024] broadcast(f0), dimensions={}
after-all.2 = token[] after-all()
recv.2 = (f32[1, 1024, 1024], u32[], token[]) recv(after-all.2), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{3,0}}",
_xla_send_recv_pipeline="0"
}
send.2 = (f32[1, 1024, 1024], u32[], token[]) send(init, after-all.2), channel_id=1,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{3,0}}",
_xla_send_recv_pipeline="0"
}
recv-done.2.p = (f32[1,1024,1024], token[]) recv-done(recv.2), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
send-done.2.p = token[] send-done(send.2), channel_id=1,
frontend_attributes={
_xla_send_recv_pipeline="0"
}
after-all.3 = token[] after-all()
recv.3 = (f32[1, 1024, 1024], u32[], token[]) recv(after-all.3), channel_id=2,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}}",
_xla_send_recv_pipeline="1"
}
send.3 = (f32[1, 1024, 1024], u32[], token[]) send(init, after-all.3), channel_id=2,
frontend_attributes={
_xla_send_recv_source_target_pairs="{{0,1}, {1,2}, {2,3}}",
_xla_send_recv_pipeline="1"
}
recv-done.3.p = (f32[1,1024,1024], token[]) recv-done(recv.3), channel_id=2,
frontend_attributes={
_xla_send_recv_pipeline="1"
}
send-done.3.p = token[] send-done(send.3), channel_id=2,
frontend_attributes={
_xla_send_recv_pipeline="1"
}
while-init.p = (u32[], (f32[1,1024,1024], token[]), token[],
(f32[1,1024,1024], token[]), token[]) tuple(c0, recv-done.2.p, send-done.2.p, recv-done.3.p, send-done.3.p)
while-result.p = (u32[], (f32[1,1024,1024], token[]), token[],
(f32[1,1024,1024], token[]), token[]) while(while-init.p),
body=while-body, condition=while-cond,
backend_config={"known_trip_count":{"n":"25"}}
recv-done.2.q = (f32[1,1024,1024], token[]) get-tuple-element(while-result.p), index=1
recv-data.2 = f32[1, 1024, 1024] get-tuple-element(recv-done.2.q), index=0
recv-done.3.q = (f32[1,1024,1024], token[]) get-tuple-element(while-result.p), index=3
recv-data.3 = f32[1, 1024, 1024] get-tuple-element(recv-done.3.q), index=0
replica = u32[] replica-id()
constant0 = u32[] constant(0)
compare0 = pred[] compare(replica, constant0), direction=EQ
compare = pred[1, 1024, 1024] broadcast(compare0), dimensions={}
ROOT entry-result = f32[1, 1024, 1024] select(compare, recv-data.2, recv-data.3)
}
)";
const char* kExpected = R"(
CHECK: %while-body (param.1: (u32[], (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]))) -> (u32[], (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[])) {
CHECK: %param.1 = parameter(0)
CHECK: %get-tuple-element = get-tuple-element(%param.1), index=1
CHECK: %get-tuple-element.1 = get-tuple-element(%param.1), index=2
CHECK: %get-tuple-element.2 = get-tuple-element(%param.1), index=3
CHECK: %get-tuple-element.3 = get-tuple-element(%param.1), index=4
CHECK: %count.1 = get-tuple-element(%param.1), index=0
CHECK: %recv-done.p.clone = recv-done(%get-tuple-element), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK: %recv-data.0 = get-tuple-element(%recv-done.p.clone), index=0
CHECK: %recv-done.1.p.clone = recv-done(%get-tuple-element.2), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1"}
CHECK: %recv-data.1 = get-tuple-element(%recv-done.1.p.clone), index=0
CHECK: %replica = replica-id()
CHECK: %constant0 = constant(0)
CHECK: %compare0 = compare(%replica, %constant0), direction=EQ
CHECK: %compare = broadcast(%compare0), dimensions={}
CHECK: %recv-data.2 = select(%compare, %recv-data.0, %recv-data.1)
CHECK: %c1 = constant(1)
CHECK: %new-count = add(%count.1, %c1)
CHECK: %c10 = constant(10)
CHECK: %sum = add(%replica, %c10)
CHECK: %sum2 = add(%sum, %count.1)
CHECK: %conv = convert(%sum2)
CHECK: %p = broadcast(%conv), dimensions={}
CHECK: %b = add(%p, %recv-data.2)
CHECK: %c = multiply(%b, %b)
CHECK: %d = tan(%c)
CHECK: %s = dot(%c, %d), lhs_batch_dims={0}, lhs_contracting_dims={1}, rhs_batch_dims={0}, rhs_contracting_dims={1}
CHECK: %send-data = add(%c, %s)
CHECK: %after-all = after-all()
CHECK: %send-done.p.clone = send-done(%get-tuple-element.1), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK: %send-done.1.p.clone = send-done(%get-tuple-element.3), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1"}
CHECK{LITERAL}: %recv = recv(%after-all), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{3,0}}}
CHECK{LITERAL}: %send = send(%send-data, %after-all), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{3,0}}}
CHECK: %after-all.1 = after-all()
CHECK{LITERAL}: %recv.1 = recv(%after-all.1), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}}}
CHECK{LITERAL}: %send.1 = send(%send-data, %after-all.1), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}}}
CHECK: ROOT %tuple = tuple(%new-count, %recv, %send, %recv.1, %send.1)
CHECK: }
CHECK: %while-cond (param: (u32[], (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]), (f32[1,1024,1024], u32[], token[]))) -> pred[] {
CHECK: %param = parameter(0)
CHECK: %count = get-tuple-element(%param), index=0
CHECK: %ub = constant(25)
CHECK: ROOT %cond-result = compare(%count, %ub), direction=LT
CHECK: }
CHECK: ENTRY %main () -> f32[1,1024,1024] {
CHECK: %c0 = constant(0)
CHECK: %f0 = constant(0)
CHECK: %init = broadcast(%f0), dimensions={}
CHECK: %after-all.2 = after-all()
CHECK{LITERAL}: %recv.2 = recv(%after-all.2), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{3,0}}}
CHECK{LITERAL}: %send.2 = send(%init, %after-all.2), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0",_xla_send_recv_source_target_pairs={{3,0}}}
CHECK: %after-all.3 = after-all()
CHECK{LITERAL}: %recv.3 = recv(%after-all.3), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}}}
CHECK{LITERAL}: %send.3 = send(%init, %after-all.3), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1",_xla_send_recv_source_target_pairs={{0,1}, {1,2}, {2,3}}}
CHECK: %while-init = tuple(%c0, %recv.2, %send.2, %recv.3, %send.3)
CHECK{LITERAL}: %while-result.p.clone = while(%while-init), condition=%while-cond, body=%while-body, backend_config={"known_trip_count":{"n":"25"}}
CHECK: %get-tuple-element.4 = get-tuple-element(%while-result.p.clone), index=1
CHECK: %get-tuple-element.5 = get-tuple-element(%while-result.p.clone), index=2
CHECK: %get-tuple-element.6 = get-tuple-element(%while-result.p.clone), index=3
CHECK: %get-tuple-element.7 = get-tuple-element(%while-result.p.clone), index=4
CHECK: %recv-done.2.p.clone = recv-done(%get-tuple-element.4), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK: %recv-data.3 = get-tuple-element(%recv-done.2.p.clone), index=0
CHECK: %recv-done.3.p.clone = recv-done(%get-tuple-element.6), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1"}
CHECK: %recv-data.4 = get-tuple-element(%recv-done.3.p.clone), index=0
CHECK: %replica.1 = replica-id()
CHECK: %constant0.1 = constant(0)
CHECK: %compare0.1 = compare(%replica.1, %constant0.1), direction=EQ
CHECK: %compare.1 = broadcast(%compare0.1), dimensions={}
CHECK: %send-done.2.p.clone = send-done(%get-tuple-element.5), channel_id=1, frontend_attributes={_xla_send_recv_pipeline="0"}
CHECK: %send-done.3.p.clone = send-done(%get-tuple-element.7), channel_id=2, frontend_attributes={_xla_send_recv_pipeline="1"}
CHECK: ROOT %entry-result = select(%compare.1, %recv-data.3, %recv-data.4)
CHECK: })";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
PipelinedP2PRewriter rewriter;
TF_ASSERT_OK_AND_ASSIGN(bool changed, rewriter.Run(module.get()));
EXPECT_TRUE(changed);
DoFileCheck(module.get(), kExpected);
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/transforms/pipelined_p2p_rewriter.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/service/gpu/transforms/pipelined_p2p_rewriter_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
735cb486-ca91-4254-8dcb-7d65517afcb1 | cpp | google/cel-cpp | int_wrapper_type | common/types/int_wrapper_type.h | common/types/int_wrapper_type_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_INT_WRAPPER_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_INT_WRAPPER_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeParameters;
class IntWrapperType final {
public:
static constexpr TypeKind kKind = TypeKind::kIntWrapper;
static constexpr absl::string_view kName = "google.protobuf.Int64Value";
IntWrapperType() = default;
IntWrapperType(const IntWrapperType&) = default;
IntWrapperType(IntWrapperType&&) = default;
IntWrapperType& operator=(const IntWrapperType&) = default;
IntWrapperType& operator=(IntWrapperType&&) = default;
static TypeKind kind() { return kKind; }
static absl::string_view name() { return kName; }
static TypeParameters GetParameters();
static std::string DebugString() { return std::string(name()); }
constexpr void swap(IntWrapperType&) noexcept {}
};
inline constexpr void swap(IntWrapperType& lhs, IntWrapperType& rhs) noexcept {
lhs.swap(rhs);
}
inline constexpr bool operator==(IntWrapperType, IntWrapperType) {
return true;
}
inline constexpr bool operator!=(IntWrapperType lhs, IntWrapperType rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, IntWrapperType) {
return std::move(state);
}
inline std::ostream& operator<<(std::ostream& out, const IntWrapperType& type) {
return out << type.DebugString();
}
}
#endif | #include <sstream>
#include "absl/hash/hash.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
TEST(IntWrapperType, Kind) {
EXPECT_EQ(IntWrapperType().kind(), IntWrapperType::kKind);
EXPECT_EQ(Type(IntWrapperType()).kind(), IntWrapperType::kKind);
}
TEST(IntWrapperType, Name) {
EXPECT_EQ(IntWrapperType().name(), IntWrapperType::kName);
EXPECT_EQ(Type(IntWrapperType()).name(), IntWrapperType::kName);
}
TEST(IntWrapperType, DebugString) {
{
std::ostringstream out;
out << IntWrapperType();
EXPECT_EQ(out.str(), IntWrapperType::kName);
}
{
std::ostringstream out;
out << Type(IntWrapperType());
EXPECT_EQ(out.str(), IntWrapperType::kName);
}
}
TEST(IntWrapperType, Hash) {
EXPECT_EQ(absl::HashOf(IntWrapperType()), absl::HashOf(IntWrapperType()));
}
TEST(IntWrapperType, Equal) {
EXPECT_EQ(IntWrapperType(), IntWrapperType());
EXPECT_EQ(Type(IntWrapperType()), IntWrapperType());
EXPECT_EQ(IntWrapperType(), Type(IntWrapperType()));
EXPECT_EQ(Type(IntWrapperType()), Type(IntWrapperType()));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/int_wrapper_type.h | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/types/int_wrapper_type_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
90913fc5-ee46-4fb6-91db-f159b0b8b5f7 | cpp | google/quiche | nghttp2_adapter | quiche/http2/adapter/nghttp2_adapter.cc | quiche/http2/adapter/nghttp2_adapter_test.cc | #include "quiche/http2/adapter/nghttp2_adapter.h"
#include <cstring>
#include <iterator>
#include <memory>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/http2/adapter/nghttp2_callbacks.h"
#include "quiche/http2/adapter/nghttp2_data_provider.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_endian.h"
namespace http2 {
namespace adapter {
namespace {
using ConnectionError = Http2VisitorInterface::ConnectionError;
const size_t kFrameHeaderSize = 9;
ssize_t DataFrameReadCallback(nghttp2_session* , int32_t stream_id,
uint8_t* , size_t length,
uint32_t* data_flags, nghttp2_data_source* source,
void* ) {
NgHttp2Adapter* adapter = reinterpret_cast<NgHttp2Adapter*>(source->ptr);
return adapter->DelegateReadCallback(stream_id, length, data_flags);
}
int DataFrameSendCallback(nghttp2_session* , nghttp2_frame* frame,
const uint8_t* framehd, size_t length,
nghttp2_data_source* source, void* ) {
NgHttp2Adapter* adapter = reinterpret_cast<NgHttp2Adapter*>(source->ptr);
return adapter->DelegateSendCallback(frame->hd.stream_id, framehd, length);
}
}
class NgHttp2Adapter::NotifyingMetadataSource : public MetadataSource {
public:
explicit NotifyingMetadataSource(NgHttp2Adapter* adapter,
Http2StreamId stream_id,
std::unique_ptr<MetadataSource> source)
: adapter_(adapter), stream_id_(stream_id), source_(std::move(source)) {}
size_t NumFrames(size_t max_frame_size) const override {
return source_->NumFrames(max_frame_size);
}
std::pair<int64_t, bool> Pack(uint8_t* dest, size_t dest_len) override {
const auto result = source_->Pack(dest, dest_len);
if (result.first < 0 || result.second) {
adapter_->RemovePendingMetadata(stream_id_);
}
return result;
}
void OnFailure() override {
source_->OnFailure();
adapter_->RemovePendingMetadata(stream_id_);
}
private:
NgHttp2Adapter* const adapter_;
const Http2StreamId stream_id_;
std::unique_ptr<MetadataSource> source_;
};
class NgHttp2Adapter::NotifyingVisitorMetadataSource : public MetadataSource {
public:
explicit NotifyingVisitorMetadataSource(NgHttp2Adapter* adapter,
Http2StreamId stream_id,
Http2VisitorInterface& visitor)
: adapter_(adapter), stream_id_(stream_id), visitor_(visitor) {}
size_t NumFrames(size_t ) const override {
QUICHE_LOG(DFATAL) << "Should not be invoked.";
return 0;
}
std::pair<int64_t, bool> Pack(uint8_t* dest, size_t dest_len) override {
const auto [packed, end_metadata] =
visitor_.PackMetadataForStream(stream_id_, dest, dest_len);
if (packed < 0 || end_metadata) {
adapter_->RemovePendingMetadata(stream_id_);
}
return {packed, end_metadata};
}
void OnFailure() override { adapter_->RemovePendingMetadata(stream_id_); }
private:
NgHttp2Adapter* const adapter_;
const Http2StreamId stream_id_;
Http2VisitorInterface& visitor_;
};
std::unique_ptr<NgHttp2Adapter> NgHttp2Adapter::CreateClientAdapter(
Http2VisitorInterface& visitor, const nghttp2_option* options) {
auto adapter = new NgHttp2Adapter(visitor, Perspective::kClient, options);
adapter->Initialize();
return absl::WrapUnique(adapter);
}
std::unique_ptr<NgHttp2Adapter> NgHttp2Adapter::CreateServerAdapter(
Http2VisitorInterface& visitor, const nghttp2_option* options) {
auto adapter = new NgHttp2Adapter(visitor, Perspective::kServer, options);
adapter->Initialize();
return absl::WrapUnique(adapter);
}
bool NgHttp2Adapter::IsServerSession() const {
int result = nghttp2_session_check_server_session(session_->raw_ptr());
QUICHE_DCHECK_EQ(perspective_ == Perspective::kServer, result > 0);
return result > 0;
}
int64_t NgHttp2Adapter::ProcessBytes(absl::string_view bytes) {
const int64_t processed_bytes = session_->ProcessBytes(bytes);
if (processed_bytes < 0) {
visitor_.OnConnectionError(ConnectionError::kParseError);
}
return processed_bytes;
}
void NgHttp2Adapter::SubmitSettings(absl::Span<const Http2Setting> settings) {
std::vector<nghttp2_settings_entry> nghttp2_settings;
absl::c_transform(settings, std::back_inserter(nghttp2_settings),
[](const Http2Setting& setting) {
return nghttp2_settings_entry{setting.id, setting.value};
});
nghttp2_submit_settings(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
nghttp2_settings.data(), nghttp2_settings.size());
}
void NgHttp2Adapter::SubmitPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id,
int weight, bool exclusive) {
nghttp2_priority_spec priority_spec;
nghttp2_priority_spec_init(&priority_spec, parent_stream_id, weight,
static_cast<int>(exclusive));
nghttp2_submit_priority(session_->raw_ptr(), NGHTTP2_FLAG_NONE, stream_id,
&priority_spec);
}
void NgHttp2Adapter::SubmitPing(Http2PingId ping_id) {
uint8_t opaque_data[8] = {};
Http2PingId ping_id_to_serialize = quiche::QuicheEndian::HostToNet64(ping_id);
std::memcpy(opaque_data, &ping_id_to_serialize, sizeof(Http2PingId));
nghttp2_submit_ping(session_->raw_ptr(), NGHTTP2_FLAG_NONE, opaque_data);
}
void NgHttp2Adapter::SubmitShutdownNotice() {
nghttp2_submit_shutdown_notice(session_->raw_ptr());
}
void NgHttp2Adapter::SubmitGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) {
nghttp2_submit_goaway(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
last_accepted_stream_id,
static_cast<uint32_t>(error_code),
ToUint8Ptr(opaque_data.data()), opaque_data.size());
}
void NgHttp2Adapter::SubmitWindowUpdate(Http2StreamId stream_id,
int window_increment) {
nghttp2_submit_window_update(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
stream_id, window_increment);
}
void NgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,
size_t max_frame_size,
std::unique_ptr<MetadataSource> source) {
auto wrapped_source = std::make_unique<NotifyingMetadataSource>(
this, stream_id, std::move(source));
const size_t num_frames = wrapped_source->NumFrames(max_frame_size);
size_t num_successes = 0;
for (size_t i = 1; i <= num_frames; ++i) {
const int result =
nghttp2_submit_extension(session_->raw_ptr(), kMetadataFrameType,
i == num_frames ? kMetadataEndFlag : 0,
stream_id, wrapped_source.get());
if (result != 0) {
QUICHE_LOG(DFATAL) << "Failed to submit extension frame " << i << " of "
<< num_frames;
break;
}
++num_successes;
}
if (num_successes > 0) {
auto [it, _] = stream_metadata_.insert({stream_id, MetadataSourceVec{}});
it->second.push_back(std::move(wrapped_source));
}
}
void NgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,
size_t num_frames) {
auto wrapped_source = std::make_unique<NotifyingVisitorMetadataSource>(
this, stream_id, visitor_);
size_t num_successes = 0;
for (size_t i = 1; i <= num_frames; ++i) {
const int result =
nghttp2_submit_extension(session_->raw_ptr(), kMetadataFrameType,
i == num_frames ? kMetadataEndFlag : 0,
stream_id, wrapped_source.get());
if (result != 0) {
QUICHE_LOG(DFATAL) << "Failed to submit extension frame " << i << " of "
<< num_frames;
break;
}
++num_successes;
}
if (num_successes > 0) {
auto [it, _] = stream_metadata_.insert({stream_id, MetadataSourceVec{}});
it->second.push_back(std::move(wrapped_source));
}
}
int NgHttp2Adapter::Send() {
const int result = nghttp2_session_send(session_->raw_ptr());
if (result != 0) {
QUICHE_VLOG(1) << "nghttp2_session_send returned " << result;
visitor_.OnConnectionError(ConnectionError::kSendError);
}
return result;
}
int NgHttp2Adapter::GetSendWindowSize() const {
return session_->GetRemoteWindowSize();
}
int NgHttp2Adapter::GetStreamSendWindowSize(Http2StreamId stream_id) const {
return nghttp2_session_get_stream_remote_window_size(session_->raw_ptr(),
stream_id);
}
int NgHttp2Adapter::GetStreamReceiveWindowLimit(Http2StreamId stream_id) const {
return nghttp2_session_get_stream_effective_local_window_size(
session_->raw_ptr(), stream_id);
}
int NgHttp2Adapter::GetStreamReceiveWindowSize(Http2StreamId stream_id) const {
return nghttp2_session_get_stream_local_window_size(session_->raw_ptr(),
stream_id);
}
int NgHttp2Adapter::GetReceiveWindowSize() const {
return nghttp2_session_get_local_window_size(session_->raw_ptr());
}
int NgHttp2Adapter::GetHpackEncoderDynamicTableSize() const {
return nghttp2_session_get_hd_deflate_dynamic_table_size(session_->raw_ptr());
}
int NgHttp2Adapter::GetHpackDecoderDynamicTableSize() const {
return nghttp2_session_get_hd_inflate_dynamic_table_size(session_->raw_ptr());
}
Http2StreamId NgHttp2Adapter::GetHighestReceivedStreamId() const {
return nghttp2_session_get_last_proc_stream_id(session_->raw_ptr());
}
void NgHttp2Adapter::MarkDataConsumedForStream(Http2StreamId stream_id,
size_t num_bytes) {
int rc = session_->Consume(stream_id, num_bytes);
if (rc != 0) {
QUICHE_LOG(ERROR) << "Error " << rc << " marking " << num_bytes
<< " bytes consumed for stream " << stream_id;
}
}
void NgHttp2Adapter::SubmitRst(Http2StreamId stream_id,
Http2ErrorCode error_code) {
int status =
nghttp2_submit_rst_stream(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
stream_id, static_cast<uint32_t>(error_code));
if (status < 0) {
QUICHE_LOG(WARNING) << "Reset stream failed: " << stream_id
<< " with status code " << status;
}
}
int32_t NgHttp2Adapter::SubmitRequest(
absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source, bool end_stream,
void* stream_user_data) {
auto nvs = GetNghttp2Nvs(headers);
std::unique_ptr<nghttp2_data_provider> provider;
if (data_source != nullptr || !end_stream) {
provider = std::make_unique<nghttp2_data_provider>();
provider->source.ptr = this;
provider->read_callback = &DataFrameReadCallback;
}
int32_t stream_id =
nghttp2_submit_request(session_->raw_ptr(), nullptr, nvs.data(),
nvs.size(), provider.get(), stream_user_data);
if (data_source != nullptr) {
sources_.emplace(stream_id, std::move(data_source));
}
QUICHE_VLOG(1) << "Submitted request with " << nvs.size()
<< " request headers and user data " << stream_user_data
<< "; resulted in stream " << stream_id;
return stream_id;
}
int NgHttp2Adapter::SubmitResponse(Http2StreamId stream_id,
absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream) {
auto nvs = GetNghttp2Nvs(headers);
std::unique_ptr<nghttp2_data_provider> provider;
if (data_source != nullptr || !end_stream) {
provider = std::make_unique<nghttp2_data_provider>();
provider->source.ptr = this;
provider->read_callback = &DataFrameReadCallback;
}
if (data_source != nullptr) {
sources_.emplace(stream_id, std::move(data_source));
}
int result = nghttp2_submit_response(session_->raw_ptr(), stream_id,
nvs.data(), nvs.size(), provider.get());
QUICHE_VLOG(1) << "Submitted response with " << nvs.size()
<< " response headers; result = " << result;
return result;
}
int NgHttp2Adapter::SubmitTrailer(Http2StreamId stream_id,
absl::Span<const Header> trailers) {
auto nvs = GetNghttp2Nvs(trailers);
int result = nghttp2_submit_trailer(session_->raw_ptr(), stream_id,
nvs.data(), nvs.size());
QUICHE_VLOG(1) << "Submitted trailers with " << nvs.size()
<< " response trailers; result = " << result;
return result;
}
void NgHttp2Adapter::SetStreamUserData(Http2StreamId stream_id,
void* stream_user_data) {
nghttp2_session_set_stream_user_data(session_->raw_ptr(), stream_id,
stream_user_data);
}
void* NgHttp2Adapter::GetStreamUserData(Http2StreamId stream_id) {
return nghttp2_session_get_stream_user_data(session_->raw_ptr(), stream_id);
}
bool NgHttp2Adapter::ResumeStream(Http2StreamId stream_id) {
return 0 == nghttp2_session_resume_data(session_->raw_ptr(), stream_id);
}
void NgHttp2Adapter::FrameNotSent(Http2StreamId stream_id, uint8_t frame_type) {
if (frame_type == kMetadataFrameType) {
RemovePendingMetadata(stream_id);
}
}
void NgHttp2Adapter::RemoveStream(Http2StreamId stream_id) {
sources_.erase(stream_id);
}
ssize_t NgHttp2Adapter::DelegateReadCallback(int32_t stream_id,
size_t max_length,
uint32_t* data_flags) {
auto it = sources_.find(stream_id);
if (it == sources_.end()) {
return callbacks::VisitorReadCallback(visitor_, stream_id, max_length,
data_flags);
} else {
return callbacks::DataFrameSourceReadCallback(*it->second, max_length,
data_flags);
}
}
int NgHttp2Adapter::DelegateSendCallback(int32_t stream_id,
const uint8_t* framehd,
size_t length) {
auto it = sources_.find(stream_id);
if (it == sources_.end()) {
visitor_.SendDataFrame(stream_id, ToStringView(framehd, kFrameHeaderSize),
length);
} else {
it->second->Send(ToStringView(framehd, kFrameHeaderSize), length);
}
return 0;
}
NgHttp2Adapter::NgHttp2Adapter(Http2VisitorInterface& visitor,
Perspective perspective,
const nghttp2_option* options)
: Http2Adapter(visitor),
visitor_(visitor),
options_(options),
perspective_(perspective) {}
NgHttp2Adapter::~NgHttp2Adapter() {}
void NgHttp2Adapter::Initialize() {
nghttp2_option* owned_options = nullptr;
if (options_ == nullptr) {
nghttp2_option_new(&owned_options);
nghttp2_option_set_no_closed_streams(owned_options, 1);
nghttp2_option_set_no_auto_window_update(owned_options, 1);
nghttp2_option_set_max_send_header_block_length(owned_options, 0x2000000);
nghttp2_option_set_max_outbound_ack(owned_options, 10000);
nghttp2_option_set_user_recv_extension_type(owned_options,
kMetadataFrameType);
options_ = owned_options;
}
session_ = std::make_unique<NgHttp2Session>(
perspective_, callbacks::Create(&DataFrameSendCallback), options_,
static_cast<void*>(&visitor_));
if (owned_options != nullptr) {
nghttp2_option_del(owned_options);
}
options_ = nullptr;
}
void NgHttp2Adapter::RemovePendingMetadata(Http2StreamId stream_id) {
auto it = stream_metadata_.find(stream_id);
if (it != stream_metadata_.end()) {
it->second.erase(it->second.begin());
if (it->second.empty()) {
stream_metadata_.erase(it);
}
}
}
}
} | #include "quiche/http2/adapter/nghttp2_adapter.h"
#include <memory>
#include <string>
#include <vector>
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/mock_http2_visitor.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/http2/adapter/nghttp2_test_utils.h"
#include "quiche/http2/adapter/oghttp2_util.h"
#include "quiche/http2/adapter/test_frame_sequence.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using ConnectionError = Http2VisitorInterface::ConnectionError;
using spdy::SpdyFrameType;
using testing::_;
enum FrameType {
DATA,
HEADERS,
PRIORITY,
RST_STREAM,
SETTINGS,
PUSH_PROMISE,
PING,
GOAWAY,
WINDOW_UPDATE,
CONTINUATION,
};
int TestSendCallback(nghttp2_session*, nghttp2_frame* ,
const uint8_t* framehd, size_t length,
nghttp2_data_source* source, void* user_data) {
auto* visitor = static_cast<Http2VisitorInterface*>(user_data);
ssize_t result = visitor->OnReadyToSend(ToStringView(framehd, 9));
if (result == 0) {
return NGHTTP2_ERR_WOULDBLOCK;
}
auto* test_source = static_cast<TestDataSource*>(source->ptr);
absl::string_view payload = test_source->ReadNext(length);
visitor->OnReadyToSend(payload);
return 0;
}
TEST(NgHttp2AdapterTest, ClientConstruction) {
testing::StrictMock<MockHttp2Visitor> visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
ASSERT_NE(nullptr, adapter);
EXPECT_TRUE(adapter->want_read());
EXPECT_FALSE(adapter->want_write());
EXPECT_FALSE(adapter->IsServerSession());
}
TEST(NgHttp2AdapterTest, ClientHandlesFrames) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));
visitor.Clear();
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
const std::string initial_frames = TestFrameSequence()
.ServerPreface()
.Ping(42)
.WindowUpdate(0, 1000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 1000));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_EQ(adapter->GetSendWindowSize(), kInitialFlowControlWindowSize + 1000);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING}));
visitor.Clear();
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const std::vector<Header> headers3 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/three"}});
const char* kSentinel1 = "arbitrary pointer 1";
const char* kSentinel3 = "arbitrary pointer 3";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
const int32_t stream_id2 =
adapter->SubmitRequest(headers2, nullptr, true, nullptr);
ASSERT_GT(stream_id2, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id2;
const int32_t stream_id3 = adapter->SubmitRequest(
headers3, nullptr, true, const_cast<char*>(kSentinel3));
ASSERT_GT(stream_id3, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id3;
const char* kSentinel2 = "arbitrary pointer 2";
adapter->SetStreamUserData(stream_id2, const_cast<char*>(kSentinel2));
adapter->SetStreamUserData(stream_id3, nullptr);
EXPECT_EQ(adapter->sources_size(), 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id3, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id3, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::HEADERS,
SpdyFrameType::HEADERS}));
visitor.Clear();
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id1));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id2));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id3));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowLimit(stream_id1));
EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetReceiveWindowSize());
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(stream_id1));
EXPECT_EQ(kSentinel2, adapter->GetStreamUserData(stream_id2));
EXPECT_EQ(nullptr, adapter->GetStreamUserData(stream_id3));
EXPECT_EQ(0, adapter->GetHpackDecoderDynamicTableSize());
const std::string stream_frames =
TestFrameSequence()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.RstStream(3, Http2ErrorCode::INTERNAL_ERROR)
.GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 26));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body."));
EXPECT_CALL(visitor, OnFrameHeader(3, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR))
.WillOnce(
[&adapter](Http2StreamId stream_id, Http2ErrorCode ) {
adapter->RemoveStream(stream_id);
return true;
});
EXPECT_CALL(visitor, OnFrameHeader(0, 19, GOAWAY, 0));
EXPECT_CALL(visitor,
OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!"));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_GT(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id1));
EXPECT_EQ(-1, adapter->GetStreamReceiveWindowSize(stream_id2));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id3));
EXPECT_EQ(adapter->GetReceiveWindowSize(),
adapter->GetStreamReceiveWindowSize(stream_id1));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowLimit(stream_id1));
EXPECT_GT(adapter->GetHpackDecoderDynamicTableSize(), 0);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_read());
EXPECT_CALL(visitor, OnFrameHeader(1, 0, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 0));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR))
.WillOnce(
[&adapter](Http2StreamId stream_id, Http2ErrorCode ) {
adapter->RemoveStream(stream_id);
return true;
});
EXPECT_CALL(visitor, OnFrameHeader(5, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(5, Http2ErrorCode::REFUSED_STREAM));
EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM))
.WillOnce(
[&adapter](Http2StreamId stream_id, Http2ErrorCode ) {
adapter->RemoveStream(stream_id);
return true;
});
adapter->ProcessBytes(TestFrameSequence()
.Data(1, "", true)
.RstStream(5, Http2ErrorCode::REFUSED_STREAM)
.Serialize());
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_FALSE(adapter->want_read());
EXPECT_FALSE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
}
TEST(NgHttp2AdapterTest, QueuingWindowUpdateAffectsWindow) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize);
adapter->SubmitWindowUpdate(0, 10000);
EXPECT_EQ(adapter->GetReceiveWindowSize(),
kInitialFlowControlWindowSize + 10000);
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),
kInitialFlowControlWindowSize);
adapter->SubmitWindowUpdate(1, 20000);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),
kInitialFlowControlWindowSize + 20000);
}
TEST(NgHttp2AdapterTest, AckOfSettingInitialWindowSizeAffectsWindow) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
int64_t parse_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(parse_result));
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1),
kInitialFlowControlWindowSize);
adapter->SubmitSettings({{INITIAL_WINDOW_SIZE, 80000u}});
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1),
kInitialFlowControlWindowSize);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1),
kInitialFlowControlWindowSize);
const std::string settings_ack =
TestFrameSequence().SettingsAck().Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck);
parse_result = adapter->ProcessBytes(settings_ack);
EXPECT_EQ(settings_ack.size(), static_cast<size_t>(parse_result));
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), 80000);
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const int32_t stream_id2 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id2), 80000);
}
TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithFin) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "100"}}, false)
.Headers(1, {{":status", "100"}}, true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(visitor,
OnInvalidFrame(
1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, 1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithContent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "100"}},
false)
.Data(1, "We needed the final headers before data, whoops")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithContentLength) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "100"}, {"content-length", "42"}},
false)
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [content-length], value: [42]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
class ResponseCompleteBeforeRequestTest
: public quiche::test::QuicheTestWithParam<std::tuple<bool, bool>> {
public:
bool HasTrailers() const { return std::get<0>(GetParam()); }
bool HasRstStream() const { return std::get<1>(GetParam()); }
};
INSTANTIATE_TEST_SUITE_P(TrailersAndRstStreamAllCombinations,
ResponseCompleteBeforeRequestTest,
testing::Combine(testing::Bool(), testing::Bool()));
TEST_P(ResponseCompleteBeforeRequestTest,
ClientHandlesResponseBeforeRequestComplete) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
adapter->SubmitSettings({});
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, std::move(body1), false, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor,
OnBeforeFrameSent(HEADERS, stream_id1, _, END_HEADERS_FLAG));
EXPECT_CALL(visitor,
OnFrameSent(HEADERS, stream_id1, _, END_HEADERS_FLAG, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
TestFrameSequence response;
response.ServerPreface()
.Headers(1, {{":status", "200"}, {"content-length", "2"}},
false)
.Data(1, "hi", !HasTrailers(), 10);
if (HasTrailers()) {
response.Headers(1, {{"my-weird-trailer", "has a value"}}, true);
}
if (HasRstStream()) {
response.RstStream(1, Http2ErrorCode::HTTP2_NO_ERROR);
}
const std::string stream_frames = response.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor,
OnFrameHeader(1, 2 + 10, DATA, HasTrailers() ? 0x8 : 0x9));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 2 + 10));
EXPECT_CALL(visitor, OnDataForStream(1, "hi"));
EXPECT_CALL(visitor, OnDataPaddingLength(1, 10));
if (HasTrailers()) {
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "my-weird-trailer", "has a value"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
}
EXPECT_CALL(visitor, OnEndStream(1));
if (HasRstStream()) {
EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
}
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({
SpdyFrameType::SETTINGS,
}));
if (!HasRstStream()) {
visitor.AppendPayloadForStream(1, "final fragment");
}
visitor.SetEndData(1, true);
adapter->ResumeStream(1);
if (!HasRstStream()) {
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, END_STREAM_FLAG, 0));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
}
result = adapter->Send();
EXPECT_EQ(0, result);
}
TEST(NgHttp2AdapterTest, ClientHandles204WithContent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const int32_t stream_id2 =
adapter->SubmitRequest(headers2, nullptr, true, nullptr);
ASSERT_GT(stream_id2, stream_id1);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "204"}, {"content-length", "2"}},
false)
.Data(1, "hi")
.Headers(3, {{":status", "204"}}, false)
.Data(3, "hi")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "204"));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [content-length], value: [2]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":status", "204"));
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnFrameHeader(3, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(3, 2));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientHandles304WithContent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "304"}, {"content-length", "2"}},
false)
.Data(1, "hi")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 2));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientHandles304WithContentLength) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
ASSERT_GT(stream_id, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "304"}, {"content-length", "2"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientHandlesTrailers) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.Headers(1, {{"final-status", "A-OK"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 26));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body."));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, "final-status", "A-OK"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
class NgHttp2AdapterDataTest : public quiche::test::QuicheTestWithParam<bool> {
};
INSTANTIATE_TEST_SUITE_P(BothValues, NgHttp2AdapterDataTest, testing::Bool());
TEST_P(NgHttp2AdapterDataTest, ClientSendsTrailers) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const Http2StreamId kStreamId = 1;
const std::string kBody = "This is an example request body.";
visitor.AppendPayloadForStream(kStreamId, kBody);
visitor.SetEndData(kStreamId, false);
auto body1 = std::make_unique<VisitorDataSource>(visitor, kStreamId);
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, GetParam() ? nullptr : std::move(body1), false, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_EQ(stream_id1, kStreamId);
EXPECT_EQ(adapter->sources_size(), GetParam() ? 0 : 1);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id1, _, 0x0, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data,
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA}));
visitor.Clear();
const std::vector<Header> trailers1 =
ToHeaders({{"extra-info", "Trailers are weird but good?"}});
adapter->SubmitTrailer(stream_id1, trailers1);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
data = visitor.data();
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
}
TEST(NgHttp2AdapterTest, ClientHandlesMetadata) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Metadata(0, "Example connection metadata")
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Metadata(1, "Example stream metadata")
.Data(1, "This is the response body.", true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _));
EXPECT_CALL(visitor, OnMetadataForStream(0, _));
EXPECT_CALL(visitor, OnMetadataEndForStream(0));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataEndForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 26));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body."));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientHandlesMetadataWithEmptyPayload) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Metadata(1, "")
.Data(1, "This is the response body.", true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(3);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataEndForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body."));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
}
TEST(NgHttp2AdapterTest, ClientHandlesMetadataWithError) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Metadata(0, "Example connection metadata")
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Metadata(1, "Example stream metadata")
.Data(1, "This is the response body.", true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _));
EXPECT_CALL(visitor, OnMetadataForStream(0, _));
EXPECT_CALL(visitor, OnMetadataEndForStream(0));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataForStream(1, _))
.WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_result, NGHTTP2_ERR_CALLBACK_FAILURE);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
EXPECT_TRUE(adapter->want_read());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientHandlesHpackHeaderTableSetting) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 = ToHeaders({
{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"x-i-do-not-like", "green eggs and ham"},
{"x-i-will-not-eat-them", "here or there, in a box, with a fox"},
{"x-like-them-in-a-house", "no"},
{"x-like-them-with-a-mouse", "no"},
});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 100);
const std::string stream_frames =
TestFrameSequence().Settings({{HEADER_TABLE_SIZE, 100u}}).Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{HEADER_TABLE_SIZE, 100u}));
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_LE(adapter->GetHpackEncoderDynamicTableSize(), 100);
}
TEST(NgHttp2AdapterTest, ClientHandlesInvalidTrailers) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.Headers(1, {{":bad-status", "9000"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 26));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body."));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [:bad-status], value: [9000]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id1, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id1, 4, 0x0, 1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientRstStreamWhileHandlingHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"))
.WillOnce(testing::DoAll(
testing::InvokeWithoutArgs([&adapter]() {
adapter->SubmitRst(1, Http2ErrorCode::REFUSED_STREAM);
}),
testing::Return(Http2VisitorInterface::HEADER_RST_STREAM)));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id1, 4, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, stream_id1, 4, 0x0,
static_cast<int>(Http2ErrorCode::REFUSED_STREAM)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientConnectionErrorWhileHandlingHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"))
.WillOnce(
testing::Return(Http2VisitorInterface::HEADER_CONNECTION_ERROR));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(-902 , stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientConnectionErrorWhileHandlingHeadersOnly) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"))
.WillOnce(
testing::Return(Http2VisitorInterface::HEADER_CONNECTION_ERROR));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(-902 , stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientRejectsHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1))
.WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientStartsShutdown) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
adapter->SubmitShutdownNotice();
EXPECT_FALSE(adapter->want_write());
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(visitor.data(), spdy::kHttp2ConnectionHeaderPrefix);
}
TEST(NgHttp2AdapterTest, ClientReceivesGoAway) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const int32_t stream_id2 =
adapter->SubmitRequest(headers2, nullptr, true, nullptr);
ASSERT_GT(stream_id2, stream_id1);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data,
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::HEADERS}));
visitor.Clear();
adapter->SubmitWindowUpdate(3, 42);
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.RstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM)
.GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion")
.WindowUpdate(0, 42)
.WindowUpdate(1, 42)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM));
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor,
OnGoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion"));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 42));
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientReceivesMultipleGoAways) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string initial_frames =
TestFrameSequence()
.ServerPreface()
.GoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor, OnGoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR,
"indigestion"));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result));
adapter->SubmitWindowUpdate(1, 42);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::WINDOW_UPDATE}));
visitor.Clear();
const std::string final_frames =
TestFrameSequence()
.GoAway(0, Http2ErrorCode::INTERNAL_ERROR, "indigestion")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor,
OnGoAway(0, Http2ErrorCode::INTERNAL_ERROR, "indigestion"));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM));
const int64_t final_result = adapter->ProcessBytes(final_frames);
EXPECT_EQ(final_frames.size(), static_cast<size_t>(final_result));
EXPECT_FALSE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
}
TEST(NgHttp2AdapterTest, ClientReceivesMultipleGoAwaysWithIncreasingStreamId) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})));
adapter->SubmitMetadata(stream_id1, 16384u, std::move(source));
const std::string frames =
TestFrameSequence()
.ServerPreface()
.GoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "")
.GoAway(0, Http2ErrorCode::ENHANCE_YOUR_CALM, "")
.GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, ""));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM));
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::ENHANCE_YOUR_CALM, ""));
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(
visitor,
OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));
const int64_t frames_result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(frames_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ClientReceivesGoAwayWithPendingStreams) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));
visitor.Clear();
testing::InSequence s;
const std::string initial_frames =
TestFrameSequence()
.ServerPreface({{MAX_CONCURRENT_STREAMS, 1}})
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting);
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const int32_t stream_id2 =
adapter->SubmitRequest(headers2, nullptr, true, nullptr);
ASSERT_GT(stream_id2, stream_id1);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.GoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion")
.Settings({{MAX_CONCURRENT_STREAMS, 42u}})
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor, OnGoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR,
"indigestion"));
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{MAX_CONCURRENT_STREAMS, 42u}));
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::vector<Header> headers3 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/three"}});
const int32_t stream_id3 =
adapter->SubmitRequest(headers3, nullptr, true, nullptr);
ASSERT_GT(stream_id3, stream_id2);
EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ClientFailsOnGoAway) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion")
.Data(1, "This is the response body.")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor,
OnGoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion"))
.WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientRejects101Response) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"upgrade", "new-protocol"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "101"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [:status], value: [101]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(static_cast<int64_t>(stream_frames.size()), stream_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(RST_STREAM, 1, 4, 0x0,
static_cast<uint32_t>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST_P(NgHttp2AdapterDataTest, ClientSubmitRequest) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));
visitor.Clear();
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
EXPECT_EQ(0, adapter->GetHpackEncoderDynamicTableSize());
EXPECT_FALSE(adapter->want_write());
const char* kSentinel = "";
const absl::string_view kBody = "This is an example request body.";
visitor.AppendPayloadForStream(1, kBody);
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
GetParam() ? nullptr : std::move(body1), false,
const_cast<char*>(kSentinel));
ASSERT_EQ(1, stream_id);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id));
EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetReceiveWindowSize());
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowLimit(stream_id));
EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 0);
EXPECT_LT(adapter->GetStreamSendWindowSize(stream_id),
kInitialFlowControlWindowSize);
EXPECT_GT(adapter->GetStreamSendWindowSize(stream_id), 0);
EXPECT_EQ(-1, adapter->GetStreamSendWindowSize(stream_id + 2));
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA}));
EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
nullptr, true, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
const char* kSentinel2 = "arbitrary pointer 2";
EXPECT_EQ(nullptr, adapter->GetStreamUserData(stream_id));
adapter->SetStreamUserData(stream_id, const_cast<char*>(kSentinel2));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
EXPECT_EQ(kSentinel2, adapter->GetStreamUserData(stream_id));
EXPECT_EQ(adapter->GetStreamSendWindowSize(stream_id),
kInitialFlowControlWindowSize);
}
TEST(NgHttp2AdapterTest, ClientSubmitRequestWithDataProvider) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));
visitor.Clear();
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
const absl::string_view kBody = "This is an example request body.";
TestDataSource body1{kBody};
nghttp2_data_provider provider = body1.MakeDataProvider();
nghttp2_send_data_callback send_callback = &TestSendCallback;
std::unique_ptr<DataFrameSource> frame_source =
MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback));
int stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(frame_source), false, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA}));
EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody));
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ClientSubmitRequestWithDataProviderAndReadBlock) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const absl::string_view kBody = "This is an example request body.";
TestDataSource body1{kBody};
body1.set_is_data_available(false);
nghttp2_data_provider provider = body1.MakeDataProvider();
nghttp2_send_data_callback send_callback = &TestSendCallback;
std::unique_ptr<DataFrameSource> frame_source =
MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback));
int stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(frame_source), false, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
body1.set_is_data_available(true);
EXPECT_TRUE(adapter->ResumeStream(stream_id));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA}));
EXPECT_FALSE(adapter->want_write());
EXPECT_FALSE(adapter->ResumeStream(stream_id));
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ClientSubmitRequestEmptyDataWithFin) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const absl::string_view kEmptyBody = "";
TestDataSource body1{kEmptyBody};
body1.set_is_data_available(false);
nghttp2_data_provider provider = body1.MakeDataProvider();
nghttp2_send_data_callback send_callback = &TestSendCallback;
std::unique_ptr<DataFrameSource> frame_source =
MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback));
int stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(frame_source), false, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
body1.set_is_data_available(true);
EXPECT_TRUE(adapter->ResumeStream(stream_id));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 0, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA}));
EXPECT_FALSE(adapter->want_write());
EXPECT_FALSE(adapter->ResumeStream(stream_id));
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ClientSubmitRequestWithDataProviderAndWriteBlock) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const absl::string_view kBody = "This is an example request body.";
TestDataSource body1{kBody};
nghttp2_data_provider provider = body1.MakeDataProvider();
nghttp2_send_data_callback send_callback = &TestSendCallback;
std::unique_ptr<DataFrameSource> frame_source =
MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback));
int stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(frame_source), false, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
visitor.set_is_write_blocked(true);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
visitor.set_is_write_blocked(false);
result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA}));
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ClientReceivesDataOnClosedStream) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));
visitor.Clear();
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
int stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
nullptr, true, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
adapter->SubmitRst(stream_id, Http2ErrorCode::CANCEL);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id, _, 0x0,
static_cast<int>(Http2ErrorCode::CANCEL)));
EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::CANCEL));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM}));
visitor.Clear();
const std::string response_frames =
TestFrameSequence()
.Headers(stream_id,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(stream_id, "This is the response body.", true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 0x4));
EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, DATA, _)).Times(0);
const int64_t response_result = adapter->ProcessBytes(response_frames);
EXPECT_EQ(response_frames.size(), response_result);
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ClientQueuesRequests) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
adapter->SubmitSettings({});
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
adapter->Send();
const std::string initial_frames =
TestFrameSequence()
.ServerPreface({{MAX_CONCURRENT_STREAMS, 2}})
.SettingsAck()
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0x0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{
Http2KnownSettingsId::MAX_CONCURRENT_STREAMS, 2u}));
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck());
adapter->ProcessBytes(initial_frames);
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/example/request"}});
std::vector<int32_t> stream_ids;
int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr);
stream_ids.push_back(stream_id);
stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr);
stream_ids.push_back(stream_id);
stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr);
stream_ids.push_back(stream_id);
stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr);
stream_ids.push_back(stream_id);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[0], _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[0], _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[1], _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[1], _, 0x5, 0));
adapter->Send();
const std::string update_streams =
TestFrameSequence().Settings({{MAX_CONCURRENT_STREAMS, 5}}).Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0x0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{
Http2KnownSettingsId::MAX_CONCURRENT_STREAMS, 5u}));
EXPECT_CALL(visitor, OnSettingsEnd());
adapter->ProcessBytes(update_streams);
stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr);
stream_ids.push_back(stream_id);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[2], _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[2], _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[3], _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[3], _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[4], _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[4], _, 0x5, 0));
adapter->Send();
}
TEST(NgHttp2AdapterTest, ClientAcceptsHeadResponseWithContentLength) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const std::vector<Header> headers = ToHeaders({{":method", "HEAD"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
testing::InSequence s;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
adapter->Send();
const std::string initial_frames =
TestFrameSequence()
.ServerPreface()
.Headers(stream_id, {{":status", "200"}, {"content-length", "101"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, _, SETTINGS, 0x0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnHeaderForStream).Times(2);
EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnEndStream(stream_id));
EXPECT_CALL(visitor,
OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR));
adapter->ProcessBytes(initial_frames);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
adapter->Send();
}
class MetadataApiTest : public quiche::test::QuicheTestWithParam<bool> {};
INSTANTIATE_TEST_SUITE_P(WithAndWithoutNewApi, MetadataApiTest,
testing::Bool());
TEST_P(MetadataApiTest, SubmitMetadata) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}));
if (GetParam()) {
visitor.AppendMetadataForStream(1, block);
adapter->SubmitMetadata(1, 1);
} else {
auto source = std::make_unique<TestMetadataSource>(block);
adapter->SubmitMetadata(1, 16384u, std::move(source));
}
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({static_cast<SpdyFrameType>(kMetadataFrameType)}));
EXPECT_FALSE(adapter->want_write());
}
size_t DivRoundUp(size_t numerator, size_t denominator) {
return numerator / denominator + (numerator % denominator == 0 ? 0 : 1);
}
TEST_P(MetadataApiTest, SubmitMetadataMultipleFrames) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const auto kLargeValue = std::string(63 * 1024, 'a');
const quiche::HttpHeaderBlock block =
ToHeaderBlock(ToHeaders({{"large-value", kLargeValue}}));
if (GetParam()) {
visitor.AppendMetadataForStream(1, block);
adapter->SubmitMetadata(1, DivRoundUp(kLargeValue.size(), 16384u));
} else {
auto source = std::make_unique<TestMetadataSource>(block);
adapter->SubmitMetadata(1, 16384u, std::move(source));
}
EXPECT_TRUE(adapter->want_write());
testing::InSequence seq;
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({static_cast<SpdyFrameType>(kMetadataFrameType),
static_cast<SpdyFrameType>(kMetadataFrameType),
static_cast<SpdyFrameType>(kMetadataFrameType),
static_cast<SpdyFrameType>(kMetadataFrameType)}));
EXPECT_FALSE(adapter->want_write());
}
TEST_P(MetadataApiTest, SubmitConnectionMetadata) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}));
if (GetParam()) {
visitor.AppendMetadataForStream(0, block);
adapter->SubmitMetadata(0, 1);
} else {
auto source = std::make_unique<TestMetadataSource>(block);
adapter->SubmitMetadata(0, 16384u, std::move(source));
}
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 0, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 0, _, 0x4, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({static_cast<SpdyFrameType>(kMetadataFrameType)}));
EXPECT_FALSE(adapter->want_write());
}
TEST_P(MetadataApiTest, ClientSubmitMetadataWithGoaway) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
adapter->SubmitSettings({});
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0));
adapter->Send();
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}));
if (GetParam()) {
visitor.AppendMetadataForStream(stream_id, block);
adapter->SubmitMetadata(stream_id, 1);
} else {
auto source = std::make_unique<TestMetadataSource>(block);
adapter->SubmitMetadata(stream_id, 16384u, std::move(source));
}
EXPECT_TRUE(adapter->want_write());
const std::string initial_frames =
TestFrameSequence()
.ServerPreface()
.GoAway(3, Http2ErrorCode::HTTP2_NO_ERROR, "server shutting down")
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0));
EXPECT_CALL(visitor, OnGoAway(3, Http2ErrorCode::HTTP2_NO_ERROR, _));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor,
OnBeforeFrameSent(kMetadataFrameType, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor,
OnCloseStream(stream_id, Http2ErrorCode::REFUSED_STREAM));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS,
static_cast<SpdyFrameType>(kMetadataFrameType)}));
EXPECT_FALSE(adapter->want_write());
}
TEST_P(MetadataApiTest, ClientSubmitMetadataWithFailureBefore) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
adapter->SubmitSettings({});
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0));
adapter->Send();
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}));
if (GetParam()) {
visitor.AppendMetadataForStream(stream_id, block);
adapter->SubmitMetadata(stream_id, 1);
} else {
auto source = std::make_unique<TestMetadataSource>(block);
adapter->SubmitMetadata(stream_id, 16384u, std::move(source));
}
EXPECT_TRUE(adapter->want_write());
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, stream_id, _, 0x4))
.WillOnce(testing::Return(NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE));
EXPECT_CALL(visitor, OnConnectionError(
Http2VisitorInterface::ConnectionError::kSendError));
int result = adapter->Send();
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS}));
}
TEST_P(MetadataApiTest, ClientSubmitMetadataWithFailureDuring) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
adapter->SubmitSettings({});
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0));
adapter->Send();
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
const quiche::HttpHeaderBlock block = ToHeaderBlock(
ToHeaders({{"more-than-one-frame", std::string(20000, 'a')}}));
if (GetParam()) {
visitor.AppendMetadataForStream(stream_id, block);
adapter->SubmitMetadata(stream_id, 2);
} else {
auto source = std::make_unique<TestMetadataSource>(block);
adapter->SubmitMetadata(stream_id, 16384u, std::move(source));
}
EXPECT_TRUE(adapter->want_write());
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor,
OnBeforeFrameSent(kMetadataFrameType, stream_id, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, stream_id, _, 0x0, 0))
.WillOnce(testing::Return(NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE));
EXPECT_CALL(visitor, OnConnectionError(
Http2VisitorInterface::ConnectionError::kSendError));
int result = adapter->Send();
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS,
static_cast<SpdyFrameType>(kMetadataFrameType)}));
}
TEST_P(MetadataApiTest, ClientSubmitMetadataWithFailureSending) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
adapter->SubmitSettings({});
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0));
adapter->Send();
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
if (GetParam()) {
adapter->SubmitMetadata(stream_id, 2);
} else {
auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(
ToHeaders({{"more-than-one-frame", std::string(20000, 'a')}})));
source->InjectFailure();
adapter->SubmitMetadata(stream_id, 16384u, std::move(source));
}
EXPECT_TRUE(adapter->want_write());
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnConnectionError(
Http2VisitorInterface::ConnectionError::kSendError));
int result = adapter->Send();
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({
SpdyFrameType::SETTINGS,
SpdyFrameType::SETTINGS,
}));
}
TEST_P(NgHttp2AdapterDataTest, ClientObeysMaxConcurrentStreams) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));
visitor.Clear();
const std::string initial_frames =
TestFrameSequence()
.ServerPreface({{MAX_CONCURRENT_STREAMS, 1}})
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting);
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
const absl::string_view kBody = "This is an example request body.";
visitor.AppendPayloadForStream(1, kBody);
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
const int stream_id = adapter->SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
GetParam() ? nullptr : std::move(body1), false, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA}));
EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
const int next_stream_id =
adapter->SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}}),
nullptr, true, nullptr);
EXPECT_GT(next_stream_id, stream_id);
EXPECT_FALSE(adapter->want_write());
const std::string stream_frames =
TestFrameSequence()
.Headers(stream_id,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(stream_id, "This is the response body.", true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200"));
EXPECT_CALL(visitor,
OnHeaderForStream(stream_id, "server", "my-fake-server"));
EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "date",
"Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnFrameHeader(stream_id, 26, DATA, 0x1));
EXPECT_CALL(visitor, OnBeginDataForStream(stream_id, 26));
EXPECT_CALL(visitor,
OnDataForStream(stream_id, "This is the response body."));
EXPECT_CALL(visitor, OnEndStream(stream_id));
EXPECT_CALL(visitor,
OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, next_stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, next_stream_id, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
}
TEST_P(NgHttp2AdapterDataTest, ClientReceivesInitialWindowSetting) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const std::string initial_frames =
TestFrameSequence()
.Settings({{INITIAL_WINDOW_SIZE, 80000u}})
.WindowUpdate(0, 65536)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, 80000u}));
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 65536));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
int64_t result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::string kLongBody = std::string(81000, 'c');
visitor.AppendPayloadForStream(1, kLongBody);
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, true);
const int stream_id = adapter->SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
GetParam() ? nullptr : std::move(body1), false, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16384, 0x0, 0)).Times(4);
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 14464, 0x0, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA,
SpdyFrameType::DATA, SpdyFrameType::DATA,
SpdyFrameType::DATA, SpdyFrameType::DATA}));
}
TEST_P(NgHttp2AdapterDataTest,
ClientReceivesInitialWindowSettingAfterStreamStart) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const std::string initial_frames =
TestFrameSequence().ServerPreface().WindowUpdate(0, 65536).Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 65536));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
int64_t result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string kLongBody = std::string(81000, 'c');
visitor.AppendPayloadForStream(1, kLongBody);
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
const int stream_id = adapter->SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
GetParam() ? nullptr : std::move(body1), false, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16384, 0x0, 0)).Times(3);
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16383, 0x0, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA,
SpdyFrameType::DATA, SpdyFrameType::DATA,
SpdyFrameType::DATA}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
const std::string settings_frame =
TestFrameSequence().Settings({{INITIAL_WINDOW_SIZE, 80000u}}).Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, 80000u}));
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t settings_result = adapter->ProcessBytes(settings_frame);
EXPECT_EQ(settings_frame.size(), static_cast<size_t>(settings_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 14465, 0x0, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::DATA}));
}
TEST(NgHttp2AdapterTest, InvalidInitialWindowSetting) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const uint32_t kTooLargeInitialWindow = 1u << 31;
const std::string initial_frames =
TestFrameSequence()
.Settings({{INITIAL_WINDOW_SIZE, kTooLargeInitialWindow}})
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor,
OnInvalidFrame(
0, Http2VisitorInterface::InvalidFrameError::kFlowControl));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR)));
int64_t result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::GOAWAY}));
visitor.Clear();
}
TEST(NgHttp2AdapterTest, InitialWindowSettingCausesOverflow) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
ASSERT_GT(stream_id, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int64_t write_result = adapter->Send();
EXPECT_EQ(0, write_result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const uint32_t kLargeInitialWindow = (1u << 31) - 1;
const std::string frames =
TestFrameSequence()
.ServerPreface()
.Headers(stream_id, {{":status", "200"}}, false)
.WindowUpdate(stream_id, 65536u)
.Settings({{INITIAL_WINDOW_SIZE, kLargeInitialWindow}})
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 0x4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200"));
EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnFrameHeader(stream_id, 4, WINDOW_UPDATE, 0x0));
EXPECT_CALL(visitor, OnWindowUpdate(stream_id, 65536));
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE,
kLargeInitialWindow}));
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id, 4, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(RST_STREAM, stream_id, 4, 0x0,
static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR)));
EXPECT_CALL(visitor,
OnCloseStream(stream_id, Http2ErrorCode::FLOW_CONTROL_ERROR));
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientForbidsPushPromise) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
adapter->SubmitSettings({{ENABLE_PUSH, 0}});
testing::InSequence s;
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
int write_result = adapter->Send();
EXPECT_EQ(0, write_result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
ASSERT_GT(stream_id, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
write_result = adapter->Send();
EXPECT_EQ(0, write_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::vector<Header> push_headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/push"}});
const std::string frames = TestFrameSequence()
.ServerPreface()
.SettingsAck()
.PushPromise(stream_id, 2, push_headers)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck);
EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, PUSH_PROMISE, _));
EXPECT_CALL(visitor, OnInvalidFrame(stream_id, _));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), read_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int32_t>(Http2ErrorCode::PROTOCOL_ERROR)));
write_result = adapter->Send();
EXPECT_EQ(0, write_result);
}
TEST(NgHttp2AdapterTest, ClientForbidsPushStream) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
adapter->SubmitSettings({{ENABLE_PUSH, 0}});
testing::InSequence s;
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
int write_result = adapter->Send();
EXPECT_EQ(0, write_result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
ASSERT_GT(stream_id, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
write_result = adapter->Send();
EXPECT_EQ(0, write_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string frames =
TestFrameSequence()
.ServerPreface()
.SettingsAck()
.Headers(2,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck);
EXPECT_CALL(visitor, OnFrameHeader(2, _, HEADERS, _));
EXPECT_CALL(visitor, OnInvalidFrame(2, _));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), read_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int32_t>(Http2ErrorCode::PROTOCOL_ERROR)));
write_result = adapter->Send();
EXPECT_EQ(0, write_result);
}
TEST(NgHttp2AdapterTest, FailureSendingConnectionPreface) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
visitor.set_has_write_error();
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError));
int result = adapter->Send();
EXPECT_EQ(result, NGHTTP2_ERR_CALLBACK_FAILURE);
}
TEST(NgHttp2AdapterTest, MaxFrameSizeSettingNotAppliedBeforeAck) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const uint32_t large_frame_size = kDefaultFramePayloadSizeLimit + 42;
adapter->SubmitSettings({{MAX_FRAME_SIZE, large_frame_size}});
const int32_t stream_id = adapter->SubmitRequest(
ToHeaders({{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
nullptr, true, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
testing::InSequence s;
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string server_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "200"}}, false)
.Data(1, std::string(large_frame_size, 'a'))
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
const int64_t process_result = adapter->ProcessBytes(server_frames);
EXPECT_EQ(server_frames.size(), static_cast<size_t>(process_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::FRAME_SIZE_ERROR)));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, MaxFrameSizeSettingAppliedAfterAck) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
const uint32_t large_frame_size = kDefaultFramePayloadSizeLimit + 42;
adapter->SubmitSettings({{MAX_FRAME_SIZE, large_frame_size}});
const int32_t stream_id = adapter->SubmitRequest(
ToHeaders({{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
nullptr, true, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(adapter->want_write());
testing::InSequence s;
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string server_frames =
TestFrameSequence()
.ServerPreface()
.SettingsAck()
.Headers(1, {{":status", "200"}}, false)
.Data(1, std::string(large_frame_size, 'a'))
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, large_frame_size, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, large_frame_size));
EXPECT_CALL(visitor, OnDataForStream(1, _));
const int64_t process_result = adapter->ProcessBytes(server_frames);
EXPECT_EQ(server_frames.size(), static_cast<size_t>(process_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, WindowUpdateRaisesFlowControlWindowLimit) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string data_chunk(kDefaultFramePayloadSizeLimit, 'a');
const std::string request = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"}},
false)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
adapter->ProcessBytes(request);
adapter->SubmitWindowUpdate(0, 2 * kDefaultFramePayloadSizeLimit);
adapter->SubmitWindowUpdate(1, 2 * kDefaultFramePayloadSizeLimit);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(kInitialFlowControlWindowSize + 2 * kDefaultFramePayloadSizeLimit,
adapter->GetReceiveWindowSize());
EXPECT_EQ(kInitialFlowControlWindowSize + 2 * kDefaultFramePayloadSizeLimit,
adapter->GetStreamReceiveWindowSize(1));
const std::string request_body = TestFrameSequence()
.Data(1, data_chunk)
.Data(1, data_chunk)
.Data(1, data_chunk)
.Data(1, data_chunk)
.Data(1, data_chunk)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)).Times(5);
EXPECT_CALL(visitor, OnBeginDataForStream(1, _)).Times(5);
EXPECT_CALL(visitor, OnDataForStream(1, _)).Times(5);
adapter->ProcessBytes(request_body);
EXPECT_EQ(kInitialFlowControlWindowSize - 3 * kDefaultFramePayloadSizeLimit,
adapter->GetReceiveWindowSize());
EXPECT_EQ(kInitialFlowControlWindowSize - 3 * kDefaultFramePayloadSizeLimit,
adapter->GetStreamReceiveWindowSize(1));
adapter->MarkDataConsumedForStream(1, 4 * kDefaultFramePayloadSizeLimit);
EXPECT_GT(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize);
EXPECT_GT(adapter->GetStreamReceiveWindowSize(1),
kInitialFlowControlWindowSize);
}
TEST(NgHttp2AdapterTest, ConnectionErrorOnControlFrameSent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence().ClientPreface().Ping(42).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0))
.WillOnce(testing::Return(-902));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError));
int send_result = adapter->Send();
EXPECT_LT(send_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0));
send_result = adapter->Send();
EXPECT_EQ(send_result, 0);
EXPECT_FALSE(adapter->want_write());
}
TEST_P(NgHttp2AdapterDataTest, ConnectionErrorOnDataFrameSent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
auto body = std::make_unique<VisitorDataSource>(visitor, 1);
visitor.AppendPayloadForStream(
1, "Here is some data, which will lead to a fatal error");
int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
GetParam() ? nullptr : std::move(body), false);
ASSERT_EQ(0, submit_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0))
.WillOnce(testing::Return(-902));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError));
int send_result = adapter->Send();
EXPECT_LT(send_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0));
send_result = adapter->Send();
EXPECT_EQ(send_result, 0);
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ServerConstruction) {
testing::StrictMock<MockHttp2Visitor> visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
ASSERT_NE(nullptr, adapter);
EXPECT_TRUE(adapter->want_read());
EXPECT_FALSE(adapter->want_write());
EXPECT_TRUE(adapter->IsServerSession());
}
TEST(NgHttp2AdapterTest, ServerHandlesFrames) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_EQ(0, adapter->GetHpackDecoderDynamicTableSize());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Ping(42)
.WindowUpdate(0, 1000)
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.RstStream(3, Http2ErrorCode::CANCEL)
.Ping(47)
.Serialize();
testing::InSequence s;
const char* kSentinel1 = "arbitrary pointer 1";
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 1000));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1))
.WillOnce(testing::InvokeWithoutArgs([&adapter, kSentinel1]() {
adapter->SetStreamUserData(1, const_cast<char*>(kSentinel1));
return true;
}));
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(1, 2000));
EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 25));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body."));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "http"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/this/is/request/two"));
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnEndStream(3));
EXPECT_CALL(visitor, OnFrameHeader(3, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(3, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(47, false));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(1));
EXPECT_GT(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(1));
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(1),
adapter->GetReceiveWindowSize());
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowLimit(1));
EXPECT_GT(adapter->GetHpackDecoderDynamicTableSize(), 0);
const char* kSentinel3 = "another arbitrary pointer";
adapter->SetStreamUserData(3, const_cast<char*>(kSentinel3));
EXPECT_EQ(nullptr, adapter->GetStreamUserData(3));
EXPECT_EQ(3, adapter->GetHighestReceivedStreamId());
EXPECT_EQ(adapter->GetSendWindowSize(), kInitialFlowControlWindowSize + 1000);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING,
SpdyFrameType::PING}));
}
TEST(NgHttp2AdapterTest, ServerVisitorRejectsHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"header1", "ok"},
{"header2", "rejected"},
{"header3", "not processed"},
{"header4", "not processed"},
{"header5", "not processed"},
{"header6", "not processed"},
{"header7", "not processed"},
{"header8", "not processed"}},
false, true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x0));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5);
EXPECT_CALL(visitor, OnHeaderForStream(1, "header2", _))
.WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM));
int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::INTERNAL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(OgHttp2AdapterTest, HeaderValuesWithObsTextAllowed) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{"name", "val\xa1ue"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "name", "val\xa1ue"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
}
TEST(NgHttp2AdapterTest, ServerHandlesDataWithPadding) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Data(1, "This is the request body.",
true, 39)
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 25 + 39, DATA, 0x9));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 25 + 39));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body."));
EXPECT_CALL(visitor, OnDataPaddingLength(1, 39));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnEndStream(3));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ServerHandlesHostHeader) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":path", "/this/is/request/one"},
{"host", "example.com"}},
true)
.Headers(3,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"host", "example.com"}},
true)
.Headers(5,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "foo.com"},
{":path", "/this/is/request/one"},
{"host", "bar.com"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnEndStream(3));
EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(5));
EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(5));
EXPECT_CALL(visitor, OnEndStream(5));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
visitor.Clear();
}
TEST_P(NgHttp2AdapterDataTest, ServerSubmitsTrailersWhileDataDeferred) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.WindowUpdate(0, 2000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(1, 2000));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body."));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 2000));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
visitor.Clear();
const absl::string_view kBody = "This is an example response body.";
visitor.AppendPayloadForStream(1, kBody);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}),
GetParam() ? nullptr : std::move(body1), false);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
int trailer_result =
adapter->SubmitTrailer(1, ToHeaders({{"final-status", "a-ok"}}));
ASSERT_EQ(trailer_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
visitor.AppendPayloadForStream(1, kBody);
visitor.SetEndData(1, true);
adapter->ResumeStream(1);
EXPECT_TRUE(adapter->want_write());
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
EXPECT_FALSE(adapter->want_write());
}
TEST_P(NgHttp2AdapterDataTest, ServerSubmitsTrailersWithDataEndStream) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence()
.ClientPreface()
.Headers(1, {{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}})
.Data(1, "Example data, woohoo.")
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
EXPECT_CALL(visitor, OnDataForStream(1, _));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(result), frames.size());
const absl::string_view kBody = "This is an example response body.";
visitor.AppendPayloadForStream(1, kBody);
visitor.SetEndData(1, true);
auto body = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
GetParam() ? nullptr : std::move(body), false);
ASSERT_EQ(submit_result, 0);
const std::vector<Header> trailers =
ToHeaders({{"extra-info", "Trailers are weird but good?"}});
submit_result = adapter->SubmitTrailer(1, trailers);
ASSERT_EQ(submit_result, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _,
END_HEADERS_FLAG | END_STREAM_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _,
END_HEADERS_FLAG | END_STREAM_FLAG, 0));
const int send_result = adapter->Send();
EXPECT_EQ(send_result, 0);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS,
SpdyFrameType::HEADERS}));
}
TEST_P(NgHttp2AdapterDataTest,
ServerSubmitsTrailersWithDataEndStreamAndDeferral) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence()
.ClientPreface()
.Headers(1, {{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}})
.Data(1, "Example data, woohoo.")
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
EXPECT_CALL(visitor, OnDataForStream(1, _));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(result), frames.size());
const absl::string_view kBody = "This is an example response body.";
visitor.AppendPayloadForStream(1, kBody);
auto body = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
GetParam() ? nullptr : std::move(body), false);
ASSERT_EQ(submit_result, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS,
SpdyFrameType::DATA}));
visitor.Clear();
const std::vector<Header> trailers =
ToHeaders({{"extra-info", "Trailers are weird but good?"}});
submit_result = adapter->SubmitTrailer(1, trailers);
ASSERT_EQ(submit_result, 0);
visitor.AppendPayloadForStream(1, kBody);
visitor.SetEndData(1, false);
adapter->ResumeStream(1);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _,
END_HEADERS_FLAG | END_STREAM_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _,
END_HEADERS_FLAG | END_STREAM_FLAG, 0));
send_result = adapter->Send();
EXPECT_EQ(send_result, 0);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
}
TEST(NgHttp2AdapterTest, ClientDisobeysConnectionFlowControl) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"accept", "some bogus value!"}},
false)
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(4464, 'a'))
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
EXPECT_CALL(visitor, OnDataForStream(1, _));
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
EXPECT_CALL(visitor, OnDataForStream(1, _));
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
EXPECT_CALL(visitor, OnDataForStream(1, _));
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ClientDisobeysConnectionFlowControlWithOneDataFrame) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const uint32_t window_overflow_bytes = kInitialFlowControlWindowSize + 1;
adapter->SubmitSettings({{MAX_FRAME_SIZE, window_overflow_bytes}});
const std::string initial_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
int64_t process_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(process_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::string overflow_frames =
TestFrameSequence()
.SettingsAck()
.Data(1, std::string(window_overflow_bytes, 'a'))
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck());
EXPECT_CALL(visitor, OnFrameHeader(1, window_overflow_bytes, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, window_overflow_bytes));
process_result = adapter->ProcessBytes(overflow_frames);
EXPECT_EQ(overflow_frames.size(), static_cast<size_t>(process_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR)));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ClientDisobeysConnectionFlowControlAcrossReads) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const uint32_t window_overflow_bytes = kInitialFlowControlWindowSize + 1;
adapter->SubmitSettings({{MAX_FRAME_SIZE, window_overflow_bytes}});
const std::string initial_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
int64_t process_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(process_result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::string overflow_frames =
TestFrameSequence()
.SettingsAck()
.Data(1, std::string(window_overflow_bytes, 'a'))
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck());
EXPECT_CALL(visitor, OnFrameHeader(1, window_overflow_bytes, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, window_overflow_bytes));
EXPECT_CALL(visitor, OnDataForStream(1, _))
.WillRepeatedly(
[&adapter](Http2StreamId stream_id, absl::string_view data) {
adapter->MarkDataConsumedForStream(stream_id, data.size());
return true;
});
const size_t chunk_length = 16384;
ASSERT_GE(overflow_frames.size(), chunk_length);
absl::string_view remaining = overflow_frames;
while (!remaining.empty()) {
absl::string_view chunk = remaining.substr(0, chunk_length);
process_result = adapter->ProcessBytes(chunk);
EXPECT_EQ(chunk.length(), static_cast<size_t>(process_result));
remaining.remove_prefix(chunk.length());
}
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::WINDOW_UPDATE,
SpdyFrameType::WINDOW_UPDATE}));
}
TEST(NgHttp2AdapterTest, ClientDisobeysStreamFlowControl) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"accept", "some bogus value!"}},
false)
.Serialize();
const std::string more_frames = TestFrameSequence()
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(16384, 'a'))
.Data(1, std::string(4464, 'a'))
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
adapter->SubmitWindowUpdate(0, 20000);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::WINDOW_UPDATE}));
visitor.Clear();
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
EXPECT_CALL(visitor, OnDataForStream(1, _));
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
EXPECT_CALL(visitor, OnDataForStream(1, _));
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
EXPECT_CALL(visitor, OnDataForStream(1, _));
EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384));
EXPECT_CALL(visitor, OnDataForStream(1, _));
result = adapter->ProcessBytes(more_frames);
EXPECT_EQ(more_frames.size(), static_cast<size_t>(result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0));
EXPECT_CALL(
visitor,
OnFrameSent(RST_STREAM, 1, 4, 0x0,
static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::FLOW_CONTROL_ERROR));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerErrorWhileHandlingHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"accept", "some bogus value!"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.WindowUpdate(0, 2000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "some bogus value!"))
.WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM));
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(1, 2000));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 2000));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, 4, 0x0,
static_cast<int>(Http2ErrorCode::INTERNAL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerErrorWhileHandlingHeadersDropsFrames) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"accept", "some bogus value!"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.Metadata(1, "This is the request metadata.")
.RstStream(1, Http2ErrorCode::CANCEL)
.WindowUpdate(0, 2000)
.Headers(3,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
false)
.Metadata(3, "This is the request metadata.",
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "some bogus value!"))
.WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM));
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(1, 2000));
EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataEndForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 2000));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnFrameHeader(3, _, kMetadataFrameType, 0));
EXPECT_CALL(visitor, OnBeginMetadataForStream(3, _));
EXPECT_CALL(visitor, OnMetadataForStream(3, "This is the re"))
.WillOnce(testing::DoAll(testing::InvokeWithoutArgs([&adapter]() {
adapter->SubmitRst(
3, Http2ErrorCode::REFUSED_STREAM);
}),
testing::Return(true)));
EXPECT_CALL(visitor, OnFrameHeader(3, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(3, _));
EXPECT_CALL(visitor, OnMetadataForStream(3, "quest metadata."));
EXPECT_CALL(visitor, OnMetadataEndForStream(3));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, 4, 0x0,
static_cast<int>(Http2ErrorCode::INTERNAL_ERROR)));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, 4, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, 4, 0x0,
static_cast<int>(Http2ErrorCode::REFUSED_STREAM)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerConnectionErrorWhileHandlingHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"Accept", "uppercase, oh boy!"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.WindowUpdate(0, 2000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnErrorDebug);
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader))
.WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(result, NGHTTP2_ERR_CALLBACK_FAILURE);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, 4, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerErrorAfterHandlingHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.WindowUpdate(0, 2000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1))
.WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(-902, result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ServerRejectsFrameHeader) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Ping(64)
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.WindowUpdate(0, 2000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0))
.WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(-902, result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ServerRejectsBeginningOfData) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Data(1, "This is the request body.")
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.RstStream(3, Http2ErrorCode::CANCEL)
.Ping(47)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 25))
.WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ServerRejectsStreamData) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Data(1, "This is the request body.")
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.RstStream(3, Http2ErrorCode::CANCEL)
.Ping(47)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 25));
EXPECT_CALL(visitor, OnDataForStream(1, _)).WillOnce(testing::Return(false));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ServerReceivesTooLargeHeader) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string too_large_value = std::string(80 * 1024, 'q');
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"x-toobig", too_large_value}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, 8, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, 8, 0x0,
static_cast<int>(Http2ErrorCode::COMPRESSION_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ServerReceivesInvalidAuthority) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "ex|ample.com"},
{":path", "/this/is/request/one"}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [:authority], value: [ex|ample.com]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0x0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, 4, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttpAdapterTest, ServerReceivesGoAway) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.GoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "")
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0x0));
EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, ""));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<int64_t>(frames.size()), result);
const int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
nullptr, true);
ASSERT_EQ(0, submit_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0x0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
}
TEST_P(NgHttp2AdapterDataTest, ServerSubmitResponse) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
const char* kSentinel1 = "arbitrary pointer 1";
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1))
.WillOnce(testing::InvokeWithoutArgs([&adapter, kSentinel1]() {
adapter->SetStreamUserData(1, const_cast<char*>(kSentinel1));
return true;
}));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(1, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
EXPECT_EQ(0, adapter->GetHpackEncoderDynamicTableSize());
EXPECT_FALSE(adapter->want_write());
const absl::string_view kBody = "This is an example response body.";
visitor.AppendPayloadForStream(1, kBody);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1,
ToHeaders({{":status", "404"},
{"x-comment", "I have no idea what you're talking about."}}),
GetParam() ? nullptr : std::move(body1), false);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(1));
adapter->SetStreamUserData(1, nullptr);
EXPECT_EQ(nullptr, adapter->GetStreamUserData(1));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA}));
EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody));
EXPECT_FALSE(adapter->want_write());
EXPECT_LT(adapter->GetStreamSendWindowSize(1), kInitialFlowControlWindowSize);
EXPECT_GT(adapter->GetStreamSendWindowSize(1), 0);
EXPECT_EQ(adapter->GetStreamSendWindowSize(3), -1);
EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 0);
}
TEST_P(NgHttp2AdapterDataTest, ServerSubmitResponseWithResetFromClient) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(1, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
const absl::string_view kBody = "This is an example response body.";
visitor.AppendPayloadForStream(1, kBody);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1,
ToHeaders({{":status", "404"},
{"x-comment", "I have no idea what you're talking about."}}),
GetParam() ? nullptr : std::move(body1), false);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_EQ(adapter->sources_size(), GetParam() ? 0 : 1);
const std::string reset =
TestFrameSequence().RstStream(1, Http2ErrorCode::CANCEL).Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::CANCEL))
.WillOnce(
[&adapter](Http2StreamId stream_id, Http2ErrorCode ) {
adapter->RemoveStream(stream_id);
return true;
});
const int64_t reset_result = adapter->ProcessBytes(reset);
EXPECT_EQ(reset.size(), static_cast<size_t>(reset_result));
EXPECT_EQ(adapter->sources_size(), 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, _)).Times(0);
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, _, _)).Times(0);
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, _, _)).Times(0);
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
}
TEST(NgHttp2AdapterTest, ServerSendsShutdown) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
adapter->SubmitShutdownNotice();
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY}));
}
TEST_P(NgHttp2AdapterDataTest, ServerSendsTrailers) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
const absl::string_view kBody = "This is an example response body.";
visitor.AppendPayloadForStream(1, kBody);
visitor.SetEndData(1, false);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}),
GetParam() ? nullptr : std::move(body1), false);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA}));
EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
int trailer_result = adapter->SubmitTrailer(
1, ToHeaders({{"final-status", "a-ok"},
{"x-comment", "trailers sure are cool"}}));
ASSERT_EQ(trailer_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
}
TEST(NgHttp2AdapterTest, ClientSendsContinuation) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true,
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 1));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnFrameHeader(1, _, CONTINUATION, 4));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
}
TEST(NgHttp2AdapterTest, ClientSendsMetadataWithContinuation) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames =
TestFrameSequence()
.ClientPreface()
.Metadata(0, "Example connection metadata in multiple frames", true)
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false,
true)
.Metadata(1,
"Some stream metadata that's also sent in multiple frames",
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 0));
EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _));
EXPECT_CALL(visitor, OnMetadataForStream(0, _));
EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _));
EXPECT_CALL(visitor, OnMetadataForStream(0, _));
EXPECT_CALL(visitor, OnMetadataEndForStream(0));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnFrameHeader(1, _, CONTINUATION, 4));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 0));
EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataForStream(1, _));
EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4));
EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataForStream(1, _));
EXPECT_CALL(visitor, OnMetadataEndForStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ("Example connection metadata in multiple frames",
absl::StrJoin(visitor.GetMetadata(0), ""));
EXPECT_EQ("Some stream metadata that's also sent in multiple frames",
absl::StrJoin(visitor.GetMetadata(1), ""));
}
TEST_P(NgHttp2AdapterDataTest, RepeatedHeaderNames) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"accept", "text/plain"},
{"accept", "text/html"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "text/plain"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "text/html"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
const std::vector<Header> headers1 = ToHeaders(
{{":status", "200"}, {"content-length", "10"}, {"content-length", "10"}});
visitor.AppendPayloadForStream(1, "perfection");
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1, headers1, GetParam() ? nullptr : std::move(body1), false);
ASSERT_EQ(0, submit_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, 10, 0x1, 0));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS,
SpdyFrameType::DATA}));
}
TEST_P(NgHttp2AdapterDataTest, ServerRespondsToRequestWithTrailers) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames =
TestFrameSequence()
.ClientPreface()
.Headers(1, {{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}})
.Data(1, "Example data, woohoo.")
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
EXPECT_CALL(visitor, OnDataForStream(1, _));
int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
const std::vector<Header> headers1 = ToHeaders({{":status", "200"}});
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1, headers1, GetParam() ? nullptr : std::move(body1), false);
ASSERT_EQ(0, submit_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string more_frames =
TestFrameSequence()
.Headers(1, {{"extra-info", "Trailers are weird but good?"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, "extra-info",
"Trailers are weird but good?"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
result = adapter->ProcessBytes(more_frames);
EXPECT_EQ(more_frames.size(), static_cast<size_t>(result));
visitor.SetEndData(1, true);
EXPECT_EQ(true, adapter->ResumeStream(1));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, 0, 0x1, 0));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA}));
}
TEST_P(NgHttp2AdapterDataTest, ServerSubmitsResponseWithDataSourceError) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
visitor.SimulateError(1);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}),
GetParam() ? nullptr : std::move(body1), false);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, 2));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS,
SpdyFrameType::RST_STREAM}));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
int trailer_result =
adapter->SubmitTrailer(1, ToHeaders({{":final-status", "a-ok"}}));
EXPECT_EQ(trailer_result, 0);
}
TEST(NgHttp2AdapterTest, CompleteRequestWithServerResponse) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Data(1, "This is the response body.", true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
EXPECT_CALL(visitor, OnDataForStream(1, _));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
int submit_result = adapter->SubmitResponse(
1, ToHeaders({{":status", "200"}}), nullptr, true);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, IncompleteRequestWithServerResponse) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
int submit_result = adapter->SubmitResponse(
1, ToHeaders({{":status", "200"}}), nullptr, true);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ServerHandlesMultipleContentLength) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/1"},
{"content-length", "7"},
{"content-length", "7"}},
false)
.Headers(3,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/3"},
{"content-length", "11"},
{"content-length", "13"}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/1"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "7"));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [content-length], value: [7]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/3"));
EXPECT_CALL(visitor, OnHeaderForStream(3, "content-length", "11"));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 3, name: [content-length], value: [13]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
}
TEST_P(NgHttp2AdapterDataTest, ServerSendsInvalidTrailers) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
const absl::string_view kBody = "This is an example response body.";
visitor.AppendPayloadForStream(1, kBody);
visitor.SetEndData(1, false);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result = adapter->SubmitResponse(
1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}),
GetParam() ? nullptr : std::move(body1), false);
EXPECT_EQ(submit_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS,
SpdyFrameType::DATA}));
EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody));
visitor.Clear();
EXPECT_FALSE(adapter->want_write());
int trailer_result =
adapter->SubmitTrailer(1, ToHeaders({{":final-status", "a-ok"}}));
ASSERT_EQ(trailer_result, 0);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS}));
}
TEST(NgHttp2AdapterTest, ServerDropsNewStreamBelowWatermark) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(3,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Data(3, "This is the request body.")
.Headers(1,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnFrameHeader(3, 25, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(3, 25));
EXPECT_CALL(visitor, OnDataForStream(3, "This is the request body."));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnInvalidFrame).Times(0);
EXPECT_CALL(visitor, OnConnectionError).Times(0);
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(3, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterInteractionTest,
ClientServerInteractionRepeatedHeaderNames) {
TestVisitor client_visitor;
auto client_adapter = NgHttp2Adapter::CreateClientAdapter(client_visitor);
client_adapter->SubmitSettings({});
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"accept", "text/plain"},
{"accept", "text/html"}});
const int32_t stream_id1 =
client_adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(client_visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(client_visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int send_result = client_adapter->Send();
EXPECT_EQ(0, send_result);
TestVisitor server_visitor;
auto server_adapter = NgHttp2Adapter::CreateServerAdapter(server_visitor);
testing::InSequence s;
EXPECT_CALL(server_visitor, OnFrameHeader(0, _, SETTINGS, 0));
EXPECT_CALL(server_visitor, OnSettingsStart());
EXPECT_CALL(server_visitor, OnSetting(_)).Times(testing::AnyNumber());
EXPECT_CALL(server_visitor, OnSettingsEnd());
EXPECT_CALL(server_visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(server_visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":scheme", "http"));
EXPECT_CALL(server_visitor,
OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(server_visitor,
OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, "accept", "text/plain"));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, "accept", "text/html"));
EXPECT_CALL(server_visitor, OnEndHeadersForStream(1));
EXPECT_CALL(server_visitor, OnEndStream(1));
int64_t result = server_adapter->ProcessBytes(client_visitor.data());
EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result));
}
TEST(NgHttp2AdapterInteractionTest, ClientServerInteractionWithCookies) {
TestVisitor client_visitor;
auto client_adapter = NgHttp2Adapter::CreateClientAdapter(client_visitor);
client_adapter->SubmitSettings({});
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"cookie", "a; b=2; c"},
{"cookie", "d=e, f, g; h"}});
const int32_t stream_id1 =
client_adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(client_visitor,
OnBeforeFrameSent(HEADERS, stream_id1, _,
END_STREAM_FLAG | END_HEADERS_FLAG));
EXPECT_CALL(client_visitor,
OnFrameSent(HEADERS, stream_id1, _,
END_STREAM_FLAG | END_HEADERS_FLAG, 0));
int send_result = client_adapter->Send();
EXPECT_EQ(0, send_result);
TestVisitor server_visitor;
auto server_adapter = NgHttp2Adapter::CreateServerAdapter(server_visitor);
testing::InSequence s;
EXPECT_CALL(server_visitor, OnFrameHeader(0, _, SETTINGS, 0));
EXPECT_CALL(server_visitor, OnSettingsStart());
EXPECT_CALL(server_visitor, OnSetting).Times(testing::AnyNumber());
EXPECT_CALL(server_visitor, OnSettingsEnd());
EXPECT_CALL(server_visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(server_visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":scheme", "http"));
EXPECT_CALL(server_visitor,
OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(server_visitor,
OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, "cookie", "a; b=2; c"));
EXPECT_CALL(server_visitor, OnHeaderForStream(1, "cookie", "d=e, f, g; h"));
EXPECT_CALL(server_visitor, OnEndHeadersForStream(1));
EXPECT_CALL(server_visitor, OnEndStream(1));
int64_t result = server_adapter->ProcessBytes(client_visitor.data());
EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result));
}
TEST(NgHttp2AdapterTest, ServerForbidsWindowUpdateOnIdleStream) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
const std::string frames =
TestFrameSequence().ClientPreface().WindowUpdate(1, 42).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnInvalidFrame(1, _));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ServerForbidsDataOnIdleStream) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Data(1, "Sorry, out of order")
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ServerForbidsRstStreamOnIdleStream) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
const std::string frames =
TestFrameSequence()
.ClientPreface()
.RstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0));
EXPECT_CALL(visitor, OnInvalidFrame(1, _));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ServerForbidsNewStreamAboveStreamLimit) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
adapter->SubmitSettings({{MAX_CONCURRENT_STREAMS, 1}});
const std::string initial_frames =
TestFrameSequence().ClientPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.SettingsAck()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 0x5));
EXPECT_CALL(
visitor,
OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kProtocol));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ServerRstStreamsNewStreamAboveStreamLimitBeforeAck) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
adapter->SubmitSettings({{MAX_CONCURRENT_STREAMS, 1}});
const std::string initial_frames =
TestFrameSequence().ClientPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 0x5));
EXPECT_CALL(visitor,
OnInvalidFrame(
3, Http2VisitorInterface::InvalidFrameError::kRefusedStream));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_result, stream_frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::REFUSED_STREAM)));
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, AutomaticSettingsAndPingAcks) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence().ClientPreface().Ping(42).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING}));
}
TEST(NgHttp2AdapterTest, AutomaticPingAcksDisabled) {
TestVisitor visitor;
nghttp2_option* options;
nghttp2_option_new(&options);
nghttp2_option_set_no_auto_ping_ack(options, 1);
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor, options);
nghttp2_option_del(options);
const std::string frames =
TestFrameSequence().ClientPreface().Ping(42).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, InvalidMaxFrameSizeSetting) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence().ClientPreface({{MAX_FRAME_SIZE, 3u}}).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(
visitor,
OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(OgHttp2AdapterTest, InvalidPushSetting) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence().ClientPreface({{ENABLE_PUSH, 3u}}).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnInvalidFrame(0, _));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, InvalidConnectProtocolSetting) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface({{ENABLE_CONNECT_PROTOCOL, 3u}})
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(
visitor,
OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));
int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
auto adapter2 = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames2 = TestFrameSequence()
.ClientPreface({{ENABLE_CONNECT_PROTOCOL, 1}})
.Settings({{ENABLE_CONNECT_PROTOCOL, 0}})
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{ENABLE_CONNECT_PROTOCOL, 1u}));
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{ENABLE_CONNECT_PROTOCOL, 0u}));
EXPECT_CALL(visitor, OnSettingsEnd());
read_result = adapter2->ProcessBytes(frames2);
EXPECT_EQ(static_cast<size_t>(read_result), frames2.size());
EXPECT_TRUE(adapter2->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
adapter2->Send();
}
TEST(NgHttp2AdapterTest, ServerForbidsProtocolPseudoheaderBeforeAck) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string initial_frames =
TestFrameSequence().ClientPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size());
const std::string stream1_frames =
TestFrameSequence()
.Headers(1,
{{":method", "CONNECT"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{":protocol", "websocket"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [:protocol], value: [websocket]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
int64_t stream_result = adapter->ProcessBytes(stream1_frames);
EXPECT_EQ(static_cast<size_t>(stream_result), stream1_frames.size());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
adapter->SubmitSettings({{ENABLE_CONNECT_PROTOCOL, 1}});
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
visitor.Clear();
const std::string stream3_frames =
TestFrameSequence()
.Headers(3,
{{":method", "CONNECT"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/two"},
{":protocol", "websocket"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnEndStream(3));
stream_result = adapter->ProcessBytes(stream3_frames);
EXPECT_EQ(static_cast<size_t>(stream_result), stream3_frames.size());
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ServerAllowsProtocolPseudoheaderAfterAck) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
adapter->SubmitSettings({{ENABLE_CONNECT_PROTOCOL, 1}});
const std::string initial_frames =
TestFrameSequence().ClientPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.SettingsAck()
.Headers(1,
{{":method", "CONNECT"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{":protocol", "websocket"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, _, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(static_cast<size_t>(stream_result), stream_frames.size());
EXPECT_FALSE(adapter->want_write());
}
TEST_P(NgHttp2AdapterDataTest, SkipsSendingFramesForRejectedStream) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string initial_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size());
visitor.AppendPayloadForStream(
1, "Here is some data, which will be completely ignored!");
auto body = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
GetParam() ? nullptr : std::move(body), false);
ASSERT_EQ(0, submit_result);
auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})));
adapter->SubmitMetadata(1, 16384u, std::move(source));
adapter->SubmitWindowUpdate(1, 1024);
adapter->SubmitRst(1, Http2ErrorCode::INTERNAL_ERROR);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::INTERNAL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS,
static_cast<SpdyFrameType>(kMetadataFrameType),
SpdyFrameType::RST_STREAM}));
}
TEST_P(NgHttp2AdapterDataTest, ServerQueuesMetadataWithStreamReset) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string initial_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size());
visitor.AppendPayloadForStream(
1, "Here is some data, which will be completely ignored!");
auto body = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
GetParam() ? nullptr : std::move(body), false);
ASSERT_EQ(0, submit_result);
auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})));
adapter->SubmitMetadata(1, 16384u, std::move(source));
adapter->SubmitWindowUpdate(1, 1024);
const std::string reset_frame =
TestFrameSequence().RstStream(1, Http2ErrorCode::CANCEL).Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0x0));
EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::CANCEL));
adapter->ProcessBytes(reset_frame);
source = std::make_unique<TestMetadataSource>(
ToHeaderBlock(ToHeaders({{"really-important", "information!"}})));
adapter->SubmitMetadata(1, 16384u, std::move(source));
EXPECT_EQ(1, adapter->stream_metadata_size());
EXPECT_EQ(2, adapter->pending_metadata_count(1));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS,
static_cast<SpdyFrameType>(kMetadataFrameType),
static_cast<SpdyFrameType>(kMetadataFrameType)}));
EXPECT_EQ(0, adapter->stream_metadata_size());
EXPECT_EQ(0, adapter->pending_metadata_count(1));
}
TEST(NgHttp2AdapterTest, ServerStartsShutdown) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
adapter->SubmitShutdownNotice();
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
}
TEST(NgHttp2AdapterTest, ServerStartsShutdownAfterGoaway) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
EXPECT_FALSE(adapter->want_write());
adapter->SubmitGoAway(1, Http2ErrorCode::HTTP2_NO_ERROR,
"and don't come back!");
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY}));
adapter->SubmitShutdownNotice();
EXPECT_FALSE(adapter->want_write());
}
TEST(NgHttp2AdapterTest, ConnectionErrorWithBlackholeSinkingData) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence().ClientPreface().WindowUpdate(1, 42).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnInvalidFrame(1, _));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(result), frames.size());
const std::string next_frame = TestFrameSequence().Ping(42).Serialize();
const int64_t next_result = adapter->ProcessBytes(next_frame);
EXPECT_EQ(static_cast<size_t>(next_result), next_frame.size());
}
TEST_P(NgHttp2AdapterDataTest, ServerDoesNotSendFramesAfterImmediateGoAway) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
adapter->SubmitSettings({{HEADER_TABLE_SIZE, 100u}});
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
visitor.AppendPayloadForStream(1, "This data is doomed to never be written.");
auto body = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
GetParam() ? nullptr : std::move(body), false);
ASSERT_EQ(0, submit_result);
adapter->SubmitWindowUpdate(kConnectionStreamId, 42);
adapter->SubmitSettings({});
auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders(
{{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})));
adapter->SubmitMetadata(1, 16384u, std::move(source));
EXPECT_TRUE(adapter->want_write());
const std::string connection_error_frames =
TestFrameSequence().WindowUpdate(3, 42).Serialize();
EXPECT_CALL(visitor, OnFrameHeader(3, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnInvalidFrame(3, _));
const int64_t result = adapter->ProcessBytes(connection_error_frames);
EXPECT_EQ(static_cast<size_t>(result), connection_error_frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS,
SpdyFrameType::GOAWAY}));
visitor.Clear();
adapter->SubmitPing(42);
EXPECT_FALSE(adapter->want_write());
send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
}
TEST(NgHttp2AdapterTest, ServerHandlesContentLength) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
testing::InSequence s;
const std::string stream_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1, {{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"},
{"content-length", "2"}})
.Data(1, "hi", true)
.Headers(3,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/two"},
{"content-length", "nan"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 2));
EXPECT_CALL(visitor, OnDataForStream(1, "hi"));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 3, name: [content-length], value: [nan]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerHandlesContentLengthMismatch) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
testing::InSequence s;
const std::string stream_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1, {{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/two"},
{"content-length", "2"}})
.Data(1, "h", true)
.Headers(3, {{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/three"},
{"content-length", "2"}})
.Data(3, "howdy", true)
.Headers(5,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/four"},
{"content-length", "2"}},
true)
.Headers(7,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/four"},
{"content-length", "2"}},
false)
.Data(7, "h", false)
.Headers(7, {{"extra-info", "Trailers with content-length mismatch"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 1));
EXPECT_CALL(visitor, OnDataForStream(1, "h"));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnFrameHeader(3, _, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(3, 5));
EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(5));
EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(5);
EXPECT_CALL(visitor,
OnInvalidFrame(
5, Http2VisitorInterface::InvalidFrameError::kHttpMessaging));
EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(7));
EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(7));
EXPECT_CALL(visitor, OnFrameHeader(7, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(7, 1));
EXPECT_CALL(visitor, OnDataForStream(7, "h"));
EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(7));
EXPECT_CALL(visitor, OnHeaderForStream(7, _, _));
EXPECT_CALL(visitor,
OnInvalidFrame(
7, Http2VisitorInterface::InvalidFrameError::kHttpMessaging));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 5, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 7, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 7, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(7, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(
visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerHandlesAsteriskPathForOptions) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
testing::InSequence s;
const std::string stream_frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "*"},
{":method", "OPTIONS"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ServerHandlesInvalidPath) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
testing::InSequence s;
const std::string stream_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "*"},
{":method", "GET"}},
true)
.Headers(3,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "other/non/slash/starter"},
{":method", "GET"}},
true)
.Headers(5,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", ""},
{":method", "GET"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor,
OnInvalidFrame(
1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4);
EXPECT_CALL(visitor,
OnInvalidFrame(
3, Http2VisitorInterface::InvalidFrameError::kHttpMessaging));
EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(5));
EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(2);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 5, name: [:path], value: []"));
EXPECT_CALL(
visitor,
OnInvalidFrame(5, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 5, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(
visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerHandlesTeHeader) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
testing::InSequence s;
const std::string stream_frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{":method", "GET"},
{"te", "trailers"}},
true)
.Headers(3,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{":method", "GET"},
{"te", "trailers, deflate"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 3, name: [te], value: [trailers, deflate]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ServerHandlesConnectionSpecificHeaders) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
testing::InSequence s;
const std::string stream_frames =
TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{":method", "GET"},
{"connection", "keep-alive"}},
true)
.Headers(3,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{":method", "GET"},
{"proxy-connection", "keep-alive"}},
true)
.Headers(5,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{":method", "GET"},
{"keep-alive", "timeout=42"}},
true)
.Headers(7,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{":method", "GET"},
{"transfer-encoding", "chunked"}},
true)
.Headers(9,
{{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{":method", "GET"},
{"upgrade", "h2c"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [connection], value: [keep-alive]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 3, name: [proxy-connection], value: [keep-alive]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(5));
EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 5, name: [keep-alive], value: [timeout=42]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(5, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(7));
EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 7, name: [transfer-encoding], value: [chunked]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(7, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(9, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(9));
EXPECT_CALL(visitor, OnHeaderForStream(9, _, _)).Times(4);
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 9, name: [upgrade], value: [h2c]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(9, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 5, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 7, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 7, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(7, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 9, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 9, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(9, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(
visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM}));
}
TEST(OgHttp2AdapterTest, ServerConsumesDataWithPadding) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
TestFrameSequence seq = std::move(TestFrameSequence().ClientPreface().Headers(
1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false));
size_t total_size = 0;
while (total_size < 62 * 1024) {
seq.Data(1, "a", false, 254);
total_size += 255;
}
const std::string frames = seq.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0x8))
.Times(testing::AtLeast(1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _)).Times(testing::AtLeast(1));
EXPECT_CALL(visitor, OnDataForStream(1, "a")).Times(testing::AtLeast(1));
EXPECT_CALL(visitor, OnDataPaddingLength(1, _)).Times(testing::AtLeast(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(result, frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, _, 0x0)).Times(1);
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, _, 0x0, 0)).Times(1);
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, _, 0x0)).Times(1);
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, _, 0x0, 0)).Times(1);
const int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::WINDOW_UPDATE,
SpdyFrameType::WINDOW_UPDATE}));
}
TEST_P(NgHttp2AdapterDataTest, NegativeFlowControlStreamResumption) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames =
TestFrameSequence()
.ClientPreface({{INITIAL_WINDOW_SIZE, 128u * 1024u}})
.WindowUpdate(0, 1 << 20)
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor,
OnSetting(Http2Setting{Http2KnownSettingsId::INITIAL_WINDOW_SIZE,
128u * 1024u}));
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 1 << 20));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4);
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
visitor.AppendPayloadForStream(1, std::string(70000, 'a'));
auto body = std::make_unique<VisitorDataSource>(visitor, 1);
int submit_result =
adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}),
GetParam() ? nullptr : std::move(body), false);
ASSERT_EQ(0, submit_result);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)).Times(5);
adapter->Send();
EXPECT_FALSE(adapter->want_write());
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor,
OnSetting(Http2Setting{Http2KnownSettingsId::INITIAL_WINDOW_SIZE,
64u * 1024u}));
EXPECT_CALL(visitor, OnSettingsEnd());
adapter->ProcessBytes(TestFrameSequence()
.Settings({{INITIAL_WINDOW_SIZE, 64u * 1024u}})
.Serialize());
EXPECT_TRUE(adapter->want_write());
EXPECT_EQ(adapter->GetStreamSendWindowSize(1), 0);
visitor.AppendPayloadForStream(1, "Stream should be resumed.");
adapter->ResumeStream(1);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
adapter->Send();
EXPECT_FALSE(adapter->want_write());
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(1, 10000));
adapter->ProcessBytes(TestFrameSequence().WindowUpdate(1, 10000).Serialize());
EXPECT_TRUE(adapter->want_write());
EXPECT_GT(adapter->GetStreamSendWindowSize(1), 0);
EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0));
adapter->Send();
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_adapter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_adapter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
23427dcf-22eb-4675-9011-32fc7381c6eb | cpp | google/tensorstore | apply_members | tensorstore/util/apply_members/apply_members.h | tensorstore/util/apply_members/apply_members_test.cc | #ifndef TENSORSTORE_UTIL_APPLY_MEMBERS_APPLY_MEMBERS_H_
#define TENSORSTORE_UTIL_APPLY_MEMBERS_APPLY_MEMBERS_H_
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
namespace half_float {
class half;
}
namespace tensorstore {
class BFloat16;
template <typename T, typename SFINAE = void>
struct ApplyMembers {
using NotSpecialized = void;
};
namespace internal_apply_members {
struct IgnoreMembers {
template <typename... T>
constexpr void operator()(const T&...) const {}
};
template <typename T, typename SFINAE = void>
struct SupportsApplyMembersImpl : public std::true_type {};
template <typename T>
struct SupportsApplyMembersImpl<T, typename ApplyMembers<T>::NotSpecialized>
: public std::false_type {};
template <typename T>
using MemberApplyMembersCallExpr = decltype(T::ApplyMembers(
std::declval<const T&>(), internal_apply_members::IgnoreMembers{}));
}
template <typename T>
struct ApplyMembers<
T,
std::enable_if_t<
!std::is_empty_v<T>,
std::void_t<internal_apply_members::MemberApplyMembersCallExpr<T>>>> {
template <typename X, typename F>
ABSL_ATTRIBUTE_ALWAYS_INLINE static constexpr auto Apply(X&& x, F f) {
return T::ApplyMembers(x, std::move(f));
}
};
template <typename T>
struct ApplyMembers<T, std::enable_if_t<std::is_empty_v<T>>> {
template <typename X, typename F>
ABSL_ATTRIBUTE_ALWAYS_INLINE static constexpr auto Apply(X&& x, F f) {
return f();
}
};
template <typename T>
constexpr inline bool SupportsApplyMembers =
internal_apply_members::SupportsApplyMembersImpl<T>::value;
template <typename T, typename SFINAE = void>
constexpr inline bool SerializeUsingMemcpy =
std::is_integral_v<T> || std::is_floating_point_v<T> || std::is_enum_v<T>;
template <>
constexpr inline bool SerializeUsingMemcpy<BFloat16> = true;
template <>
constexpr inline bool SerializeUsingMemcpy<half_float::half> = true;
}
#endif | #include "tensorstore/util/apply_members/apply_members.h"
#include <array>
#include <complex>
#include <tuple>
#include <utility>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorstore/util/apply_members/std_array.h"
#include "tensorstore/util/apply_members/std_complex.h"
#include "tensorstore/util/apply_members/std_pair.h"
#include "tensorstore/util/apply_members/std_tuple.h"
namespace {
struct Foo {
int x, y;
static constexpr auto ApplyMembers = [](auto&& x, auto f) {
return f(x.x, x.y);
};
};
struct Bar {};
struct Baz {
int x, y;
};
[[maybe_unused]] void TestFooApplyMembers() {
Foo value;
tensorstore::ApplyMembers<Foo>::Apply(value, [&](int& x, int& y) {});
}
[[maybe_unused]] void TestBarApplyMembers() {
Bar value;
tensorstore::ApplyMembers<Bar>::Apply(value, [&]() {});
}
[[maybe_unused]] void TestTupleApplyMembers() {
using T = std::tuple<int, double>;
T value;
tensorstore::ApplyMembers<T>::Apply(value, [&](int& x, double& y) {});
}
[[maybe_unused]] void TestStdArrayApplyMembers() {
using T = std::array<int, 3>;
T value;
tensorstore::ApplyMembers<T>::Apply(value, [&](int& x, int& y, int& z) {});
}
[[maybe_unused]] void TestArrayApplyMembers() {
using T = int[3];
T value;
tensorstore::ApplyMembers<T>::Apply(value, [&](int& x, int& y, int& z) {});
}
[[maybe_unused]] void TestPairApplyMembers() {
using T = std::pair<int, double>;
T value;
tensorstore::ApplyMembers<T>::Apply(value, [&](int& x, double& y) {});
}
[[maybe_unused]] void TestComplexApplyMembers() {
using T = std::complex<double>;
T value;
tensorstore::ApplyMembers<T>::Apply(value, [&](double& r, double& i) {});
}
static_assert(tensorstore::SupportsApplyMembers<Foo>);
static_assert(tensorstore::SupportsApplyMembers<Bar>);
static_assert(tensorstore::SupportsApplyMembers<std::complex<float>>);
static_assert(tensorstore::SupportsApplyMembers<std::pair<int, double>>);
static_assert(tensorstore::SupportsApplyMembers<std::tuple<>>);
static_assert(tensorstore::SupportsApplyMembers<std::tuple<int>>);
static_assert(tensorstore::SupportsApplyMembers<std::tuple<int, double>>);
static_assert(tensorstore::SupportsApplyMembers<std::array<int, 3>>);
static_assert(!tensorstore::SupportsApplyMembers<Baz>);
} | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/util/apply_members/apply_members.h | https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/util/apply_members/apply_members_test.cc | 4f887a6430414cd6088e1743555015b10f116d50 |
67162720-7b91-4e49-9f0d-59f369b55439 | cpp | google/cel-cpp | kind | common/kind.cc | common/kind_test.cc | #include "common/kind.h"
#include "absl/strings/string_view.h"
namespace cel {
absl::string_view KindToString(Kind kind) {
switch (kind) {
case Kind::kNullType:
return "null_type";
case Kind::kDyn:
return "dyn";
case Kind::kAny:
return "any";
case Kind::kType:
return "type";
case Kind::kTypeParam:
return "type_param";
case Kind::kFunction:
return "function";
case Kind::kBool:
return "bool";
case Kind::kInt:
return "int";
case Kind::kUint:
return "uint";
case Kind::kDouble:
return "double";
case Kind::kString:
return "string";
case Kind::kBytes:
return "bytes";
case Kind::kDuration:
return "duration";
case Kind::kTimestamp:
return "timestamp";
case Kind::kList:
return "list";
case Kind::kMap:
return "map";
case Kind::kStruct:
return "struct";
case Kind::kUnknown:
return "*unknown*";
case Kind::kOpaque:
return "*opaque*";
case Kind::kBoolWrapper:
return "google.protobuf.BoolValue";
case Kind::kIntWrapper:
return "google.protobuf.Int64Value";
case Kind::kUintWrapper:
return "google.protobuf.UInt64Value";
case Kind::kDoubleWrapper:
return "google.protobuf.DoubleValue";
case Kind::kStringWrapper:
return "google.protobuf.StringValue";
case Kind::kBytesWrapper:
return "google.protobuf.BytesValue";
case Kind::kEnum:
return "enum";
default:
return "*error*";
}
}
} | #include "common/kind.h"
#include <limits>
#include <type_traits>
#include "common/type_kind.h"
#include "common/value_kind.h"
#include "internal/testing.h"
namespace cel {
namespace {
static_assert(std::is_same_v<std::underlying_type_t<TypeKind>,
std::underlying_type_t<ValueKind>>,
"TypeKind and ValueKind must have the same underlying type");
TEST(Kind, ToString) {
EXPECT_EQ(KindToString(Kind::kError), "*error*");
EXPECT_EQ(KindToString(Kind::kNullType), "null_type");
EXPECT_EQ(KindToString(Kind::kDyn), "dyn");
EXPECT_EQ(KindToString(Kind::kAny), "any");
EXPECT_EQ(KindToString(Kind::kType), "type");
EXPECT_EQ(KindToString(Kind::kBool), "bool");
EXPECT_EQ(KindToString(Kind::kInt), "int");
EXPECT_EQ(KindToString(Kind::kUint), "uint");
EXPECT_EQ(KindToString(Kind::kDouble), "double");
EXPECT_EQ(KindToString(Kind::kString), "string");
EXPECT_EQ(KindToString(Kind::kBytes), "bytes");
EXPECT_EQ(KindToString(Kind::kDuration), "duration");
EXPECT_EQ(KindToString(Kind::kTimestamp), "timestamp");
EXPECT_EQ(KindToString(Kind::kList), "list");
EXPECT_EQ(KindToString(Kind::kMap), "map");
EXPECT_EQ(KindToString(Kind::kStruct), "struct");
EXPECT_EQ(KindToString(Kind::kUnknown), "*unknown*");
EXPECT_EQ(KindToString(Kind::kOpaque), "*opaque*");
EXPECT_EQ(KindToString(Kind::kBoolWrapper), "google.protobuf.BoolValue");
EXPECT_EQ(KindToString(Kind::kIntWrapper), "google.protobuf.Int64Value");
EXPECT_EQ(KindToString(Kind::kUintWrapper), "google.protobuf.UInt64Value");
EXPECT_EQ(KindToString(Kind::kDoubleWrapper), "google.protobuf.DoubleValue");
EXPECT_EQ(KindToString(Kind::kStringWrapper), "google.protobuf.StringValue");
EXPECT_EQ(KindToString(Kind::kBytesWrapper), "google.protobuf.BytesValue");
EXPECT_EQ(KindToString(static_cast<Kind>(std::numeric_limits<int>::max())),
"*error*");
}
TEST(Kind, TypeKindRoundtrip) {
EXPECT_EQ(TypeKindToKind(KindToTypeKind(Kind::kBool)), Kind::kBool);
}
TEST(Kind, ValueKindRoundtrip) {
EXPECT_EQ(ValueKindToKind(KindToValueKind(Kind::kBool)), Kind::kBool);
}
TEST(Kind, IsTypeKind) {
EXPECT_TRUE(KindIsTypeKind(Kind::kBool));
EXPECT_TRUE(KindIsTypeKind(Kind::kAny));
EXPECT_TRUE(KindIsTypeKind(Kind::kDyn));
}
TEST(Kind, IsValueKind) {
EXPECT_TRUE(KindIsValueKind(Kind::kBool));
EXPECT_FALSE(KindIsValueKind(Kind::kAny));
EXPECT_FALSE(KindIsValueKind(Kind::kDyn));
}
TEST(Kind, Equality) {
EXPECT_EQ(Kind::kBool, TypeKind::kBool);
EXPECT_EQ(TypeKind::kBool, Kind::kBool);
EXPECT_EQ(Kind::kBool, ValueKind::kBool);
EXPECT_EQ(ValueKind::kBool, Kind::kBool);
EXPECT_NE(Kind::kBool, TypeKind::kInt);
EXPECT_NE(TypeKind::kInt, Kind::kBool);
EXPECT_NE(Kind::kBool, ValueKind::kInt);
EXPECT_NE(ValueKind::kInt, Kind::kBool);
}
TEST(TypeKind, ToString) {
EXPECT_EQ(TypeKindToString(TypeKind::kBool), KindToString(Kind::kBool));
}
TEST(ValueKind, ToString) {
EXPECT_EQ(ValueKindToString(ValueKind::kBool), KindToString(Kind::kBool));
}
}
} | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/kind.cc | https://github.com/google/cel-cpp/blob/4552db5798fb0853b131b783d8875794334fae7f/common/kind_test.cc | 4552db5798fb0853b131b783d8875794334fae7f |
c4ea70b1-9d47-4f07-af1c-0c17c795a89a | cpp | tensorflow/tensorflow | cuda_executor | third_party/xla/xla/stream_executor/cuda/cuda_executor.cc | third_party/xla/xla/stream_executor/cuda/cuda_executor_test.cc | #include "xla/stream_executor/cuda/cuda_executor.h"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <variant>
#include "absl/log/check.h"
#include "absl/numeric/int128.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "third_party/gpus/cuda/include/cuda.h"
#include "xla/stream_executor/blas.h"
#include "xla/stream_executor/command_buffer.h"
#include "xla/stream_executor/cuda/cuda_collectives.h"
#include "xla/stream_executor/cuda/cuda_event.h"
#include "xla/stream_executor/cuda/cuda_kernel.h"
#include "xla/stream_executor/cuda/cuda_platform_id.h"
#include "xla/stream_executor/cuda/cuda_runtime.h"
#include "xla/stream_executor/cuda/cuda_status.h"
#include "xla/stream_executor/cuda/cuda_version_parser.h"
#include "xla/stream_executor/cuda/delay_kernel.h"
#include "xla/stream_executor/device_description.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/dnn.h"
#include "xla/stream_executor/event.h"
#include "xla/stream_executor/event_based_timer.h"
#include "xla/stream_executor/fft.h"
#include "xla/stream_executor/gpu/context.h"
#include "xla/stream_executor/gpu/gpu_command_buffer.h"
#include "xla/stream_executor/gpu/gpu_driver.h"
#include "xla/stream_executor/gpu/gpu_event.h"
#include "xla/stream_executor/gpu/gpu_kernel.h"
#include "xla/stream_executor/gpu/gpu_semaphore.h"
#include "xla/stream_executor/gpu/gpu_stream.h"
#include "xla/stream_executor/gpu/gpu_timer.h"
#include "xla/stream_executor/gpu/gpu_types.h"
#include "xla/stream_executor/gpu/read_numa_node.h"
#include "xla/stream_executor/kernel.h"
#include "xla/stream_executor/kernel_spec.h"
#include "xla/stream_executor/launch_dim.h"
#include "xla/stream_executor/module_spec.h"
#include "xla/stream_executor/platform.h"
#include "xla/stream_executor/plugin_registry.h"
#include "xla/stream_executor/semantic_version.h"
#include "xla/stream_executor/stream.h"
#include "xla/stream_executor/stream_executor.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/fingerprint.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/statusor.h"
namespace stream_executor {
namespace gpu {
namespace {
bool ShouldLaunchDelayKernel() {
static bool value = [] {
const char* blocking = std::getenv("CUDA_LAUNCH_BLOCKING");
return !blocking || std::string_view{blocking} != "1";
}();
return value;
}
absl::Status FuncGetAttribute(CUfunction_attribute attribute, CUfunction func,
int* attribute_value) {
return cuda::ToStatus(
cuFuncGetAttribute(attribute_value, attribute, func),
absl::StrCat("Failed to query kernel attribute: ", attribute));
}
}
static CUdeviceptr AsCudaDevicePtr(const DeviceMemoryBase& gpu_mem) {
return reinterpret_cast<CUdeviceptr>(gpu_mem.opaque());
}
static CUdeviceptr AsCudaDevicePtr(DeviceMemoryBase* gpu_mem) {
return AsCudaDevicePtr(*gpu_mem);
}
CudaExecutor::~CudaExecutor() {
CHECK(kernel_to_gpu_binary_.empty()) << "GpuExecutor has live kernels.";
CHECK(gpu_binary_to_module_.empty()) << "GpuExecutor has loaded modules.";
if (gpu_context() != nullptr) {
GpuDriver::DestroyContext(gpu_context());
}
}
absl::Status CudaExecutor::Init() {
TF_RETURN_IF_ERROR(GpuDriver::Init());
TF_RETURN_IF_ERROR(GpuDriver::GetDevice(device_ordinal(), &device_));
Context* context;
TF_RETURN_IF_ERROR(
GpuDriver::CreateContext(device_ordinal(), device_, &context));
set_context(context);
TF_RETURN_IF_ERROR(
GpuDriver::GetComputeCapability(&cc_major_, &cc_minor_, device_));
TF_ASSIGN_OR_RETURN(delay_kernels_supported_, DelayKernelIsSupported());
return absl::OkStatus();
}
absl::StatusOr<bool> CudaExecutor::DelayKernelIsSupported() {
TF_ASSIGN_OR_RETURN(int status,
GpuDriver::GetDeviceAttribute(
CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, device_));
return static_cast<bool>(status);
}
absl::Status CudaExecutor::LoadModuleFromCuBin(const char* cubin,
CUmodule* module) {
uint64_t module_refcount;
std::tie(*module, module_refcount) = gpu_binary_to_module_[cubin];
if (*module == nullptr) {
TF_RETURN_IF_ERROR(GpuDriver::LoadCubin(gpu_context(), cubin, module));
module_refcount = 1;
VLOG(3) << "Loaded CUBIN " << static_cast<const void*>(cubin)
<< " as module " << *module;
} else {
++module_refcount;
VLOG(3) << "CUBIN " << static_cast<const void*>(cubin)
<< " is already loaded as module " << *module;
}
gpu_binary_to_module_[cubin] = {*module, module_refcount};
return absl::OkStatus();
}
absl::Status CudaExecutor::LoadModuleFromPtx(const char* ptx,
CUmodule* module) {
uint64_t module_refcount;
std::tie(*module, module_refcount) = gpu_binary_to_module_[ptx];
if (*module == nullptr) {
TF_RETURN_IF_ERROR(GpuDriver::LoadPtx(gpu_context(), ptx, module));
VLOG(3) << "Loaded PTX " << static_cast<const void*>(ptx) << " as module "
<< *module;
module_refcount = 1;
} else {
++module_refcount;
VLOG(3) << "PTX " << static_cast<const void*>(ptx)
<< " is already loaded as module " << module;
}
gpu_binary_to_module_[ptx] = {*module, module_refcount};
return absl::OkStatus();
}
absl::Status CudaExecutor::LoadModuleFromHsaco(const char* hsaco,
CUmodule* module) {
return absl::InternalError(
"Feature not supported on CUDA platform (LoadModuleFromHsaco)");
}
absl::StatusOr<std::unique_ptr<Kernel>> CudaExecutor::LoadKernel(
const MultiKernelLoaderSpec& spec) {
auto cuda_kernel = std::make_unique<CudaKernel>(this);
CUmodule module;
const std::string* kernel_name;
if (spec.has_cuda_cubin_in_memory()) {
absl::MutexLock lock{&in_memory_modules_mu_};
kernel_name = &spec.cuda_cubin_in_memory().kernel_name();
const char* cubin = reinterpret_cast<const char*>(
spec.cuda_cubin_in_memory().cubin_bytes().data());
TF_RETURN_IF_ERROR(LoadModuleFromCuBin(cubin, &module));
kernel_to_gpu_binary_[cuda_kernel.get()] = cubin;
} else if (spec.has_cuda_ptx_in_memory()) {
kernel_name = &spec.cuda_ptx_in_memory().kernel_name();
if (cc_major_ == 0 && cc_minor_ == 0) {
return absl::InternalError("Compute capability not set");
}
const char* ptx = spec.cuda_ptx_in_memory().text(cc_major_, cc_minor_);
if (ptx == nullptr) {
ptx = spec.cuda_ptx_in_memory().default_text();
}
if (ptx == nullptr) {
LOG(FATAL) << "Loader spec has no ptx for kernel " << *kernel_name;
}
absl::MutexLock lock{&in_memory_modules_mu_};
TF_RETURN_IF_ERROR(LoadModuleFromPtx(ptx, &module));
kernel_to_gpu_binary_[cuda_kernel.get()] = ptx;
} else if (spec.has_in_process_symbol()) {
kernel_name = &spec.in_process_symbol().kernel_name();
void* symbol = spec.in_process_symbol().symbol();
VLOG(2) << "Resolve CUDA kernel " << *kernel_name
<< " from symbol pointer: " << symbol;
TF_ASSIGN_OR_RETURN(
GpuFunctionHandle function,
CudaRuntime::GetFuncBySymbol(spec.in_process_symbol().symbol()));
cuda_kernel->set_gpu_function(function);
} else {
return absl::InternalError("No method of loading CUDA kernel provided");
}
VLOG(3) << "LoadKernel on kernel : " << *kernel_name;
if (!spec.has_in_process_symbol()) {
VLOG(2) << "getting function " << *kernel_name << " from module " << module;
GpuFunctionHandle function;
TF_RETURN_IF_ERROR(GpuDriver::GetModuleFunction(
gpu_context(), module, kernel_name->c_str(), &function));
cuda_kernel->set_gpu_function(function);
}
cuda_kernel->set_name(*kernel_name);
cuda_kernel->set_arity(spec.arity());
KernelMetadata kernel_metadata;
TF_RETURN_IF_ERROR(GetKernelMetadata(cuda_kernel.get(), &kernel_metadata));
cuda_kernel->set_metadata(kernel_metadata);
cuda_kernel->set_name(*kernel_name);
cuda_kernel->set_args_packing(spec.kernel_args_packing());
return std::move(cuda_kernel);
}
absl::StatusOr<std::unique_ptr<EventBasedTimer>>
CudaExecutor::CreateEventBasedTimer(GpuStream* stream, bool use_delay_kernel) {
GpuSemaphore semaphore{};
if (use_delay_kernel && ShouldLaunchDelayKernel() &&
delay_kernels_supported_) {
TF_ASSIGN_OR_RETURN(semaphore, LaunchDelayKernel(stream));
}
TF_ASSIGN_OR_RETURN(auto start_event, CreateGpuEvent(true));
TF_ASSIGN_OR_RETURN(auto stop_event, CreateGpuEvent(true));
TF_RETURN_IF_ERROR(start_event->Record(stream->gpu_stream()));
return std::make_unique<GpuTimer>(gpu_context(), std::move(start_event),
std::move(stop_event), stream,
std::move(semaphore));
}
bool CudaExecutor::UnloadGpuBinary(const void* gpu_binary) {
auto module_it = gpu_binary_to_module_.find(gpu_binary);
if (gpu_binary_to_module_.end() == module_it) {
VLOG(3) << "No loaded CUDA module for " << gpu_binary;
return false;
}
auto& module = module_it->second.first;
auto& refcount = module_it->second.second;
VLOG(3) << "Found CUDA module " << module << " with refcount " << refcount;
if (--refcount == 0) {
VLOG(3) << "Unloading CUDA module " << module;
GpuDriver::UnloadModule(gpu_context(), module);
gpu_binary_to_module_.erase(module_it);
}
return true;
}
void CudaExecutor::UnloadKernel(const Kernel* kernel) {
VLOG(3) << "Unloading kernel " << kernel << " : " << kernel->name();
absl::MutexLock lock{&in_memory_modules_mu_};
auto gpu_binary_it = kernel_to_gpu_binary_.find(kernel);
if (kernel_to_gpu_binary_.end() == gpu_binary_it) {
VLOG(3) << "Kernel " << kernel << " : " << kernel->name()
<< " has never been loaded.";
return;
}
VLOG(3) << "Kernel " << kernel << " : " << kernel->name()
<< " has loaded GPU code " << gpu_binary_it->second;
UnloadGpuBinary(gpu_binary_it->second);
kernel_to_gpu_binary_.erase(gpu_binary_it);
}
absl::Status CudaExecutor::LoadModule(const MultiModuleLoaderSpec& spec,
ModuleHandle* module_handle) {
CUmodule cu_module;
if (spec.has_cuda_cubin_in_memory()) {
absl::MutexLock lock{&in_memory_modules_mu_};
TF_RETURN_IF_ERROR(LoadModuleFromCuBin(
reinterpret_cast<const char*>(spec.cuda_cubin_in_memory().data()),
&cu_module));
*module_handle = ModuleHandle(const_cast<void*>(
static_cast<const void*>(spec.cuda_cubin_in_memory().data())));
return absl::OkStatus();
} else if (spec.has_cuda_ptx_in_memory()) {
if (cc_major_ == 0 && cc_minor_ == 0) {
return absl::InternalError("Compute capability not set");
}
if (!spec.cuda_ptx_in_memory()) {
return absl::InternalError("PTX not found in spec");
}
absl::MutexLock lock{&in_memory_modules_mu_};
TF_RETURN_IF_ERROR(
LoadModuleFromPtx(spec.cuda_ptx_in_memory(), &cu_module));
*module_handle = ModuleHandle(
const_cast<void*>(static_cast<const void*>(spec.cuda_ptx_in_memory())));
return absl::OkStatus();
}
return absl::InternalError("No method of loading CUDA module provided");
}
bool CudaExecutor::UnloadModule(ModuleHandle module_handle) {
const char* gpu_binary = reinterpret_cast<const char*>(module_handle.id());
absl::MutexLock lock{&in_memory_modules_mu_};
return UnloadGpuBinary(gpu_binary);
}
namespace {
absl::uint128 Fingerprint128(const absl::string_view s) {
auto fp = tsl::Fingerprint128(s);
return absl::MakeUint128(fp.high64, fp.low64);
}
int fpus_per_core(int cc_major, int cc_minor) {
int n = 128;
if (cc_major == 3) {
n = 192;
} else if ((cc_major == 6 && cc_minor == 0) || (cc_major == 7) ||
(cc_major == 8 && cc_minor == 0)) {
n = 64;
}
return n;
}
}
absl::StatusOr<std::shared_ptr<DeviceMemoryBase>>
CudaExecutor::CreateOrShareConstant(Stream* stream,
absl::Span<const uint8_t> content) {
absl::MutexLock lock{&shared_constants_mu_};
absl::uint128 fingerprint = Fingerprint128(absl::string_view(
reinterpret_cast<const char*>(content.data()), content.size()));
auto insert_result = shared_constants_.insert(
{fingerprint, std::weak_ptr<DeviceMemoryBase>()});
auto it = insert_result.first;
bool was_already_in_cache = !insert_result.second;
std::shared_ptr<DeviceMemoryBase> shared_constant;
if (was_already_in_cache) {
shared_constant = it->second.lock();
}
if (shared_constant == nullptr) {
auto new_constant = std::make_unique<DeviceMemoryBase>(
Allocate(content.size(), 0));
if (new_constant->opaque() == nullptr) {
return absl::InternalError(absl::StrFormat(
"Failed to allocate %d bytes for new constant", content.size()));
}
TF_RETURN_IF_ERROR(
stream->Memcpy(new_constant.get(), content.data(), content.size()));
absl::Status status = stream->BlockHostUntilDone();
if (!status.ok()) {
Deallocate(new_constant.get());
status.Update(absl::InternalError(absl::StrFormat(
"Memcpy to device address %p failed", new_constant->opaque())));
return status;
}
shared_constant = std::shared_ptr<DeviceMemoryBase>(
new_constant.release(), [this](DeviceMemoryBase* p) {
Deallocate(p);
delete p;
});
it->second = std::weak_ptr<DeviceMemoryBase>(shared_constant);
}
return shared_constant;
}
absl::Status CudaExecutor::GetKernelMetadata(GpuKernel* cuda_kernel,
KernelMetadata* kernel_metadata) {
int value;
TF_RETURN_IF_ERROR(FuncGetAttribute(CU_FUNC_ATTRIBUTE_NUM_REGS,
cuda_kernel->gpu_function(), &value));
kernel_metadata->set_registers_per_thread(value);
TF_RETURN_IF_ERROR(FuncGetAttribute(CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES,
cuda_kernel->gpu_function(), &value));
kernel_metadata->set_shared_memory_bytes(value);
return absl::OkStatus();
}
DeviceMemoryBase CudaExecutor::Allocate(uint64_t size, int64_t memory_space) {
if (memory_space == 1) {
auto result =
CudaCollectives::CollectiveMemoryAllocate(gpu_context(), size);
if (!result.ok()) {
LOG(ERROR) << result.status();
}
return DeviceMemoryBase(nullptr, 0);
} else if (memory_space ==
static_cast<int64_t>(stream_executor::MemoryType::kHost)) {
return DeviceMemoryBase(GpuDriver::HostAllocate(gpu_context(), size), size);
}
CHECK_EQ(memory_space, 0);
return DeviceMemoryBase(GpuDriver::DeviceAllocate(gpu_context(), size), size);
}
void CudaExecutor::Deallocate(DeviceMemoryBase* mem) {
auto status_or_memory_space = GetPointerMemorySpace(mem->opaque());
if (!status_or_memory_space.ok()) {
LOG(ERROR) << status_or_memory_space.status();
return;
}
auto memory_space = status_or_memory_space.value();
if (memory_space == MemoryType::kHost) {
GpuDriver::HostDeallocate(gpu_context(), mem->opaque());
} else {
GpuDriver::DeviceDeallocate(gpu_context(), mem->opaque());
}
}
bool CudaExecutor::SynchronizeAllActivity() {
return GpuDriver::SynchronizeContext(gpu_context()).ok();
}
bool CudaExecutor::HostMemoryRegister(void* location, uint64_t size) {
VLOG(1) << "Called StreamExecutor::HostMemoryRegister(data=" << location
<< ")";
return GpuDriver::HostRegister(gpu_context(), location, size);
}
bool CudaExecutor::HostMemoryUnregister(void* location) {
VLOG(1) << "Called StreamExecutor::HostUnregister(data=" << location << ")";
return GpuDriver::HostUnregister(gpu_context(), location);
}
absl::Status CudaExecutor::SynchronousMemZero(DeviceMemoryBase* location,
uint64_t size) {
if (reinterpret_cast<uintptr_t>(location->opaque()) % 4 == 0 &&
size % 4 == 0) {
return GpuDriver::SynchronousMemsetUint32(
gpu_context(), AsCudaDevicePtr(location), 0x0, size / 4);
}
return GpuDriver::SynchronousMemsetUint8(
gpu_context(), AsCudaDevicePtr(location), 0x0, size);
}
absl::Status CudaExecutor::SynchronousMemcpy(DeviceMemoryBase* gpu_dst,
const void* host_src,
uint64_t size) {
return GpuDriver::SynchronousMemcpyH2D(
gpu_context(), AsCudaDevicePtr(gpu_dst), host_src, size);
}
absl::Status CudaExecutor::SynchronousMemcpy(void* host_dst,
const DeviceMemoryBase& gpu_src,
uint64_t size) {
return GpuDriver::SynchronousMemcpyD2H(gpu_context(), host_dst,
AsCudaDevicePtr(gpu_src), size);
}
void CudaExecutor::DeallocateStream(Stream* stream) {
{
absl::MutexLock lock(&mu_);
if (dnn_ != nullptr) {
dnn_->NotifyStreamDestroyed(stream);
}
}
GpuStream* gpu_stream = AsGpuStream(stream);
absl::MutexLock l(&alive_gpu_streams_mu_);
alive_gpu_streams_.erase(gpu_stream->gpu_stream());
}
absl::Status CudaExecutor::BlockHostUntilDone(Stream* stream) {
return GpuDriver::SynchronizeStream(gpu_context(), AsGpuStreamValue(stream));
}
blas::BlasSupport* CudaExecutor::AsBlas() {
absl::MutexLock lock(&mu_);
if (blas_ != nullptr) {
return blas_.get();
}
PluginRegistry* registry = PluginRegistry::Instance();
absl::StatusOr<PluginRegistry::BlasFactory> status =
registry->GetFactory<PluginRegistry::BlasFactory>(cuda::kCudaPlatformId);
if (!status.ok()) {
LOG(ERROR) << "Unable to retrieve BLAS factory: "
<< status.status().message();
return nullptr;
}
auto blas = status.value()(this);
blas_.reset(blas);
return blas_.get();
}
dnn::DnnSupport* CudaExecutor::AsDnn() {
absl::MutexLock lock(&mu_);
if (dnn_ != nullptr) {
return dnn_.get();
}
PluginRegistry* registry = PluginRegistry::Instance();
absl::StatusOr<PluginRegistry::DnnFactory> status =
registry->GetFactory<PluginRegistry::DnnFactory>(cuda::kCudaPlatformId);
if (!status.ok()) {
LOG(ERROR) << "Unable to retrieve DNN factory: "
<< status.status().message();
return nullptr;
}
auto dnn = status.value()(this);
dnn_.reset(dnn);
return dnn_.get();
}
fft::FftSupport* CudaExecutor::AsFft() {
absl::MutexLock lock(&mu_);
if (fft_ != nullptr) {
return fft_.get();
}
PluginRegistry* registry = PluginRegistry::Instance();
absl::StatusOr<PluginRegistry::FftFactory> status =
registry->GetFactory<PluginRegistry::FftFactory>(cuda::kCudaPlatformId);
if (!status.ok()) {
LOG(ERROR) << "Unable to retrieve FFT factory: "
<< status.status().message();
return nullptr;
}
auto fft = status.value()(this);
fft_.reset(fft);
return fft_.get();
}
bool CudaExecutor::CanEnablePeerAccessTo(StreamExecutor* other) {
GpuExecutor* cuda_other = static_cast<GpuExecutor*>(other);
return GpuDriver::CanEnablePeerAccess(gpu_context(),
cuda_other->gpu_context());
}
absl::Status CudaExecutor::EnablePeerAccessTo(StreamExecutor* other) {
GpuExecutor* cuda_other = static_cast<GpuExecutor*>(other);
return GpuDriver::EnablePeerAccess(gpu_context(), cuda_other->gpu_context());
}
bool CudaExecutor::DeviceMemoryUsage(int64_t* free, int64_t* total) const {
return GpuDriver::GetDeviceMemoryInfo(gpu_context(), free, total);
}
absl::StatusOr<DeviceMemoryBase> CudaExecutor::GetSymbol(
const std::string& symbol_name, ModuleHandle module_handle) {
void* mem = nullptr;
size_t bytes = 0;
CHECK(static_cast<bool>(module_handle));
{
absl::MutexLock lock{&in_memory_modules_mu_};
auto it = gpu_binary_to_module_.find(module_handle.id());
CHECK(it != gpu_binary_to_module_.end());
GpuModuleHandle gpu_module_handle = it->second.first;
CHECK(gpu_module_handle != nullptr);
TF_RETURN_IF_ERROR(GpuDriver::GetModuleSymbol(
gpu_context(), gpu_module_handle, symbol_name.c_str(),
reinterpret_cast<CUdeviceptr*>(&mem), &bytes));
return DeviceMemoryBase(mem, bytes);
}
return absl::NotFoundError(
absl::StrCat("Check if module containing symbol ", symbol_name,
" is loaded (module_handle = ",
reinterpret_cast<uintptr_t>(module_handle.id()), ")"));
}
absl::Status FillBlockDimLimit(GpuDeviceHandle device,
BlockDim* block_dim_limit) {
int x, y, z;
TF_RETURN_IF_ERROR(GpuDriver::GetGridLimits(&x, &y, &z, device));
block_dim_limit->x = x;
block_dim_limit->y = y;
block_dim_limit->z = z;
return absl::OkStatus();
}
absl::StatusOr<std::unique_ptr<GpuEvent>> CudaExecutor::CreateGpuEvent(
bool allow_timing) {
auto gpu_event = std::make_unique<CudaEvent>(gpu_context());
TF_RETURN_IF_ERROR(gpu_event->Init(allow_timing));
return std::move(gpu_event);
}
absl::StatusOr<std::unique_ptr<Event>> CudaExecutor::CreateEvent() {
return CreateGpuEvent(false);
}
absl::StatusOr<std::unique_ptr<Stream>> CudaExecutor::CreateStream(
std::optional<std::variant<StreamPriority, int>> priority) {
TF_ASSIGN_OR_RETURN(auto event, CreateGpuEvent(false));
auto stream = std::make_unique<GpuStream>(this, std::move(event), priority);
absl::MutexLock l(&alive_gpu_streams_mu_);
TF_RETURN_IF_ERROR(stream->Init());
auto gpu_stream = stream->gpu_stream();
alive_gpu_streams_[gpu_stream] = stream.get();
return std::move(stream);
}
absl::StatusOr<std::unique_ptr<CommandBuffer>>
CudaExecutor::CreateCommandBuffer(CommandBuffer::Mode mode) {
VLOG(2) << "Create CUDA command buffer (CUDA graph)";
GpuGraphHandle graph = nullptr;
TF_RETURN_IF_ERROR(GpuDriver::CreateGraph(&graph));
return std::make_unique<GpuCommandBuffer>(mode, this, graph);
}
absl::Status CudaExecutor::TrimGraphMemory() {
return GpuDriver::DeviceGraphMemTrim(device_);
}
absl::StatusOr<std::unique_ptr<DeviceDescription>>
CudaExecutor::CreateDeviceDescription(int device_ordinal) {
GpuDeviceHandle device;
TF_RETURN_IF_ERROR(GpuDriver::GetDevice(device_ordinal, &device));
int cc_major;
int cc_minor;
TF_RETURN_IF_ERROR(
GpuDriver::GetComputeCapability(&cc_major, &cc_minor, device));
DeviceDescription desc;
desc.set_driver_version(
ParseCudaVersion(GpuDriver::GetDriverVersion().value_or(0))
.value_or(SemanticVersion{0, 0, 0}));
desc.set_runtime_version(
ParseCudaVersion(CudaRuntime::GetRuntimeVersion().value_or(0))
.value_or(SemanticVersion{0, 0, 0}));
desc.set_compile_time_toolkit_version(
ParseCudaVersion(CUDA_VERSION).value_or(SemanticVersion{0, 0, 0}));
{
std::string pci_bus_id = GpuDriver::GetPCIBusID(device);
pci_bus_id = absl::AsciiStrToLower(pci_bus_id);
desc.set_pci_bus_id(pci_bus_id);
int numa_node = ReadNumaNode(pci_bus_id, device_ordinal);
desc.set_numa_node(numa_node);
}
{
desc.set_threads_per_block_limit(
GpuDriver::GetDeviceAttribute(CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
device)
.value());
ThreadDim thread_dim_limit;
thread_dim_limit.x = GpuDriver::GetDeviceAttribute(
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, device)
.value();
thread_dim_limit.y = GpuDriver::GetDeviceAttribute(
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, device)
.value();
thread_dim_limit.z = GpuDriver::GetDeviceAttribute(
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, device)
.value();
desc.set_thread_dim_limit(thread_dim_limit);
}
int sm_clock_khz =
GpuDriver::GetDeviceAttribute(CU_DEVICE_ATTRIBUTE_CLOCK_RATE, device)
.value();
desc.set_clock_rate_ghz(static_cast<float>(sm_clock_khz) / 1e6);
{
bool ecc_enabled = false;
(void)GpuDriver::IsEccEnabled(device, &ecc_enabled);
desc.set_ecc_enabled(ecc_enabled);
}
uint64_t device_memory_size = static_cast<uint64_t>(-1);
(void)GpuDriver::GetDeviceTotalMemory(device, &device_memory_size);
desc.set_device_memory_size(device_memory_size);
int64_t l2_cache_bytes =
GpuDriver::GetDeviceAttribute(CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, device)
.value();
desc.set_l2_cache_size(l2_cache_bytes);
absl::StatusOr<int> mem_clock_khz = GpuDriver::GetDeviceAttribute(
CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, device_ordinal);
absl::StatusOr<int> mem_bus_width_bits = GpuDriver::GetDeviceAttribute(
CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, device_ordinal);
if (mem_clock_khz.ok() && mem_bus_width_bits.ok()) {
desc.set_memory_bandwidth(2 * int64_t{mem_clock_khz.value()} * 1000 *
int64_t{mem_bus_width_bits.value()} / 8);
}
{
BlockDim block_dim_limit;
TF_RETURN_IF_ERROR(FillBlockDimLimit(device, &block_dim_limit));
desc.set_block_dim_limit(block_dim_limit);
}
{
std::string device_name;
TF_RETURN_IF_ERROR(GpuDriver::GetDeviceName(device, &device_name));
desc.set_name(device_name);
}
desc.set_platform_version(
absl::StrCat("Compute Capability ", cc_major, ".", cc_minor));
desc.set_device_address_bits(64);
desc.set_device_vendor("NVIDIA Corporation");
desc.set_cuda_compute_capability(cc_major, cc_minor);
desc.set_shared_memory_per_core(
GpuDriver::GetMaxSharedMemoryPerCore(device).value());
desc.set_shared_memory_per_block(
GpuDriver::GetMaxSharedMemoryPerBlock(device).value());
desc.set_shared_memory_per_block_optin(
GpuDriver::GetMaxSharedMemoryPerBlockOptin(device).value());
int core_count = GpuDriver::GetMultiprocessorCount(device).value();
desc.set_core_count(core_count);
desc.set_fpus_per_core(fpus_per_core(cc_major, cc_minor));
desc.set_threads_per_core_limit(
GpuDriver::GetMaxThreadsPerMultiprocessor(device).value());
desc.set_registers_per_block_limit(
GpuDriver::GetMaxRegistersPerBlock(device).value());
desc.set_threads_per_warp(GpuDriver::GetThreadsPerWarp(device).value());
desc.set_registers_per_core_limit(
GpuDriver::GetDeviceAttribute(
CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR, device)
.value());
auto value_or = [](const auto& status_or, auto default_val) {
if (status_or.ok()) return *status_or;
return default_val;
};
desc.set_model_str(absl::StrFormat(
"sm_%d.%d with %dB RAM, %d cores, %dKHz clock, %dKHz mem clock, %dB L2$",
cc_major, cc_minor, device_memory_size, core_count, sm_clock_khz,
value_or(mem_clock_khz, 0), l2_cache_bytes));
return std::make_unique<DeviceDescription>(std::move(desc));
}
}
} | #include "xla/stream_executor/cuda/cuda_executor.h"
#include <memory>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "xla/stream_executor/device_description.h"
#include "xla/stream_executor/gpu/gpu_driver.h"
#include "xla/stream_executor/semantic_version.h"
#include "xla/tsl/lib/core/status_test_util.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace stream_executor::gpu {
namespace {
using testing::Ge;
using testing::IsEmpty;
using testing::Not;
using testing::VariantWith;
TEST(CudaExecutorTest, CreateDeviceDescription) {
TF_ASSERT_OK(GpuDriver::Init());
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DeviceDescription> result,
CudaExecutor::CreateDeviceDescription(0));
constexpr SemanticVersion kNullVersion{0, 0, 0};
EXPECT_NE(result->runtime_version(), kNullVersion);
EXPECT_NE(result->driver_version(), kNullVersion);
EXPECT_NE(result->compile_time_toolkit_version(), kNullVersion);
EXPECT_THAT(result->platform_version(), Not(IsEmpty()));
EXPECT_THAT(result->name(), Not(IsEmpty()));
EXPECT_THAT(result->model_str(), Not(IsEmpty()));
EXPECT_THAT(result->device_vendor(), "NVIDIA Corporation");
EXPECT_THAT(
result->gpu_compute_capability(),
VariantWith<CudaComputeCapability>(Ge(CudaComputeCapability{1, 0})));
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/stream_executor/cuda/cuda_executor.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/stream_executor/cuda/cuda_executor_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
c0931f4d-cd5e-4947-b16f-94cba53908d8 | cpp | tensorflow/tensorflow | cl_arguments | tensorflow/lite/delegates/gpu/cl/cl_arguments.cc | tensorflow/lite/delegates/gpu/cl/cl_arguments_test.cc | #include "tensorflow/lite/delegates/gpu/cl/cl_arguments.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/substitute.h"
#include "tensorflow/lite/delegates/gpu/cl/buffer.h"
#include "tensorflow/lite/delegates/gpu/cl/gpu_object.h"
#include "tensorflow/lite/delegates/gpu/cl/qcom_thin_filter.h"
#include "tensorflow/lite/delegates/gpu/cl/tensor.h"
#include "tensorflow/lite/delegates/gpu/common/task/util.h"
#include "tensorflow/lite/delegates/gpu/common/util.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
bool IsWordSymbol(char symbol) {
return absl::ascii_isalnum(symbol) || symbol == '_';
}
void ReplaceAllWords(const std::string& old_word, const std::string& new_word,
std::string* str) {
size_t position = str->find(old_word);
while (position != std::string::npos) {
char prev = position == 0 ? '.' : (*str)[position - 1];
char next = position + old_word.size() < str->size()
? (*str)[position + old_word.size()]
: '.';
if (IsWordSymbol(prev) || IsWordSymbol(next)) {
position = str->find(old_word, position + 1);
continue;
}
str->replace(position, old_word.size(), new_word);
position = str->find(old_word, position + new_word.size());
}
}
void AppendArgument(const std::string& arg, std::string* args) {
if (!args->empty()) {
absl::StrAppend(args, ",\n ");
}
absl::StrAppend(args, arg);
}
std::string GetImageModifier(AccessType access) {
switch (access) {
case AccessType::READ:
return "__read_only";
case AccessType::WRITE:
return "__write_only";
case AccessType::READ_WRITE:
return "__read_write";
}
}
std::string GetDefaultSamplers(const GpuInfo& gpu_info) {
std::string result;
result +=
"__constant sampler_t smp_none = CLK_NORMALIZED_COORDS_FALSE | "
"CLK_ADDRESS_NONE | CLK_FILTER_NEAREST;\n";
if (gpu_info.IsAdreno() && gpu_info.adreno_info.IsAdreno3xx()) {
result +=
"__constant sampler_t smp_zero = CLK_NORMALIZED_COORDS_FALSE | "
"CLK_ADDRESS_NONE | CLK_FILTER_NEAREST;\n";
} else {
result +=
"__constant sampler_t smp_zero = CLK_NORMALIZED_COORDS_FALSE | "
"CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;\n";
}
return result;
}
absl::Status CreateCLObject(GPUObjectDescriptor* desc, CLContext* context,
GPUObjectPtr* result) {
const auto* buffer_desc = dynamic_cast<const BufferDescriptor*>(desc);
if (buffer_desc) {
Buffer gpu_buffer;
RETURN_IF_ERROR(
gpu_buffer.CreateFromBufferDescriptor(*buffer_desc, context));
*result = std::make_unique<Buffer>(std::move(gpu_buffer));
return absl::OkStatus();
}
const auto* tensor_desc = dynamic_cast<const TensorDescriptor*>(desc);
if (tensor_desc) {
Tensor gpu_tensor;
RETURN_IF_ERROR(gpu_tensor.CreateFromDescriptor(*tensor_desc, context));
*result = std::make_unique<Tensor>(std::move(gpu_tensor));
return absl::OkStatus();
}
const auto* qcom_thin_filter_desc =
dynamic_cast<const QcomThinFilterDescriptor*>(desc);
if (qcom_thin_filter_desc) {
QcomThinFilter thin_filter;
RETURN_IF_ERROR(
thin_filter.CreateFromDescriptor(*qcom_thin_filter_desc, context));
*result = std::make_unique<QcomThinFilter>(std::move(thin_filter));
return absl::OkStatus();
}
return absl::InvalidArgumentError("Unknown GPU descriptor.");
}
}
constexpr char CLArguments::kArgsPrefix[];
absl::Status CLArguments::Init(const GpuInfo& gpu_info, CLContext* context,
Arguments* args, std::string* code) {
RETURN_IF_ERROR(AllocateObjects(*args, context));
RETURN_IF_ERROR(AddObjectArgs(gpu_info, *args));
args->MoveObjectRefs(&object_refs_);
const bool use_f32_for_halfs = gpu_info.IsPowerVR();
CopyArguments(*args, use_f32_for_halfs);
RETURN_IF_ERROR(SetObjectsResources(*args));
RenameArgumentsInCode(code);
args->ResolveArgsPass(code);
*code = absl::Substitute(*code, GetListOfArgs());
if (gpu_info.SupportsImages()) {
*code = GetDefaultSamplers(gpu_info) + *code;
}
return absl::OkStatus();
}
absl::Status CLArguments::Init(const GpuInfo& gpu_info, Arguments* args,
CLContext* context) {
RETURN_IF_ERROR(AllocateObjects(*args, context));
RETURN_IF_ERROR(AddObjectArgs(gpu_info, *args));
args->MoveObjectRefs(&object_refs_);
const bool use_f32_for_halfs = gpu_info.IsPowerVR();
CopyArguments(*args, use_f32_for_halfs);
RETURN_IF_ERROR(SetObjectsResources(*args));
return absl::OkStatus();
}
absl::Status CLArguments::AllocateObjects(const Arguments& args,
CLContext* context) {
objects_.resize(args.GetObjects().size());
int i = 0;
for (auto& t : args.GetObjects()) {
RETURN_IF_ERROR(CreateCLObject(t.second.get(), context, &objects_[i]));
i++;
}
return absl::OkStatus();
}
absl::Status CLArguments::AddObjectArgs(const GpuInfo& gpu_info,
const Arguments& args) {
for (const auto& t : args.GetObjects()) {
AddGPUResources(t.first, t.second->GetGPUResources(gpu_info));
}
for (const auto& t : args.GetObjectRefs()) {
AddGPUResources(t.first, t.second->GetGPUResources(gpu_info));
}
return absl::OkStatus();
}
absl::Status CLArguments::SetObjectsResources(const Arguments& args) {
int i = 0;
for (const auto& t : args.GetObjects()) {
GPUResourcesWithValue resources;
RETURN_IF_ERROR(objects_[i]->GetGPUResources(t.second.get(), &resources));
RETURN_IF_ERROR(SetGPUResources(t.first, resources));
i++;
}
return absl::OkStatus();
}
void CLArguments::CopyArguments(const Arguments& args, bool use_f32_for_halfs) {
for (const auto& fvalue : args.GetFloatValues()) {
auto& new_val = float_values_[fvalue.first];
new_val.value = fvalue.second.value;
new_val.active = fvalue.second.active;
if (fvalue.second.active) {
new_val.offset = shared_float4s_data_.size();
shared_float4s_data_.push_back(new_val.value);
}
}
for (const auto& ivalue : args.GetIntValues()) {
auto& new_val = int_values_[ivalue.first];
new_val.value = ivalue.second.value;
new_val.active = ivalue.second.active;
if (ivalue.second.active) {
new_val.offset = shared_int4s_data_.size();
shared_int4s_data_.push_back(new_val.value);
}
}
for (const auto& hfvalue : args.GetHalfValues()) {
auto& new_val = half_values_[hfvalue.first];
new_val.value = hfvalue.second.value;
new_val.active = hfvalue.second.active;
if (hfvalue.second.active) {
if (use_f32_for_halfs) {
new_val.store_as_f32 = true;
new_val.offset = shared_float4s_data_.size();
shared_float4s_data_.push_back(new_val.value);
} else {
new_val.store_as_f32 = false;
new_val.offset = shared_half4s_data_.size();
shared_half4s_data_.push_back(new_val.value);
}
}
}
int shared_int4s_aligned_size = AlignByN(shared_int4s_data_.size(), 4);
shared_int4s_data_.resize(shared_int4s_aligned_size);
int shared_float4s_aligned_size = AlignByN(shared_float4s_data_.size(), 4);
shared_float4s_data_.resize(shared_float4s_aligned_size);
int shared_half4s_aligned_size = AlignByN(shared_half4s_data_.size(), 4);
shared_half4s_data_.resize(shared_half4s_aligned_size);
}
void CLArguments::RenameArgumentsInCode(std::string* code) {
const std::string postfixes[4] = {"x", "y", "z", "w"};
for (const auto& fvalue : float_values_) {
if (fvalue.second.active) {
std::string index = std::to_string(fvalue.second.offset / 4);
std::string new_name =
"shared_float4_" + index + "." + postfixes[fvalue.second.offset % 4];
ReplaceAllWords(kArgsPrefix + fvalue.first, new_name, code);
}
}
for (const auto& ivalue : int_values_) {
if (ivalue.second.active) {
std::string index = std::to_string(ivalue.second.offset / 4);
std::string new_name =
"shared_int4_" + index + "." + postfixes[ivalue.second.offset % 4];
ReplaceAllWords(kArgsPrefix + ivalue.first, new_name, code);
}
}
for (const auto& hfvalue : half_values_) {
if (hfvalue.second.active) {
std::string index = std::to_string(hfvalue.second.offset / 4);
std::string new_name;
if (hfvalue.second.store_as_f32) {
new_name = "(half)(shared_float4_" + index + "." +
postfixes[hfvalue.second.offset % 4] + ")";
} else {
new_name = "shared_half4_" + index + "." +
postfixes[hfvalue.second.offset % 4];
}
ReplaceAllWords(kArgsPrefix + hfvalue.first, new_name, code);
}
}
}
void CLArguments::AddBuffer(const std::string& name,
const GPUBufferDescriptor& desc) {
buffers_[name].desc = desc;
}
void CLArguments::AddImage2D(const std::string& name,
const GPUImage2DDescriptor& desc) {
images2d_[name].desc = desc;
}
void CLArguments::AddImage2DArray(const std::string& name,
const GPUImage2DArrayDescriptor& desc) {
image2d_arrays_[name].desc = desc;
}
void CLArguments::AddImage3D(const std::string& name,
const GPUImage3DDescriptor& desc) {
images3d_[name].desc = desc;
}
void CLArguments::AddImageBuffer(const std::string& name,
const GPUImageBufferDescriptor& desc) {
image_buffers_[name].desc = desc;
}
void CLArguments::AddCustomMemory(const std::string& name,
const GPUCustomMemoryDescriptor& desc) {
custom_memories_[name].desc = desc;
}
void CLArguments::AddGPUResources(const std::string& name,
const GPUResources& resources) {
for (const auto& r : resources.buffers) {
AddBuffer(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.images2d) {
AddImage2D(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.image2d_arrays) {
AddImage2DArray(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.images3d) {
AddImage3D(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.image_buffers) {
AddImageBuffer(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.custom_memories) {
AddCustomMemory(absl::StrCat(name, "_", r.first), r.second);
}
}
absl::Status CLArguments::SetInt(const std::string& name, int value) {
auto it = int_values_.find(name);
if (it == int_values_.end()) {
return absl::NotFoundError(
absl::StrCat("No int argument with name - ", name));
}
it->second.value = value;
if (it->second.active) {
shared_int4s_data_[it->second.offset] = value;
}
return absl::OkStatus();
}
absl::Status CLArguments::SetFloat(const std::string& name, float value) {
auto it = float_values_.find(name);
if (it == float_values_.end()) {
return absl::NotFoundError(
absl::StrCat("No float argument with name - ", name));
}
it->second.value = value;
if (it->second.active) {
shared_float4s_data_[it->second.offset] = value;
}
return absl::OkStatus();
}
absl::Status CLArguments::SetHalf(const std::string& name, half value) {
auto it = half_values_.find(name);
if (it == half_values_.end()) {
return absl::NotFoundError(
absl::StrCat("No half argument with name - ", name));
}
it->second.value = value;
if (it->second.active) {
if (it->second.store_as_f32) {
shared_float4s_data_[it->second.offset] = value;
} else {
shared_half4s_data_[it->second.offset] = value;
}
}
return absl::OkStatus();
}
absl::Status CLArguments::SetImage2D(const std::string& name, cl_mem memory) {
auto it = images2d_.find(name);
if (it == images2d_.end()) {
return absl::NotFoundError(
absl::StrCat("No image2D argument with name - ", name));
}
it->second.memory = memory;
return absl::OkStatus();
}
absl::Status CLArguments::SetBuffer(const std::string& name, cl_mem memory) {
auto it = buffers_.find(name);
if (it == buffers_.end()) {
return absl::NotFoundError(
absl::StrCat("No buffer argument with name - ", name));
}
it->second.memory = memory;
return absl::OkStatus();
}
absl::Status CLArguments::SetImage2DArray(const std::string& name,
cl_mem memory) {
auto it = image2d_arrays_.find(name);
if (it == image2d_arrays_.end()) {
return absl::NotFoundError(
absl::StrCat("No image2D array argument with name - ", name));
}
it->second.memory = memory;
return absl::OkStatus();
}
absl::Status CLArguments::SetImage3D(const std::string& name, cl_mem memory) {
auto it = images3d_.find(name);
if (it == images3d_.end()) {
return absl::NotFoundError(
absl::StrCat("No image3D argument with name - ", name));
}
it->second.memory = memory;
return absl::OkStatus();
}
absl::Status CLArguments::SetImageBuffer(const std::string& name,
cl_mem memory) {
auto it = image_buffers_.find(name);
if (it == image_buffers_.end()) {
return absl::NotFoundError(
absl::StrCat("No image buffer argument with name - ", name));
}
it->second.memory = memory;
return absl::OkStatus();
}
absl::Status CLArguments::SetCustomMemory(const std::string& name,
cl_mem memory) {
auto it = custom_memories_.find(name);
if (it == custom_memories_.end()) {
return absl::NotFoundError(
absl::StrCat("No custom memory argument with name - ", name));
}
it->second.memory = memory;
return absl::OkStatus();
}
absl::Status CLArguments::SetObjectRef(const std::string& name,
const GPUObject* object) {
auto it = object_refs_.find(name);
if (it == object_refs_.end()) {
return absl::NotFoundError(
absl::StrCat("No object ref with name - ", name));
}
GPUResourcesWithValue resources;
RETURN_IF_ERROR(object->GetGPUResources(it->second.get(), &resources));
return SetGPUResources(name, resources);
}
absl::Status CLArguments::SetGPUResources(
const std::string& name, const GPUResourcesWithValue& resources) {
for (const auto& r : resources.generic.ints) {
RETURN_IF_ERROR(SetInt(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.generic.floats) {
RETURN_IF_ERROR(SetFloat(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.buffers) {
RETURN_IF_ERROR(SetBuffer(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.images2d) {
RETURN_IF_ERROR(SetImage2D(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.image2d_arrays) {
RETURN_IF_ERROR(
SetImage2DArray(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.images3d) {
RETURN_IF_ERROR(SetImage3D(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.image_buffers) {
RETURN_IF_ERROR(SetImageBuffer(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.custom_memories) {
RETURN_IF_ERROR(
SetCustomMemory(absl::StrCat(name, "_", r.first), r.second));
}
return absl::OkStatus();
}
std::string CLArguments::GetListOfArgs() {
std::string result;
for (auto& t : buffers_) {
const std::string type_name =
t.second.desc.data_type == DataType::FLOAT32 ? "float" : "half";
std::string attributes;
for (const auto& attr : t.second.desc.attributes) {
attributes += absl::StrCat(" __attribute__((", attr, "))");
}
std::string cl_type;
if (t.second.desc.data_type == DataType::BOOL) {
cl_type = ToCLDataType(DataType::UINT8, t.second.desc.element_size);
} else {
cl_type =
ToCLDataType(t.second.desc.data_type, t.second.desc.element_size);
}
AppendArgument(absl::StrCat(MemoryTypeToCLType(t.second.desc.memory_type),
" ", cl_type, "* ", t.first, attributes),
&result);
}
for (auto& t : image_buffers_) {
AppendArgument(absl::StrCat(GetImageModifier(t.second.desc.access_type),
" image1d_buffer_t ", t.first),
&result);
}
for (auto& t : images2d_) {
AppendArgument(absl::StrCat(GetImageModifier(t.second.desc.access_type),
" image2d_t ", t.first),
&result);
}
for (auto& t : image2d_arrays_) {
AppendArgument(absl::StrCat(GetImageModifier(t.second.desc.access_type),
" image2d_array_t ", t.first),
&result);
}
for (auto& t : images3d_) {
AppendArgument(absl::StrCat(GetImageModifier(t.second.desc.access_type),
" image3d_t ", t.first),
&result);
}
for (auto& t : custom_memories_) {
AppendArgument(absl::StrCat(t.second.desc.type_name, " ", t.first),
&result);
}
for (int i = 0; i < shared_int4s_data_.size() / 4; ++i) {
AppendArgument(absl::StrCat("int4 shared_int4_", i), &result);
}
for (int i = 0; i < shared_float4s_data_.size() / 4; ++i) {
AppendArgument(absl::StrCat("float4 shared_float4_", i), &result);
}
for (int i = 0; i < shared_half4s_data_.size() / 4; ++i) {
AppendArgument(absl::StrCat("half4 shared_half4_", i), &result);
}
return result;
}
absl::Status CLArguments::Bind(cl_kernel kernel, int offset) {
for (auto& t : buffers_) {
const int error_code =
clSetKernelArg(kernel, offset, sizeof(cl_mem), &t.second.memory);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (auto& t : image_buffers_) {
const int error_code =
clSetKernelArg(kernel, offset, sizeof(cl_mem), &t.second.memory);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (auto& t : images2d_) {
const int error_code =
clSetKernelArg(kernel, offset, sizeof(cl_mem), &t.second.memory);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (auto& t : image2d_arrays_) {
const int error_code =
clSetKernelArg(kernel, offset, sizeof(cl_mem), &t.second.memory);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (auto& t : images3d_) {
const int error_code =
clSetKernelArg(kernel, offset, sizeof(cl_mem), &t.second.memory);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (auto& t : custom_memories_) {
const int error_code =
clSetKernelArg(kernel, offset, sizeof(cl_mem), &t.second.memory);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (int i = 0; i < shared_int4s_data_.size() / 4; ++i) {
const int error_code = clSetKernelArg(kernel, offset, sizeof(int32_t) * 4,
&shared_int4s_data_[i * 4]);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (int i = 0; i < shared_float4s_data_.size() / 4; ++i) {
const int error_code = clSetKernelArg(kernel, offset, sizeof(int32_t) * 4,
&shared_float4s_data_[i * 4]);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
for (int i = 0; i < shared_half4s_data_.size() / 4; ++i) {
const int error_code = clSetKernelArg(kernel, offset, sizeof(int16_t) * 4,
&shared_half4s_data_[i * 4]);
if (error_code != CL_SUCCESS) {
return absl::UnknownError(absl::StrCat(
"Failed to set kernel arguments - ", CLErrorCodeToString(error_code),
"(at index - ", offset, ")"));
}
offset++;
}
return absl::OkStatus();
}
bool CLArguments::HasEqualScalarArguments(const CLArguments& other) const {
return (other.int_values_ == int_values_ &&
other.float_values_ == float_values_ &&
other.half_values_ == half_values_);
}
}
}
} | #include "tensorflow/lite/delegates/gpu/cl/cl_arguments.h"
#include <cstdint>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/match.h"
#include "tensorflow/lite/delegates/gpu/cl/buffer.h"
#include "tensorflow/lite/delegates/gpu/cl/cl_test.h"
#include "tensorflow/lite/delegates/gpu/cl/gpu_object.h"
#include "tensorflow/lite/delegates/gpu/common/gpu_info.h"
namespace tflite {
namespace gpu {
namespace cl {
TEST(CLArgumentsTest, TestSelectorResolve) {
BufferDescriptor desc;
desc.element_type = DataType::FLOAT32;
desc.element_size = 4;
desc.memory_type = MemoryType::GLOBAL;
Arguments args;
args.AddObjectRef("weights", AccessType::READ,
std::make_unique<BufferDescriptor>(std::move(desc)));
std::string sample_code = R"(
__kernel void main_function($0) {
if (a < 3) {
value = args.weights.Read(id);
}
})";
CLArguments cl_args;
GpuInfo gpu_info;
ASSERT_OK(cl_args.Init(gpu_info, nullptr, &args, &sample_code));
EXPECT_TRUE(absl::StrContains(sample_code, "value = weights_buffer[id];"));
EXPECT_TRUE(
absl::StrContains(sample_code, "__global float4* weights_buffer"));
}
TEST(CLArgumentsTest, TestNoSelector) {
BufferDescriptor desc;
desc.element_type = DataType::FLOAT32;
desc.element_size = 4;
desc.memory_type = MemoryType::GLOBAL;
Arguments args;
args.AddObjectRef("weights", AccessType::READ,
std::make_unique<BufferDescriptor>(std::move(desc)));
std::string sample_code = R"(
if (a < 3) {
value = args.weights.UnknownSelector(id);
}
)";
CLArguments cl_args;
GpuInfo gpu_info;
EXPECT_FALSE(cl_args.Init(gpu_info, nullptr, &args, &sample_code).ok());
}
}
}
} | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/cl/cl_arguments.cc | https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/cl/cl_arguments_test.cc | 4a29233a7b7c1a3a4294e4ccdd1772f9083944ea |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.