Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions docs/experiments/native-sin-cos-f16.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Binary16 VOP1/VOP3/SDWA `v_sin_f16` and `v_cos_f16` in direct Compute DXIL

Issue #3298 (Refs #2935) lowers `v_sin_f16` (`0x60` / `0x1e0`) and `v_cos_f16`
(`0x61` / `0x1e1`) in the direct Compute DXIL translator via
`binary16_unary()` (`src/gfx1013_compute_native.cpp`) and `DirectCompute::trig_turns()`
/ `float_alu()` (`src/gfx1013_direct_compute.inl`).

## Lowering & Semantics

- Both instructions share `trig_turns()` with `v_sin_f32` and `v_cos_f32`. It reduces the widened binary32 angle
in revolutions with round-to-nearest-even (`part = a - Round_ne(a)`, DXIL op 26, so `|part| <= 0.5`), keeps a
signed zero angle, multiplies by `2 * pi` and selects an exact `+0.0` at `|part| == 0.5` for sin and
`|part| == 0.25` for cos, before `packed_half_rne()`. An angle of +0.75 turns reduces to -0.25.
- Special values on the modified binary16 source:
- `±Inf` and `NaN` (`|source| >= 0x7c00`) give the quiet NaN `0x7e00`, whatever NaN the host Sin/Cos returns.
- `v_sin_f16(-0.0)` (`0x8000`) gives `-0.0` (`0x8000`) even on a host whose Sin loses the sign of zero; `v_cos_f16(±0.0)`
returns `+1.0` (`0x3c00`).
- Preserves destination high bits `D[31:16]` on VOP1/VOP3 and supports SDWA
subword selection/padding/preservation, `abs`/`neg`, SGPR/VGPR/literal, and
inline float/integer constants under the default binary16 RNE + keep-denormals
`MODE` contract.
- Refuses `clamp`, `omod`, high-half VOP3 `op_sel`, DPP16/DPP8 encodings,
non-default binary16 `MODE`, and SDWA high-half selection on inline constants.

## Verification

- [native_sin_cos_f16_check.py](../../tests/native_sin_cos_f16_check.py) checks 37 cases (`VOP1`, `VOP3`, `SDWA`,
`abs`/`neg` including sin on negative halves, inline/literal/SGPR/overlap, `±0`, `±0.25`, `±0.5`, `±0.75`,
`-1.75`, `2048.0`, `65504.0`, `±Inf`, `qNaN`, `sNaN`, subnormals, general angles) and 8 refusals in `ir`,
`controls` and `hardware` (`tests/cmake/native_sin_cos_f16.cmake`).
- `ir` evaluates the IR on a model host and compares every bit, NaN payloads too. The model keeps NaN payloads
(also through `legacyF16ToF32`), answers an invalid operation with the negative quiet NaN `0xffc00000` (as x86
SSE does) and has Sin return `+0` for a zero angle. D3D fixes none of these, so the NaN select and the `-0.0`
select of `v_sin_f16` are each needed on that host: removing either, or changing the NaN test from `uge` to
`ugt`, fails `ir`. The `a == 0` select inside `trig_turns()` belongs to the shared `v_sin_f32` path; for binary16
the `-0.0` select covers the same case.
- `hardware` compares NaN, `±0` and `±1` results exactly. Other results accept `2^-20` absolute plus two binary16
ulp of the expected value.

## Accuracy

No documented error bound for DXIL `Sin` and `Cos` was found. The parts of the Direct3D 11.3 functional
specification read for this note (section 3.1, floating-point rules) list none, and the instruction reference rows
were not reachable. The `hardware` tolerance is therefore an assumption, not a host contract: a binary32 error of
at most `2^-20` absolute for an argument in [-pi, pi]. Near a zero crossing only that absolute part applies, so the
check cannot tell a tiny result such as `sin_subnormal` (about 3.7e-7) from zero. The RDNA2 accuracy of
`V_SIN_F16`/`V_COS_F16` was not compared. The readback is not measured on this machine (capability skip 77).
2 changes: 1 addition & 1 deletion src/gfx1013_compute_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ static bool binary16_alu(std::string_view name) {

static bool binary16_unary(std::string_view name) {
return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16" ||
name == "v_rsq_f16" || name == "v_log_f16";
name == "v_rsq_f16" || name == "v_log_f16" || name == "v_sin_f16" || name == "v_cos_f16";
}

[[noreturn]] void refuse(unsigned pc, const string &reason) {
Expand Down
32 changes: 24 additions & 8 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -947,6 +947,20 @@ struct DirectCompute {
string select_float(const string &condition, const string &yes, const string &no) {
return ir.value("select i1 " + condition + ", float " + yes + ", float " + no);
}
// Reduce an angle in turns to [-0.5, 0.5] with round-to-nearest-even (DXIL
// Round_ne, op 26) before converting to radians, preserving signed zero and
// the exact zeros at half a turn for sin and a quarter turn for cos.
string trig_turns(bool cosine, const string &a) {
auto unary_f32 = [&](unsigned op, const string &v) {
return ir.invoke("float", "unary.f32", op, {{"float", v}}, "nounwind readnone");
};
auto part = ir.value("fsub float " + a + ", " + unary_f32(26, a));
part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part);
auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000");
auto mag_part = unary_f32(6, part);
auto exact = ir.value("fcmp oeq float " + mag_part + (cosine ? ", 0.25" : ", 0.5"));
return select_float(exact, "0.0", unary_f32(cosine ? 12 : 13, radians));
}
// Invert the cube projection. Each pair of faces has a common major
// axis, with the negative face second. The two minor axes span [-1,1].
std::array<string, 3> cube_axes(const string &face, const string &u, const string &v, bool tangent) {
Expand Down Expand Up @@ -2566,9 +2580,12 @@ struct DirectCompute {
const auto source = half_bits(0);
auto a = widen(source);
const bool rsq = n == "v_rsq_f16", exp = n == "v_exp_f16", log = n == "v_log_f16";
const bool trig = n == "v_sin_f16" || n == "v_cos_f16";
string widened;
if (n == "v_rcp_f16") {
widened = ir.value("fdiv float 1.000000e+00, " + a);
} else if (trig) {
widened = trig_turns(n == "v_cos_f16", a);
} else if (binary16_unary(n)) {
const unsigned opcode = rsq ? 25 : exp ? 21 : log ? 23 : 24;
widened = ir.invoke("float", "unary.f32", opcode, {{"float", a}}, "nounwind readnone");
Expand Down Expand Up @@ -2611,6 +2628,12 @@ struct DirectCompute {
rounded = select(cmp("eq", source, "31744"), "31744", rounded);
rounded = select(cmp("ugt", source, "31744"), "32256", rounded);
rounded = select(cmp("eq", magnitude, "0"), "64512", rounded);
} else if (trig) {
const auto magnitude = ir.binary("and", source, "32767");
// Map +/-Inf and NaN to canonical quiet NaN; preserve -0.0 on v_sin_f16.
rounded = select(cmp("uge", magnitude, "31744"), "32256", rounded);
if (n == "v_sin_f16")
rounded = select(cmp("eq", source, "32768"), "32768", rounded);
}
// D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest says
// "On gfx10, all 16-bit instructions preserve the high bits", as v_cvt_f16_f32 above already does.
Expand Down Expand Up @@ -2959,14 +2982,7 @@ struct DirectCompute {
ir.value("fcmp oeq float " + b + ", 0.0"));
result = select_float(zero, "0.0", ir.value("fmul float " + a + ", " + b));
} else if (n == "v_sin_f32" || n == "v_cos_f32") {
// Victory trig_turns: reduce in turns before converting to
// radians, preserving signed zero and exact quarter-turn zeros.
auto part = ir.value("fsub float " + a + ", " + unary(26, a));
part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part);
const bool cosine = n == "v_cos_f32";
auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000");
auto exact = ir.value("fcmp oeq float " + unary(6, part) + (cosine ? ", 0.25" : ", 0.5"));
result = select_float(exact, "0.0", unary(cosine ? 12 : 13, radians));
result = trig_turns(n == "v_cos_f32", a);
} else if (cube)
result = cube_alu(n, a, fp(1), fp(2));
else if (n == "v_add_f32" || n == "v_sub_f32" || n == "v_subrev_f32" || n == "v_mul_f32") {
Expand Down
17 changes: 17 additions & 0 deletions tests/cmake/native_sin_cos_f16.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}")
add_test(NAME native_sin_cos_f16_ir COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" ir
"$<TARGET_FILE:native_compute_ir_dump>")
set_tests_properties(native_sin_cos_f16_ir PROPERTIES TIMEOUT 60)
endif()
if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND
EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll")
add_test(NAME native_sin_cos_f16_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" controls
"$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(native_sin_cos_f16_controls PROPERTIES TIMEOUT 60)
add_test(NAME native_sin_cos_f16_hardware COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" hardware
"$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}")
set_tests_properties(native_sin_cos_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120)
endif()
1 change: 0 additions & 1 deletion tests/native_f16_alu_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,6 @@ def refusal_programs():
programs.append(([0xb98005c1] + add + [0xbf810000], 'unsupported binary16 rounding or denormal mode'))
programs.append(([0xbfa40001] + add + [0xbf810000], 'unsupported compute control instruction s_round_mode'))
programs.append(([0xbfa5000c] + add + [0xbf810000], 'unsupported compute control instruction s_denorm_mode'))
programs.append((vop1(0x60, 3, 257) + [0xbf810000], 'direct DXIL lowering for v_sin_f16'))
for name, op in UNARY_CODE.items():
programs.append((vop1(op, 3, 250) + [0, 0xbf810000], 'unsupported v_%s_f16 DPP form' % name))
programs.append((vop3(op, 3, 257, 0, clamp=1, unary=True) + [0xbf810000],
Expand Down
Loading
Loading