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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
67 changes: 43 additions & 24 deletions tests/jax/test_fused_attn.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,7 +113,7 @@ def customcall_cross_fused_attn(q, kv, q_token, kv_token, dropout_rng, **kwargs)
reason="Fused attention kernel is not supported.")
class TestSelfFusedAttnMax512():

def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
key = jax.random.PRNGKey(0)
subkeys = jax.random.split(key, 2)

Expand All@@ -125,16 +125,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):

min_val, max_val = -1, 1
self.qkv = jax.random.uniform(subkeys[0], qkv_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val, max_val)
self.bias = jax.random.uniform(subkeys[1], bias_shape, dtype, min_val,
max_val) if with_bias else None

self.q_token = jnp.concatenate((jnp.ones((b, self.valid_len)), jnp.zeros((b, pad_len))),
axis=-1)
self.kv_token = self.q_token

self.scaling_factor = 1. / math.sqrt(d)
self.dropout_probability = 0.
self.dropout_rng = jax.random.PRNGKey(0)
self.attn_bias_type = AttnBiasType.POST_SCALE_BIAS
self.dropout_rng = jax.random.PRNGKey(0) if self.dropout_probability > 0 else None
self.attn_bias_type = AttnBiasType.NO_BIAS if self.bias is None else AttnBiasType.POST_SCALE_BIAS
# deterministic = not is_training
self.deterministic = False

Expand All@@ -143,9 +144,17 @@ def set_input(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('attn_mask_type',
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):

self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

primitive_out = customcall_self_fused_attn(self.qkv,
self.bias,
Expand DownExpand Up@@ -183,8 +192,16 @@ def test_forward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
[AttnMaskType.PADDING_MASK, AttnMaskType.CAUSAL_MASK])
@pytest.mark.parametrize('dtype', DTYPES)
@pytest.mark.parametrize('pad_ratio', PAD_RATIO)
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio):
self.set_input(b, s, h, d, dtype=dtype, attn_mask_type=attn_mask_type, pad_ratio=pad_ratio)
@pytest.mark.parametrize('with_bias', [True, False])
def test_forward_backward(self, b, s, h, d, dtype, attn_mask_type, pad_ratio, with_bias):
self.set_input(b,
s,
h,
d,
dtype=dtype,
attn_mask_type=attn_mask_type,
pad_ratio=pad_ratio,
with_bias=with_bias)

def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Gradient is small, use a gradient multiplier to amplify the graident
Expand DownExpand Up@@ -221,11 +238,11 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
(0, 1)))

primitive_out, (primitive_dqkv,
primitive_dbeta) = jitted_primitive(self.qkv, self.bias, self.q_token,
primitive_dbias) = jitted_primitive(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

reference_out, (reference_dqkv,
reference_dbeta) = jitted_reference(self.qkv, self.bias, self.q_token,
reference_dbias) = jitted_reference(self.qkv, self.bias, self.q_token,
self.kv_token, self.dropout_rng)

np.testing.assert_allclose(jnp.asarray(primitive_out, np.float32),
Expand DownExpand Up@@ -261,20 +278,22 @@ def grad_func(fused_attn_max_512_func, *args, **kwargs):
# Padded part should be 0s
assert jnp.allclose(invalid_primitive_dqkv, jnp.zeros_like(invalid_primitive_dqkv))

# dbeta valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbeta[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbeta padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbeta[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(primitive_dbeta[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbeta[:, :, self.valid_len:, self.valid_len:]))
if self.attn_bias_type != AttnBiasType.NO_BIAS:
Comment thread
nouiz marked this conversation as resolved.
# dbias valid part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
jnp.asarray(reference_dbias[:, :, :self.valid_len, :self.valid_len], np.float32),
rtol=1e-4,
atol=3e-5)

# dbias padded part
np.testing.assert_allclose(
jnp.asarray(primitive_dbias[:, :, self.valid_len:, self.valid_len:], np.float32),
jnp.asarray(reference_dbias[:, :, self.valid_len:, self.valid_len:], np.float32))

assert jnp.allclose(
primitive_dbias[:, :, self.valid_len:, self.valid_len:],
jnp.zeros_like(primitive_dbias[:, :, self.valid_len:, self.valid_len:]))


@pytest.mark.skipif(not is_fused_attn_kernel_available(),
Expand Down
6 changes: 6 additions & 0 deletions tests/jax/test_layer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,12 @@ def compare_frozen_dict(ref_fd, test_fd, rtol=1e-05, atol=1e-08):
_KEY_OF_DROPOUT_RATE: 0.0,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_SCALE_ATTN_LOGITS: True,
_KEY_OF_LAYERNORM_TYPE: 'rmsnorm',
_KEY_OF_DROPOUT_RATE: 0.8,
_KEY_OF_MLP_ACTIVATIONS: (('gelu', 'linear')),
_KEY_OF_FUSE_MLP_WI: True
}, {
_KEY_OF_TRANSPOSE_BS: False,
_KEY_OF_SCALE_ATTN_LOGITS: True,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -327,7 +327,6 @@ static cudnn_frontend::Tensor createSoftmaxForward(
// NOLINTNEXTLINE(runtime/references)
std::vector<cudnn_frontend::Operation> &ops,
cudnn_frontend::Tensor const &prevBlockOutputTensor) {

int64_t afterBMM1_dim[4] = {b, h, s_q, s_kv};
int64_t afterBMM1_stride[4] = {h * s_q * s_kv, s_q * s_kv, s_kv, 1};

Expand DownExpand Up@@ -645,7 +644,7 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_fprop_cache;
static thread_local CacheType fmha_fprop_cache;

bool enable_dropout = (dropout_probability != 0.0f);

Expand All@@ -668,7 +667,8 @@ void fused_attn_max_512_fwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
createScale(b, h, s_q, s_kv, d, layout, tensorType, ops);

// if bias, we need to memset the S buffer to correctly computate dbias
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS);
auto zero_s = (bias_type != NVTE_Bias_Type::NVTE_NO_BIAS) ||
(mask_type == NVTE_Mask_Type::NVTE_CAUSAL_MASK);
Comment thread
zlsh80826 marked this conversation as resolved.
auto bmm1_output = createBMM1(b, h, s_q, s_kv, d, layout, tensorType, zero_s, ops);

NVTE_CHECK(bias_type != NVTE_Bias_Type::NVTE_PRE_SCALE_BIAS,
Expand DownExpand Up@@ -814,7 +814,7 @@ void fused_attn_max_512_bwd_impl(int64_t b, int64_t h, int64_t s_q, int64_t s_kv
layout, bias_type, mask_type, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fmha_bprop_cache;
static thread_local CacheType fmha_bprop_cache;

auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
auto it = cache.find(descriptor);
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/common/fused_attn/fused_attn_fp8.cu
Original file line numberDiff line numberDiff line change
Expand Up@@ -1016,7 +1016,7 @@ void fa_fwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_fprop_cache;
static thread_local CacheType fa_fprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand DownExpand Up@@ -1332,7 +1332,7 @@ void fa_bwd_fp8(int64_t b, int64_t s_q, int64_t s_kv, int64_t h, int64_t d,
NVTE_Bias_Type::NVTE_NO_BIAS, NVTE_Mask_Type::NVTE_PADDING_MASK, tensorType};

using CacheType = std::map<FADescriptor, cudnn_frontend::ExecutionPlan>;
static CacheType fa_bprop_cache;
static thread_local CacheType fa_bprop_cache;

// Get plan from cache if cache is available, otherwise create one
auto get_plan = [&](CacheType &cache, const FADescriptor &descriptor) {
Expand Down
17 changes: 14 additions & 3 deletions transformer_engine/jax/flax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
import functools
from enum import Enum
from math import sqrt
import os
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import warnings

Expand DownExpand Up@@ -165,8 +166,17 @@ def core_attention(query: Array,
else:
attn_weights = jnp.einsum('bqhd,bkhd->bhqk', query, key)

# When a bias is present, the computation is performed as Softmax(attn_weights * scale + bias).
# In this case, the scale can not fused into the Softmax module.
if bias is not None:
attn_weights = attn_weights * scale_factor
fused_scale_factor = 1.
else:
# If no bias, the scale can be fused into Softmax module
fused_scale_factor = scale_factor

attn_weights = Softmax(softmax_type=softmax_type,
scale_factor=scale_factor,
scale_factor=fused_scale_factor,
sharding_type=softmax_sharding_type)(attn_weights, mask, bias)

if not deterministic and dropout_rate > 0.:
Expand DownExpand Up@@ -360,12 +370,13 @@ def kv_init(key, shape, dtype):
q_seqlen = inputs_q.shape[0] if self.transpose_batch_sequence else inputs_q.shape[1]
kv_seqlen = inputs_kv.shape[0] if self.transpose_batch_sequence else inputs_kv.shape[1]
fused_attn_supported_seqlen = [128, 256, 384, 512]
enable_fused_attn = int(os.getenv("NVTE_FUSED_ATTN", "0"))
use_fused_attn = not decode and not self.transpose_batch_sequence and self.fuse_qkv and \
self.dropout_rate == 0 and canonicalize_dtype in [jnp.bfloat16, jnp.float16] and \
q_seqlen in fused_attn_supported_seqlen and kv_seqlen in fused_attn_supported_seqlen \
and is_fused_attn_kernel_available()
and is_fused_attn_kernel_available() and enable_fused_attn

if not use_fused_attn:
if enable_fused_attn and not use_fused_attn:
reason = ""
if decode:
reason += f"decode=False is required but got {decode}, "
Expand Down
4 changes: 2 additions & 2 deletions transformer_engine/jax/sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -386,7 +386,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],

for input_shape, dp_dim, tp_dim in zip(input_shapes, input_dp_dims, input_tp_dims):
in_axis = {}
if dp_dim is not None:
if dp_dim is not None and input_shape is not None:
in_axis[dp_dim] = dp_axis_name
assert input_shape[dp_dim] % dp_size == 0, \
f"The dimension of batch in input_shape should be a multiple of " \
Expand All@@ -398,7 +398,7 @@ def _get_dptp_sharding_meta(input_shapes: Tuple[Tuple[int, ...]],
if tp_dim is not None and tp_dim >= dp_dim:
tp_dim = tp_dim + 1

if tp_dim is not None:
if tp_dim is not None and input_shape is not None:
in_axis[tp_dim] = tp_axis_name
assert input_shape[tp_dim] % tp_size == 0, \
f"The dimension of tensor parallel in input_shape should be a multiple of " \
Expand Down