Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[CPU] bf16 constant saturation during model compilation stage (#28542)

Bo Liu810589a28f52
diff --git a/src/plugins/intel_cpu/src/cpu_memory.cpp b/src/plugins/intel_cpu/src/cpu_memory.cpp
index db2abe6eba7..15cc1a73933 100644
--- a/src/plugins/intel_cpu/src/cpu_memory.cpp
+++ b/src/plugins/intel_cpu/src/cpu_memory.cpp
@@ -9,6 +9,7 @@
#include "memory_desc/cpu_memory_desc_utils.h"
#include "nodes/common/cpu_memcpy.h"
#include "nodes/reorder.h"
+#include "utils/bfloat16.hpp"
#include "utils/debug_capabilities.h"
#if defined(__linux__)
# include <sys/syscall.h> /* Definition of SYS_* constants */
@@ -30,19 +31,44 @@ BlockedMemoryDescPtr IMemory::getDescWithType<BlockedMemoryDesc, 0, 0>() const {
}
namespace {
-inline void setSubnormalsToZero(float* data, size_t size) {
+inline void setSubnormalsToZeroAndbf16Saturation(float* data, size_t size, bool ftz, bool bf16saturation) {
uint32_t* u32data = reinterpret_cast<uint32_t*>(data);
- for (size_t i = 0; i < size; ++i) {
- if ((u32data[i] & (0xFF << 23)) == 0) {
- u32data[i] = 0;
+ float* floatdata = reinterpret_cast<float*>(data);
+ if (ftz && bf16saturation) {
+ for (size_t i = 0; i < size; ++i) {
+ if ((u32data[i] & (0xFF << 23)) == 0) {
+ u32data[i] = 0;
+ } else if (!std::isnan(floatdata[i]) && !std::isinf(floatdata[i])) {
+ floatdata[i] = (floatdata[i] < static_cast<float>(std::numeric_limits<ov::bfloat16>::lowest()))
+ ? static_cast<float>(std::numeric_limits<ov::bfloat16>::lowest())
+ : (floatdata[i] > static_cast<float>(std::numeric_limits<ov::bfloat16>::max()))
+ ? static_cast<float>(std::numeric_limits<ov::bfloat16>::max())
+ : floatdata[i];
+ }
+ }
+ } else if (ftz) {
+ for (size_t i = 0; i < size; ++i) {
+ if ((u32data[i] & (0xFF << 23)) == 0) {
+ u32data[i] = 0;
+ }
+ }
+ } else if (bf16saturation) {
+ for (size_t i = 0; i < size; ++i) {
+ if (!std::isnan(floatdata[i]) && !std::isinf(floatdata[i])) {
+ floatdata[i] = (floatdata[i] < static_cast<float>(std::numeric_limits<ov::bfloat16>::lowest()))
+ ? static_cast<float>(std::numeric_limits<ov::bfloat16>::lowest())
+ : (floatdata[i] > static_cast<float>(std::numeric_limits<ov::bfloat16>::max()))
+ ? static_cast<float>(std::numeric_limits<ov::bfloat16>::max())
+ : floatdata[i];
+ }
}
}
}
-void transferData(const IMemory& src, const IMemory& dst, bool ftz) {
+void transferData(const IMemory& src, const IMemory& dst, bool ftz, bool bf16saturation) {
node::Reorder::reorderData(src, dst);
- if (!ftz) {
+ if (!ftz && !bf16saturation) {
return;
}
if (src.getDesc().getPrecision() != ov::element::f32 || dst.getDesc().getPrecision() != ov::element::f32) {
@@ -62,7 +88,7 @@ void transferData(const IMemory& src, const IMemory& dst, bool ftz) {
// actual FTZ
auto* memData = static_cast<float*>(dst.getData());
memData += offset;
- setSubnormalsToZero(memData, dst.getSize() / sizeof(float));
+ setSubnormalsToZeroAndbf16Saturation(memData, dst.getSize() / sizeof(float), ftz, bf16saturation);
}
} // namespace
@@ -125,11 +151,11 @@ void Memory::create(MemoryDescPtr desc, const void* data, bool pads_zeroing) {
}
}
-void Memory::load(const IMemory& src, bool ftz) const {
+void Memory::load(const IMemory& src, bool ftz, bool bf16saturation) const {
if (src.getDesc().getPrecision() == element::string) {
OPENVINO_THROW("[CPU] Memory object cannot load string data.");
}
- transferData(src, *this, ftz);
+ transferData(src, *this, ftz, bf16saturation);
}
void Memory::nullify() {
@@ -273,12 +299,12 @@ StringMemory::StringMemory(dnnl::engine engine, MemoryDescPtr desc, const void*
}
}
-void StringMemory::load(const IMemory& src, bool ftz) const {
+void StringMemory::load(const IMemory& src, bool ftz, bool bf16saturation) const {
if (src.getDesc().getPrecision() != element::string) {
OPENVINO_THROW("[CPU] String memory cannot load a non-string object.");
}
- transferData(src, *this, false);
+ transferData(src, *this, false, false);
}
void* StringMemory::getData() const {
@@ -472,11 +498,11 @@ void StaticMemory::redefineDesc(MemoryDescPtr desc) {
OPENVINO_THROW("Unexpected: Memory descriptor may not be modified in StaticMemory object");
}
-void StaticMemory::load(const IMemory& src, bool ftz) const {
+void StaticMemory::load(const IMemory& src, bool ftz, bool bf16saturation) const {
if (src.getDesc().getPrecision() == element::string) {
OPENVINO_THROW("[CPU] StaticMemory cannot load string data.");
}
- transferData(src, *this, ftz);
+ transferData(src, *this, ftz, bf16saturation);
}
MemoryBlockPtr StaticMemory::getMemoryBlock() const {
diff --git a/src/plugins/intel_cpu/src/cpu_memory.h b/src/plugins/intel_cpu/src/cpu_memory.h
index 1004f3eaf36..c7fe407a798 100644
--- a/src/plugins/intel_cpu/src/cpu_memory.h
+++ b/src/plugins/intel_cpu/src/cpu_memory.h
@@ -188,7 +188,7 @@ public:
// Caution!!! This action invalidates the previous data layout. The old data may become unreachable.
virtual void redefineDesc(MemoryDescPtr desc) = 0;
- virtual void load(const IMemory& src, bool ftz) const = 0;
+ virtual void load(const IMemory& src, bool ftz, bool bf16saturation) const = 0;
virtual MemoryBlockPtr getMemoryBlock() const = 0;
@@ -260,7 +260,7 @@ public:
// Always throws since a static memory descriptor should not be modified
void redefineDesc(MemoryDescPtr desc) override;
- void load(const IMemory& src, bool ftz) const override;
+ void load(const IMemory& src, bool ftz, bool bf16saturation) const override;
MemoryBlockPtr getMemoryBlock() const override;
@@ -315,7 +315,7 @@ public:
void redefineDesc(MemoryDescPtr desc) override;
- void load(const IMemory& src, bool ftz) const override;
+ void load(const IMemory& src, bool ftz, bool bf16saturation) const override;
void nullify() override;
dnnl::engine getEngine() const {
@@ -421,7 +421,7 @@ public:
void redefineDesc(MemoryDescPtr desc) override;
- void load(const IMemory& src, bool ftz) const override;
+ void load(const IMemory& src, bool ftz, bool bf16saturation) const override;
MemoryBlockPtr getMemoryBlock() const override;
diff --git a/src/plugins/intel_cpu/src/dnnl_postops_composer.cpp b/src/plugins/intel_cpu/src/dnnl_postops_composer.cpp
index 09a01a410f2..5bfa6c6789b 100644
--- a/src/plugins/intel_cpu/src/dnnl_postops_composer.cpp
+++ b/src/plugins/intel_cpu/src/dnnl_postops_composer.cpp
@@ -659,7 +659,7 @@ static MemoryPtr prepackDecompressionParams(const MemoryCPtr& paramsPtr,
srcFormat);
auto srcMem = std::make_shared<Memory>(engine, srcMemoryDesc, paramsPtr->getData());
- dstMem->load(*srcMem, true);
+ dstMem->load(*srcMem, true, false);
return dstMem;
}
diff --git a/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_bf16_emitters.hpp b/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_bf16_emitters.hpp
index b68128ab2fb..f1ee8ef0571 100644
--- a/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_bf16_emitters.hpp
+++ b/src/plugins/intel_cpu/src/emitters/plugin/x64/jit_bf16_emitters.hpp
@@ -17,7 +17,12 @@ public:
conversion_mode mode = conversion_mode::default_mode)
: jit_emitter(host, host_isa, exec_prc),
mode_(mode) {
- prepare_table();
+ // only saturation_mode or non avx512_core_bf16/avx2_vnni_2 platforms requires table
+ if ((!dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_bf16) &&
+ !dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2_vnni_2)) ||
+ mode_ == conversion_mode::saturation_mode) {
+ prepare_table();
+ }
}
size_t get_inputs_num() const override {
diff --git a/src/plugins/intel_cpu/src/graph.cpp b/src/plugins/intel_cpu/src/graph.cpp
index 4e9cb4d8968..1610a5a3a05 100644
--- a/src/plugins/intel_cpu/src/graph.cpp
+++ b/src/plugins/intel_cpu/src/graph.cpp
@@ -1201,10 +1201,10 @@ void Graph::PushInputData(const std::size_t& index, const ov::SoPtr<ITensor>& in
if (actualDesc->getPrecision() == element::string) {
StringMemory ext_mem(getEngine(), ext_tensor_desc, ext_data_ptr);
- edgeMemory->load(ext_mem, false);
+ edgeMemory->load(ext_mem, false, false);
} else if (!actualDesc->isCompatible(*ext_tensor_desc)) {
Memory ext_mem(getEngine(), ext_tensor_desc, ext_data_ptr, false);
- edgeMemory->load(ext_mem, false);
+ edgeMemory->load(ext_mem, false, false);
} else {
size_t size_to_copy = ext_tensor_desc->getCurrentMemSize();
cpu_parallel_memcpy(inter_data_ptr, ext_data_ptr, size_to_copy);
@@ -1311,10 +1311,10 @@ void Graph::PullOutputData(std::unordered_map<std::size_t, ov::SoPtr<ITensor>>&
if (actualDesc->getPrecision() == element::string) {
StringMemory outBloMem(getEngine(), expected_desc_ptr, ext_blob_ptr);
- outBloMem.load(intr_blob, false);
+ outBloMem.load(intr_blob, false, false);
} else if (!actualDesc->isCompatible(*expected_desc_ptr) && !isScalarOutput) {
Memory outBloMem(getEngine(), expected_desc_ptr, ext_blob_ptr, false);
- outBloMem.load(intr_blob, false);
+ outBloMem.load(intr_blob, false, false);
} else {
OPENVINO_ASSERT(srcPrec == dstPrec,
"The precision of the CPU output tensor index",
diff --git a/src/plugins/intel_cpu/src/memory_state.cpp b/src/plugins/intel_cpu/src/memory_state.cpp
index ba6173fe280..077f590b91a 100644
--- a/src/plugins/intel_cpu/src/memory_state.cpp
+++ b/src/plugins/intel_cpu/src/memory_state.cpp
@@ -57,7 +57,7 @@ void VariableStateBase::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {
auto src = state->data();
Memory mem(get_engine(), state_desc, src);
- input_mem()->load(mem, true);
+ input_mem()->load(mem, true, false);
reset_state_flag = false;
}
@@ -96,7 +96,7 @@ ov::SoPtr<ov::ITensor> VariableStateBase::get_state() const {
// reorder
auto mem = std::make_shared<Memory>(get_engine(), current_ext_desc);
- mem->load(*(internal_state_mem()), true);
+ mem->load(*(internal_state_mem()), true, false);
return std::make_shared<Tensor>(mem);
}
@@ -312,7 +312,7 @@ void VariableStateKVcache::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {
m_scale_zp.at<float>({m, b, h, size_t{1}}));
});
} else {
- m_internal_mem->load(external_mem, true);
+ m_internal_mem->load(external_mem, true, false);
}
// 2. Reset the beam search table
diff --git a/src/plugins/intel_cpu/src/nodes/conv.cpp b/src/plugins/intel_cpu/src/nodes/conv.cpp
index cecc647bd3a..c1c4791fe4c 100644
--- a/src/plugins/intel_cpu/src/nodes/conv.cpp
+++ b/src/plugins/intel_cpu/src/nodes/conv.cpp
@@ -1687,7 +1687,7 @@ void Convolution::executeDynamicImpl(const dnnl::stream& strm) {
const auto& outMem = out->getParentEdgeAt(0)->getMemory();
auto convOutMem = getDstMemoryAtPort(0);
Node::redefineOutputMemory({outMem.getStaticDims()});
- convOutMem->load(outMem, true);
+ convOutMem->load(outMem, true, false);
}
}
diff --git a/src/plugins/intel_cpu/src/nodes/eltwise.cpp b/src/plugins/intel_cpu/src/nodes/eltwise.cpp
index 6e26bfb3a48..8634a3eeedc 100644
--- a/src/plugins/intel_cpu/src/nodes/eltwise.cpp
+++ b/src/plugins/intel_cpu/src/nodes/eltwise.cpp
@@ -360,7 +360,6 @@ struct EltwiseKey {
ov::element::Type outPrc;
dnnl::post_ops postOps;
EltwiseImplType implType;
- bool doOutputSaturation;
size_t hash() const {
using namespace dnnl::impl;
@@ -396,10 +395,6 @@ struct EltwiseKey {
seed = hash_combine(seed, outPrc.hash());
seed = get_post_op_hash(seed, *postOps.get());
seed = hash_combine(seed, implType);
-
- if (outPrc == ov::element::bf16) {
- seed = hash_combine(seed, doOutputSaturation);
- }
return seed;
}
@@ -427,9 +422,6 @@ struct EltwiseKey {
result = result && (inpDims[i] == rhs.inpDims[i]);
}
}
- if (doOutputSaturation != rhs.doOutputSaturation) {
- return false;
- }
}
return result;
@@ -462,8 +454,7 @@ public:
const std::vector<ov::element::Type>& inpPrc,
const ov::element::Type& outPrc,
const dnnl::post_ops& post_ops,
- bool useRuntimePtrs,
- bool doOutputSaturation) {
+ bool useRuntimePtrs) {
auto collapseLastDims = [](std::vector<size_t>& dims, int dimsToCollapse) {
for (size_t i = dims.size() - 2; i > dims.size() - dimsToCollapse - 2; i--) {
dims[dims.size() - 1] *= dims[i];
@@ -657,7 +648,6 @@ public:
jep.dst_prc = outPrc;
jep.work_amount = jep.dst_size = jep.dims.back();
jep.oc_size = oc_size;
- jep.do_output_saturation = doOutputSaturation;
std::transform(jep.oc_offsets.begin(), jep.oc_offsets.end(), jep.oc_offsets.begin(), [](size_t& offset) {
return offset * sizeof(float);
@@ -1189,8 +1179,7 @@ static Eltwise::executorPtr buildExecutor(const EltwiseKey& key) {
key.inpPrc,
key.outPrc,
key.postOps,
- key.implType == EltwiseImplType::optimizedShapeAgnostic,
- key.doOutputSaturation);
+ key.implType == EltwiseImplType::optimizedShapeAgnostic);
}
bool Eltwise::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
@@ -1906,18 +1895,6 @@ void Eltwise::prepareParams() {
}
}
- // FP32 constant inputs may contain values out of BF16 representable range. In case output precision is BF16 we
- // choose "saturation" mode for fp32->bf16 conversion procedure to prevent getting -Inf/+Inf values in the
- // outputs. Since "saturation" conversion is more time consuming, better solution would be to clamp constants on
- // compilation stage (ticket: 159589).
- key.doOutputSaturation = false;
- for (size_t i = 0; i < getParentEdges().size(); i++) {
- if (getParentEdgeAt(i)->getParent()->isConstant()) {
- key.doOutputSaturation = true;
- break;
- }
- }
-
auto cache = context->getParamsCache();
auto result = cache->getOrCreate(key, buildExecutor);
execPtr = result.first;
diff --git a/src/plugins/intel_cpu/src/nodes/input.cpp b/src/plugins/intel_cpu/src/nodes/input.cpp
index df41c7e307e..92b8719006f 100644
--- a/src/plugins/intel_cpu/src/nodes/input.cpp
+++ b/src/plugins/intel_cpu/src/nodes/input.cpp
@@ -21,18 +21,18 @@ namespace ov::intel_cpu::node {
#if defined(OPENVINO_ARCH_X86_64)
namespace {
-struct jit_has_subnormals_base : public jit_generator {
- DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_has_subnormals_base)
+struct jit_has_special_value_base : public jit_generator {
+ DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_has_special_value_base)
typedef struct {
const float* src;
const size_t count;
- bool hasSubnormals;
+ bool hasTargetValues;
} args_t;
typedef void (*fn_t)(const args_t*);
- jit_has_subnormals_base() : jit_generator(jit_name()) {
+ jit_has_special_value_base() : jit_generator(jit_name()) {
jit_ker_ = nullptr;
}
@@ -108,8 +108,35 @@ protected:
uni_vtestps(b, c); // if ((!b & c) == 0) CF = 1 else CF = 0
}
+ void check_bf16_saturations(const Xbyak::Reg64& src,
+ const Xbyak::Ymm& bf16_max_mask,
+ const Xbyak::Ymm& bf16_min_mask) {
+ auto a = ymm1;
+ auto b = ymm2;
+ auto c = ymm3;
+ vmovdqu(a, yword[src]); // load 8 floats
+ vcmpps(b, a, bf16_max_mask, 0x1e); // b = (a > bf16_max) ? 1 : 0
+ vcmpps(c, a, bf16_min_mask, 0x11); // c = (a < bf16_min) ? 1 : 0
+ vorps(b, b, c); // b = b | c
+ vptest(b, b); // if (b != 0) CF = 1 else CF = 0
+ }
+
+ void check_bf16_saturations(const Xbyak::Reg64& src,
+ const Xbyak::Xmm& bf16_max_mask,
+ const Xbyak::Xmm& bf16_min_mask) {
+ auto a = xmm1;
+ auto b = xmm2;
+ auto c = xmm3;
+
+ uni_vmovdqu(a, xword[src]); // load 4 floats
+ uni_vcmpps(b, a, bf16_max_mask, 0x1e); // b = (a > bf16_max) ? 1 : 0
+ uni_vcmpps(c, a, bf16_max_mask, 0x11); // c = (a < bf16_min) ? 1 : 0
+ uni_vorps(b, b, c); // b = b | c
+ uni_vtestps(b, b); // if (b != 0) CF = 1 else CF = 0
+ }
+
protected:
- Label exit, has_subnormals, no_subnormals;
+ Label exit, has_target_values, no_target_values;
const Reg64& reg_src = rax;
const Reg64& reg_dst = rbx;
@@ -119,16 +146,35 @@ protected:
static const uint32_t exponent_mask_data[8];
static const uint32_t mantissa_mask_data[8];
+ static const float bf16_max_mask_data[8];
+ static const float bf16_min_mask_data[8];
};
-const uint32_t jit_has_subnormals_base::exponent_mask_data[8] =
+const uint32_t jit_has_special_value_base::exponent_mask_data[8] =
{0x7f800000, 0x7f800000, 0x7f800000, 0x7f800000, 0x7f800000, 0x7f800000, 0x7f800000, 0x7f800000};
-const uint32_t jit_has_subnormals_base::mantissa_mask_data[8] =
+const uint32_t jit_has_special_value_base::mantissa_mask_data[8] =
{0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff};
+const float jit_has_special_value_base::bf16_max_mask_data[8] = {std::numeric_limits<ov::bfloat16>::max(),
+ std::numeric_limits<ov::bfloat16>::max(),
+ std::numeric_limits<ov::bfloat16>::max(),
+ std::numeric_limits<ov::bfloat16>::max(),
+ std::numeric_limits<ov::bfloat16>::max(),
+ std::numeric_limits<ov::bfloat16>::max(),
+ std::numeric_limits<ov::bfloat16>::max(),
+ std::numeric_limits<ov::bfloat16>::max()};
+
+const float jit_has_special_value_base::bf16_min_mask_data[8] = {std::numeric_limits<ov::bfloat16>::lowest(),
+ std::numeric_limits<ov::bfloat16>::lowest(),
+ std::numeric_limits<ov::bfloat16>::lowest(),
+ std::numeric_limits<ov::bfloat16>::lowest(),
+ std::numeric_limits<ov::bfloat16>::lowest(),
+ std::numeric_limits<ov::bfloat16>::lowest(),
+ std::numeric_limits<ov::bfloat16>::lowest(),
+ std::numeric_limits<ov::bfloat16>::lowest()};
template <cpu_isa_t isa>
-struct jit_has_subnormals : public jit_has_subnormals_base {
+struct jit_has_subnormals : public jit_has_special_value_base {
using Vmm = typename dnnl::impl::utils::conditional<isa == sse41, Xbyak::Xmm, Xbyak::Ymm>::type;
const Vmm rmm4 = Vmm(4);
@@ -148,7 +194,7 @@ struct jit_has_subnormals : public jit_has_subnormals_base {
// Get arguments addresses
mov(reg_src, ptr[param1 + offsetof(args_t, src)]);
- lea(reg_dst, ptr[param1 + offsetof(args_t, hasSubnormals)]);
+ lea(reg_dst, ptr[param1 + offsetof(args_t, hasTargetValues)]);
mov(reg_sz, ptr[param1 + offsetof(args_t, count)]);
// Initialize necessary consts
@@ -165,7 +211,7 @@ struct jit_has_subnormals : public jit_has_subnormals_base {
foreach (reg_idx, 1, r8, [&, this](const Xbyak::Reg64& idx) {
check_subnormals(reg_src, exponent_mask, mantissa_mask, zero);
- jnc(has_subnormals);
+ jnc(has_target_values);
add(reg_src, sizeof(float) * vlen);
})
;
@@ -184,16 +230,16 @@ struct jit_has_subnormals : public jit_has_subnormals_base {
copy_floats(r8, reg_src, reg_sz);
check_subnormals(r8, exponent_mask, mantissa_mask, zero);
- jc(no_subnormals);
+ jc(no_target_values);
add(rsp, vlen * sizeof(float));
- L(has_subnormals);
+ L(has_target_values);
mov(rax, 1);
mov(byte[reg_dst], al);
jmp(exit);
- L(no_subnormals);
+ L(no_target_values);
add(rsp, vlen * sizeof(float));
L(exit);
@@ -201,8 +247,81 @@ struct jit_has_subnormals : public jit_has_subnormals_base {
postamble();
}
};
+template <cpu_isa_t isa>
+struct jit_has_bf16_overflows : public jit_has_special_value_base {
+ using Vmm = typename dnnl::impl::utils::conditional<isa == sse41, Xbyak::Xmm, Xbyak::Ymm>::type;
+
+ const Vmm rmm4 = Vmm(4);
+ const Vmm rmm5 = Vmm(5);
+ const Vmm rmm6 = Vmm(6);
+ const int length = isa == sse41 ? 4 : 8;
+
+ void generate() override final { // NOLINT
+ size_t const vlen = length;
+ const int sh_bits = std::ilogb(vlen);
+
+ auto zero = rmm4;
+ auto bf16_max_mask = rmm5;
+ auto bf16_min_mask = rmm6;
+
+ preamble();
+
+ // Get arguments addresses
+ mov(reg_src, ptr[param1 + offsetof(args_t, src)]);
+ lea(reg_dst, ptr[param1 + offsetof(args_t, hasTargetValues)]);
+ mov(reg_sz, ptr[param1 + offsetof(args_t, count)]);
+
+ // Initialize necessary consts
+ uni_vpxor(zero, zero, zero);
+ mov(reg_mask_addr, (size_t)bf16_max_mask_data);
+ uni_vmovdqu(bf16_max_mask, ptr[reg_mask_addr]);
+ mov(reg_mask_addr, (size_t)bf16_min_mask_data);
+ uni_vmovdqu(bf16_min_mask, ptr[reg_mask_addr]);
+
+ // Main loop
+ xor_(reg_idx, reg_idx);
+ mov(r8, reg_sz);
+ shr(r8, sh_bits);
+
+ foreach (reg_idx, 1, r8, [&, this](const Xbyak::Reg64& idx) {
+ check_bf16_saturations(reg_src, bf16_max_mask, bf16_min_mask);
+ jnz(has_target_values, T_NEAR);
+ add(reg_src, sizeof(float) * vlen);
+ })
+ ;
+
+ // Tail
+ shl(reg_idx, sh_bits);
+ sub(reg_sz, reg_idx);
+ test(reg_sz, reg_sz);
+ jz(exit);
+
+ // use space on stack for 4 or 8 floats
+ sub(rsp, vlen * sizeof(float));
+ mov(r8, rsp);
-jit_has_subnormals_base::fn_t jit_has_subnormals_function() {
+ uni_vmovdqu(ptr[r8], zero);
+
+ copy_floats(r8, reg_src, reg_sz);
+ check_bf16_saturations(r8, bf16_max_mask, bf16_min_mask);
+ jz(no_target_values, T_NEAR);
+ add(rsp, vlen * sizeof(float));
+
+ L(has_target_values);
+
+ mov(rax, 1);
+ mov(byte[reg_dst], al);
+ jmp(exit);
+
+ L(no_target_values);
+ add(rsp, vlen * sizeof(float));
+
+ L(exit);
+
+ postamble();
+ }
+};
+jit_has_special_value_base::fn_t jit_has_subnormals_function() {
if (mayiuse(cpu_isa_t::avx2)) {
static jit_has_subnormals<cpu_isa_t::avx2> generator;
static auto fn = generator.get();
@@ -214,6 +333,18 @@ jit_has_subnormals_base::fn_t jit_has_subnormals_function() {
}
return nullptr;
}
+jit_has_special_value_base::fn_t jit_has_bf16_overflows_function() {
+ if (mayiuse(cpu_isa_t::avx2)) {
+ static jit_has_bf16_overflows<cpu_isa_t::avx2> generator;
+ static auto fn = generator.get();
+ return fn;
+ } else if (mayiuse(cpu_isa_t::sse41)) {
+ static jit_has_bf16_overflows<cpu_isa_t::sse41> generator;
+ static auto fn = generator.get();
+ return fn;
+ }
+ return nullptr;
+}
} // namespace
#endif
@@ -260,6 +391,85 @@ void Input::cloneBlobIfRequired() {
needFlushDenormalsToZero = false;
}
+ // The presence of subnormals is better to determined at IR read time.
+ auto checkSubnormalsAndBF16Overflows = [&](bool& has_subnormals, bool& has_bf16_overflows) {
+ if (prec == ov::element::f32) {
+ uint32_t const* u32data = m_constOp->get_data_ptr<uint32_t>();
+ float const* f32data = m_constOp->get_data_ptr<float>();
+
+ if (!size) {
+ return;
+ }
+ // Only bf16 inferencePrecision cases need to be checked for saturation
+ const bool do_bf16_saturation_check =
+ (context->getConfig().inferencePrecision == ov::element::bf16) ? true : false;
+
+#if defined(OPENVINO_ARCH_X86_64)
+ auto fn = jit_has_subnormals_function();
+ auto fn_bf16_check = jit_has_bf16_overflows_function();
+ if (fn && fn_bf16_check) {
+ static const size_t batch_size = 2048;
+ const size_t iterations_num = size / batch_size + 1;
+
+ std::atomic<bool> has_subnormals_local(false);
+ std::atomic<bool> has_bf16_overflows_local(false);
+ if (needFlushDenormalsToZero || do_bf16_saturation_check) {
+ parallel_for(iterations_num, [&](int n) {
+ auto ptr = u32data + n * batch_size;
+ jit_has_special_value_base::args_t args = {reinterpret_cast<float const*>(ptr),
+ std::min(batch_size, (size_t)(u32data + size - ptr)),
+ false};
+
+ if (needFlushDenormalsToZero && !has_subnormals_local) {
+ fn(&args);
+ if (args.hasTargetValues) {
+ has_subnormals_local = true;
+ }
+ }
+
+ if (do_bf16_saturation_check && !has_bf16_overflows_local) {
+ // batch_size is small enough, so source data are still cache-hot
+ args.hasTargetValues = false;
+ fn_bf16_check(&args);
+ if (args.hasTargetValues) {
+ has_bf16_overflows_local = true;
+ }
+ }
+ });
+ }
+
+ has_subnormals = has_subnormals_local;
+ has_bf16_overflows = has_bf16_overflows_local;
+
+ return;
+ }
+#endif
+
+ uint32_t mantissaMask = 0x007fffff;
+ uint32_t exponentMask = 0x7f800000;
+ const float bf16_max = std::numeric_limits<ov::bfloat16>::max();
+ for (size_t i = 0; i < size; ++i) {
+ if (needFlushDenormalsToZero && (u32data[i] & exponentMask) == 0 && (u32data[i] & mantissaMask) != 0) {
+ has_subnormals = true;
+ }
+
+ if (do_bf16_saturation_check && (f32data[i] < -bf16_max || f32data[i] > bf16_max)) {
+ has_bf16_overflows = true;
+ }
+
+ if ((!needFlushDenormalsToZero || has_subnormals) &&
+ (!do_bf16_saturation_check || has_bf16_overflows)) {
+ return;
+ }
+ }
+ }
+ };
+
+ bool has_subnormals = false;
+ bool has_bf16_overflows = false;
+
+ checkSubnormalsAndBF16Overflows(has_subnormals, has_bf16_overflows);
+
auto cloneBlob = [&, this]() {
MemoryPtr memory;
@@ -292,7 +502,7 @@ void Input::cloneBlobIfRequired() {
} else {
ptr = std::make_shared<StaticMemory>(getEngine(), memDesc);
}
- ptr->load(*memory.get(), needFlushDenormalsToZero);
+ ptr->load(*memory.get(), has_subnormals, has_bf16_overflows);
return ptr;
};
@@ -309,51 +519,6 @@ void Input::cloneBlobIfRequired() {
#endif
};
- // The presence of subnormals is better to determined at IR read time.
- auto hasSubnormals = [&]() {
- if (prec == ov::element::f32) {
- uint32_t const* u32data = m_constOp->get_data_ptr<uint32_t>();
-
- if (!size) {
- return false;
- }
-
-#if defined(OPENVINO_ARCH_X86_64)
- if (auto fn = jit_has_subnormals_function()) {
- static const size_t batch_size = 2048;
- const size_t iterations_num = size / batch_size + 1;
-
- volatile bool has_subnormals = false;
-
- parallel_for(iterations_num, [&](int n) {
- auto ptr = u32data + n * batch_size;
- const jit_has_subnormals_base::args_t args = {
- reinterpret_cast<float const*>(ptr),
- std::min(batch_size, static_cast<size_t>(u32data + size - ptr)),
- false};
-
- fn(&args);
-
- if (args.hasSubnormals) {
- has_subnormals = true;
- }
- });
-
- return has_subnormals;
- }
-#endif
-
- uint32_t mantissaMask = 0x007fffff;
- uint32_t exponentMask = 0x7f800000;
- for (size_t i = 0; i < size; ++i) {
- if ((u32data[i] & exponentMask) == 0 && (u32data[i] & mantissaMask) != 0) {
- return true;
- }
- }
- }
- return false;
- };
-
auto blobKey = [&]() {
char ptr[32];
snprintf(ptr, sizeof ptr, "%p", m_constOp->get_data_ptr());
@@ -365,7 +530,7 @@ void Input::cloneBlobIfRequired() {
prec != element::string &&
// IRs already have all subnormals flushed to zero, but in
// read_model scenario with directly loaded original model still can have subnormals
- isBlobAligned(m_constOp) && (!needFlushDenormalsToZero || !hasSubnormals()) &&
+ isBlobAligned(m_constOp) && !has_subnormals && !has_bf16_overflows &&
// Blob should be cloned in cache only if original weights are stored on other numa node.
// This is possible only in multistream case on multisocket machine.
// TODO: don't clone blob for multisocket + multistream case if current stream is run on the numa node where
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/jit_eltwise_common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/jit_eltwise_common.hpp
index 1aa1e1aecd5..c83a12e4df7 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/jit_eltwise_common.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/jit_eltwise_common.hpp
@@ -46,7 +46,6 @@ struct jit_eltwise_params {
size_t work_amount;
bool use_runtime_ptrs;
- bool do_output_saturation;
};
struct jit_eltwise_call_args_indexes {
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.cpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.cpp
index 76add5c3274..e580c1f8ec9 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.cpp
@@ -59,9 +59,7 @@ void jit_uni_eltwise_generic<isa>::generate() {
}
if (mayiuse(avx512_core) || mayiuse(avx2_vnni_2)) {
- auto const mode = jep_.do_output_saturation ? jit_uni_vcvtneps2bf16::conversion_mode::saturation_mode
- : jit_uni_vcvtneps2bf16::conversion_mode::default_mode;
- uni_vcvtneps2bf16.reset(new jit_uni_vcvtneps2bf16(this, isa, element::bf16, mode));
+ uni_vcvtneps2bf16.reset(new jit_uni_vcvtneps2bf16(this, isa));
}
const auto& jep = jep_;
@@ -208,11 +206,7 @@ void jit_uni_eltwise_generic<isa>::generate() {
apply_post_ops(true, jep_.oc_size > 1 ? j * sizeof(float) : 0);
- store_scalar(ptr[reg_dst + j * jep.dst_prc.size()],
- xmm_dst,
- exec_prc,
- jep.dst_prc,
- jep.do_output_saturation);
+ store_scalar(ptr[reg_dst + j * jep.dst_prc.size()], xmm_dst, exec_prc, jep.dst_prc);
}
for (size_t i = 0; i < jep.inputs_number; i++) {
@@ -288,7 +282,7 @@ void jit_uni_eltwise_generic<isa>::generate() {
apply_post_ops(true);
- store_scalar(ptr[reg_dst], xmm_dst, exec_prc, jep.dst_prc, jep.do_output_saturation);
+ store_scalar(ptr[reg_dst], xmm_dst, exec_prc, jep.dst_prc);
for (size_t i = 0; i < jep.inputs_number; i++) {
if (jep.src_size[i] != 1) {
@@ -781,8 +775,7 @@ template <dnnl::impl::cpu::x64::cpu_isa_t isa>
void jit_uni_eltwise_generic<isa>::store_scalar(const Xbyak::Address& op,
Xmm xmm_dst,
ov::element::Type src_prc,
- ov::element::Type dst_prc,
- const bool do_output_saturation) {
+ ov::element::Type dst_prc) {
if (src_prc == dst_prc) {
switch (src_prc.size()) {
case 4:
@@ -819,12 +812,7 @@ void jit_uni_eltwise_generic<isa>::store_scalar(const Xbyak::Address& op,
uni_vmovss(op, xmm_dst);
break;
case ov::element::bf16:
- if (do_output_saturation) {
- uni_vpsrld(xmm_dst, xmm_dst, 16);
- } else {
- uni_vcvtneps2bf16->emit_code({static_cast<size_t>(xmm_dst.getIdx())},
- {static_cast<size_t>(xmm_dst.getIdx())});
- }
+ uni_vcvtneps2bf16->emit_code({static_cast<size_t>(xmm_dst.getIdx())}, {static_cast<size_t>(xmm_dst.getIdx())});
uni_vpextrw(op, xmm_dst, 0x0);
break;
case ov::element::f16:
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.hpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.hpp
index 07a32a8af73..8677dd0524d 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/jit_uni_eltwise_generic.hpp
@@ -116,8 +116,7 @@ private:
void store_scalar(const Xbyak::Address& op,
Xbyak::Xmm xmm_dst,
ov::element::Type src_prc,
- ov::element::Type dst_prc,
- const bool do_output_saturation);
+ ov::element::Type dst_prc);
};
} // namespace ov::intel_cpu::x64
diff --git a/src/plugins/intel_cpu/src/nodes/memory.cpp b/src/plugins/intel_cpu/src/nodes/memory.cpp
index d3a3ce679b5..37ae2e88a1a 100644
--- a/src/plugins/intel_cpu/src/nodes/memory.cpp
+++ b/src/plugins/intel_cpu/src/nodes/memory.cpp
@@ -83,7 +83,7 @@ public:
m_pMemDesc = desc;
}
- void load(const IMemory& src, bool ftz) const override {
+ void load(const IMemory& src, bool ftz, bool bf16saturation) const override {
OPENVINO_THROW("Unexpected call MemoryStub::load()");
}
@@ -307,7 +307,7 @@ void MemoryOutput::runStatic(dnnl::stream strm) {
CPU_NODE_ASSERT(assignedMem, " uninitialized assigned memory");
if (inputMem->getData() != assignedMem->getData()) {
- assignedMem->load(*inputMem, true);
+ assignedMem->load(*inputMem, true, false);
}
}
@@ -811,7 +811,7 @@ void MemoryInput::runDynamic(dnnl::stream strm) {
// copy data when necessary
if (src->getData() != dst->getData()) {
- dst->load(*src, true);
+ dst->load(*src, true, false);
}
}
@@ -855,7 +855,7 @@ void MemoryInput::runStatic(dnnl::stream strm) {
// copy data when necessary
auto dst = getDstMemoryAtPort(0);
if (src->getData() != dst->getData()) {
- dst->load(*src, true);
+ dst->load(*src, true, false);
}
}
@@ -1068,7 +1068,7 @@ void MemoryInputSingle::runStatic(dnnl::stream strm) {
auto stateMem = getAssignedState()->output_mem();
CPU_NODE_ASSERT(stateMem, " state memory has nullptr");
if (result->getData() != stateMem->getData()) {
- stateMem->load(*result, true);
+ stateMem->load(*result, true, false);
}
}
getAssignedState()->commit(); // since we don't use MemoryOutput, commit must be called to change the reset state
@@ -1093,7 +1093,7 @@ void MemoryInputSingle::runDynamic(dnnl::stream strm) {
}
if (result->getData() != stateMem->getData()) {
- stateMem->load(*result, true);
+ stateMem->load(*result, true, false);
}
}
getAssignedState()->commit(); // since we don't use MemoryOutput, commit must be called to change the reset state
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/bf16_convert_saturation.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/bf16_convert_saturation.cpp
index 5f43f863c78..17b1f4d1350 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/bf16_convert_saturation.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/bf16_convert_saturation.cpp
@@ -58,7 +58,7 @@ protected:
in_data.resolution = 1;
auto thenTensor = ov::test::utils::create_and_fill_tensor(precision, ov::Shape{1}, in_data);
- in_data.start_from = 3.40282e+38;
+ in_data.start_from = 1;
in_data.range = 10;
in_data.resolution = 2;
auto elseTensor = ov::test::utils::create_and_fill_tensor(precision, ov::Shape{2, 1, 32, 32}, in_data);
diff --git a/src/plugins/intel_cpu/tests/unit/cpu_tensor_test.cpp b/src/plugins/intel_cpu/tests/unit/cpu_tensor_test.cpp
index b8f9634ddb6..d0ce6e0d47c 100644
--- a/src/plugins/intel_cpu/tests/unit/cpu_tensor_test.cpp
+++ b/src/plugins/intel_cpu/tests/unit/cpu_tensor_test.cpp
@@ -71,7 +71,7 @@ public:
MOCK_METHOD(const VectorDims&, getStaticDims, (), (const, override));
MOCK_METHOD(void, redefineDesc, (MemoryDescPtr), (override));
- MOCK_METHOD(void, load, (const IMemory&, bool), (const, override));
+ MOCK_METHOD(void, load, (const IMemory&, bool, bool), (const, override));
MOCK_METHOD(MemoryBlockPtr, getMemoryBlock, (), (const, override));
MOCK_METHOD(dnnl::memory, getPrimitive, (), (const, override));