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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
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" + '
Fix Bugs of TE/JAX by mingxu1067 · Pull Request #119 · NVIDIA/TransformerEngine · GitHub
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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
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('^' + ".*" + ' Fix Bugs of TE/JAX by mingxu1067 · Pull Request #119 · NVIDIA/TransformerEngine · GitHub
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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
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('^' + ".*" + ' Fix Bugs of TE/JAX by mingxu1067 · Pull Request #119 · NVIDIA/TransformerEngine · GitHub
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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
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" + ' Fix Bugs of TE/JAX by mingxu1067 · Pull Request #119 · NVIDIA/TransformerEngine · GitHub
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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
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('^' + ".*" + ' Fix Bugs of TE/JAX by mingxu1067 · Pull Request #119 · NVIDIA/TransformerEngine · GitHub
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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
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('^' + ".*" + ' Fix Bugs of TE/JAX by mingxu1067 · Pull Request #119 · NVIDIA/TransformerEngine · GitHub
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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
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); } })(); })(); Fix Bugs of TE/JAX by mingxu1067 · Pull Request #119 · NVIDIA/TransformerEngine · GitHub
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
10 changes: 7 additions & 3 deletions tests/jax/test_sharding.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,13 @@ def _get_sharding_resource(mesh_names, sharding_type):
((4,), ("tp",), ShardingType.TP_ROW), ((2, 2), ("dp", "tp"), ShardingType.DP_TP_COL),
((2, 2), ("dp", "tp"), ShardingType.DP_TP_ROW)]

LOGICAL_RULES = [[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True]]
LOGICAL_RULES = [
[(('a1', None), ('a2', 'ma2')), False],
[(('a1', None), ('a2', 'ma2'), ('a3', ('ma31', 'ma32'))), True],
[(('a1', None), ('a2', 'ma2'), ('a3', 'ma31'), ('a3', 'ma32')), False],
[(('a1', None), ('a2', 'ma2'), ('batch', 'batch_1200234')), True],
[(('a1', None), ('a2', 'ma2'), ('a2', 'ma1'), ('batch', 'model'), ('batch', 'data')), True],
]
SRS = [
ShardingResource(),
ShardingResource('data', None),
Expand Down
3 changes: 2 additions & 1 deletion tests/jax/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -321,8 +321,9 @@ def __call__(self, inputs, deterministic: bool = False):

# Take elementwise product of above intermediate activations.
x = functools.reduce(operator.mul, activations)
dropout_broadcast_dims = (0,) if self.transpose_batch_sequence else (1,)
# Apply dropout and final dense output projection.
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
x = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=dropout_broadcast_dims)(
x, deterministic=deterministic) # Broadcast along length.
if self.transpose_batch_sequence:
x = nn_partitioning.with_sharding_constraint(x, ('length', 'batch', 'mlp'))
Expand Down
2 changes: 1 addition & 1 deletion transformer_engine/jax/fp8.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,7 +190,7 @@ def update_amax_history(amax_buffers: jnp.ndarray) -> jnp.ndarray:
Update the amax history
"""
updated_amax_buffers = jnp.roll(amax_buffers, -1, 1)
updated_amax_buffers.at[:, 0].set(0)
updated_amax_buffers = updated_amax_buffers.at[:, 0].set(0)
return updated_amax_buffers

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions transformer_engine/jax/module.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -683,6 +683,8 @@ class LayerNormMLP(TransformerEngineBase):
Each activation has its own transformation layer.
intermediate_dropout_rate: float, default = 0.1
Dropout probability for the dropout op after the :attr:`activations`.
intermediate_hidden_dropout_dims: Sequence[int], default = ()
Dimensions that will share the same dropout mask for hidden
axis: Union[Iterable[int], int], default = -1
An integer tuple with axes to apply the transformation on.

Expand DownExpand Up@@ -716,6 +718,7 @@ class LayerNormMLP(TransformerEngineBase):
return_layernorm_output: bool = True
activations: Sequence[Union[str, Callable]] = ('relu',)
intermediate_dropout_rate: float = 0.1
intermediate_hidden_dropout_dims: Sequence[int] = ()
axis: Union[Iterable[int], int] = -1
dtype: DType = jnp.float32
transpose_batch_sequence: bool = True
Expand DownExpand Up@@ -912,8 +915,9 @@ def fp8_meta_generator():
z = functools.reduce(operator.mul, activations)
z = jnp.reshape(z, (*z.shape[:-2], -1))

z = nn.Dropout(rate=self.intermediate_dropout_rate, broadcast_dims=(-2,))(
z, deterministic=deterministic) # Broadcast along length.
z = nn.Dropout(rate=self.intermediate_dropout_rate,
broadcast_dims=self.intermediate_hidden_dropout_dims)(
z, deterministic=deterministic)

# DenseGeneral 2
hidden_size = inputs.shape[-1]
Expand Down
49 changes: 27 additions & 22 deletions transformer_engine/jax/transformer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -53,6 +53,10 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
.. warning::
Please make sure ShardingResource is set via fp8_autocast before calling this function.

.. note::
This function is only needed when using TransformerLayer. For other modules, such as
DenseGeneral, please properly set axes of kernels and bias.

Parameters
----------
rules : Sequence[Tuple[str, Union[str, None]]]
Expand All@@ -73,10 +77,12 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
f"Thie axis_name should be str, but got {type(key)}."
assert isinstance(val, str) or (val is None), \
f"Thie mesh_axis_name should be str or None, but got {type(val)}."
rules_map[key] = val
if key in rules_map:
rules_map[key].append(val)
else:
rules_map[key] = [val]

gsr = global_shard_resource()

te_logical_axis_rules = (('batch', gsr.dp_resource), ('embed', None), ('mlp', gsr.tp_resource),
('heads', gsr.tp_resource), ('kv', None), ('qkv_dim', None),
('kv_dim', None), ('joined_kv', gsr.tp_resource), ('act', None),
Expand All@@ -87,7 +93,7 @@ def extend_logical_axis_rules(rules: LogicalRules) -> LogicalRules:
key = item[0]
val = item[1]
if key in rules_map:
assert rules_map[key] == val, \
assert len(rules_map[key]) == 1 and rules_map[key][0] == val, \
f"The rule diverged between TE and given rule." \
f"Axis:{key} map to {rules_map[key]} in the given" \
f" rules, but {val} in TE's rules."
Expand DownExpand Up@@ -447,41 +453,38 @@ def kv_init(key, shape, dtype):
if decode:
is_initialized = self.has_variable('cache', 'cached_key')

# TODO (Ming Huang): Check performance on GPU withou swap dimensions # pylint: disable=fixme
def swap_dims(x):
return x[:-3] + tuple(x[i] for i in [-2, -1, -3])

cached_key = self.variable('cache', 'cached_key', jnp.zeros, swap_dims(key.shape),
key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, swap_dims(value.shape),
cached_key = self.variable('cache', 'cached_key', jnp.zeros, key.shape, key.dtype)
cached_value = self.variable('cache', 'cached_value', jnp.zeros, value.shape,
value.dtype)
cache_index = self.variable('cache', 'cache_index',
lambda: jnp.array(0, dtype=jnp.int32))
if is_initialized:
batch, num_heads, head_dim, length = cached_key.value.shape
if self.transpose_batch_sequence:
length, batch, num_heads, head_dim = cached_key.value.shape
expected_shape = (1, batch, num_heads, head_dim)
one_hot_indices_shape = (length, 1, 1, 1)
else:
batch, length, num_heads, head_dim = cached_key.value.shape
expected_shape = (batch, 1, num_heads, head_dim)
one_hot_indices_shape = (1, length, 1, 1)

# Sanity shape check of cached key against input query.
expected_shape = (batch, 1, num_heads, head_dim)
if expected_shape != query.shape:
raise ValueError(
'Autoregressive cache shape error, '
f"expected query shape {expected_shape} instead got {query.shape}.")

cur_index = cache_index.value
one_hot_indices = jax_nn.one_hot(cur_index, length, dtype=key.dtype)
one_token_key = jnp.moveaxis(key, -3, -1)
one_token_value = jnp.moveaxis(value, -3, -1)
key = cached_key.value + one_token_key * one_hot_indices
value = cached_value.value + one_token_value * one_hot_indices
one_hot_indices = jnp.reshape(one_hot_indices, one_hot_indices_shape)
key = cached_key.value + key * one_hot_indices
value = cached_value.value + value * one_hot_indices
cached_key.value = key
cached_value.value = value
cache_index.value = cache_index.value + 1

key = jnp.moveaxis(key, -1, -3)
value = jnp.moveaxis(value, -1, -3)

mask = combine_masks(
mask, jnp.broadcast_to(jnp.arange(length) <= cur_index, (batch, 1, 1, length)))
mask, jnp.broadcast_to(jnp.arange(length) > cur_index, (batch, 1, 1, length)))
Comment thread
timmoon10 marked this conversation as resolved.
Outdated

if bias is not None:
bias = dynamic_vector_slice_in_dim(jnp.squeeze(bias, axis=0),
Expand DownExpand Up@@ -889,10 +892,11 @@ def hidden_dropout(x, deterministic):
assert isinstance(self.hidden_dropout_dims, Sequence)
x_shape_len = len(x.shape)
for dims in self.hidden_dropout_dims:
assert -x_shape_len < dims < x_shape_len
assert -x_shape_len <= dims < x_shape_len

return nn.Dropout(rate=self.hidden_dropout,
broadcast_dims=self.hidden_dropout_dims)(x, deterministic)
broadcast_dims=self.hidden_dropout_dims)(x,
deterministic=deterministic)

x = hidden_dropout(x, deterministic)
if self.drop_path > 0.0:
Expand DownExpand Up@@ -944,6 +948,7 @@ def hidden_dropout(x, deterministic):
intermediate_dim=self.mlp_hidden_size,
activations=self.mlp_activations,
intermediate_dropout_rate=self.hidden_dropout,
intermediate_hidden_dropout_dims=self.hidden_dropout_dims,
dtype=self.dtype,
scale_axes=('embed',),
kernel_init=self.mlp_kernel_init,
Expand Down