Skip to content

Commit 17053f7

Browse files
committed
Fix zero division risk in embedding _compute_grid when M=0 and update div
1 parent faa7a2b commit 17053f7

2 files changed

Lines changed: 22 additions & 11 deletions

File tree

src/flag_gems/runtime/backend/_ascend/ops/div.py

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -141,17 +141,6 @@ def true_div_func_scalar_tensor(x, y):
141141
return x / y
142142

143143

144-
def _can_use_manual_kernel(A, B):
145-
"""Check if both tensors have the same shape (no broadcasting needed) and are float types."""
146-
if not isinstance(A, torch.Tensor) or not isinstance(B, torch.Tensor):
147-
return False
148-
if A.shape != B.shape:
149-
return False
150-
if not A.dtype.is_floating_point:
151-
return False
152-
return True
153-
154-
155144
def true_divide(A, B):
156145
logger.debug("GEMS_ASCEND TRUE_DIVIDE")
157146
if isinstance(A, torch.Tensor) and isinstance(B, torch.Tensor):

src/flag_gems/runtime/backend/_ascend/ops/embedding.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,8 @@ def _compute_block_sizes(N):
142142

143143

144144
def _compute_grid(M):
145+
if M == 0:
146+
return 0, 0
145147
ncore = min(M, NUM_VECTOR_CORES)
146148
rows_per_core = triton.cdiv(M, ncore)
147149
return ncore, rows_per_core
@@ -158,6 +160,18 @@ def forward(
158160
M = math.prod(indices.shape)
159161
N = weight.shape[-1]
160162

163+
if M == 0:
164+
ctx.M = 0
165+
ctx.N = N
166+
ctx.num_weights = weight.shape[0]
167+
ctx.padding_idx = padding_idx
168+
ctx.scale_grad_by_freq = scale_grad_by_freq
169+
ctx.sparse = sparse
170+
ctx.indices = indices
171+
return torch.empty(
172+
(*indices.shape, N), device=indices.device, dtype=weight.dtype
173+
)
174+
161175
BLOCK_SIZE, NUM_ITERS = _compute_block_sizes(N)
162176
ncore, rows_per_core = _compute_grid(M)
163177

@@ -188,6 +202,14 @@ def backward(ctx, grad_outputs):
188202
logger.debug("GEMS_ASCEND EMBEDDING BACKWARD")
189203
assert not ctx.sparse, "Currently do not support sparse format"
190204

205+
if ctx.M == 0:
206+
grad_inputs = torch.zeros(
207+
(ctx.num_weights, grad_outputs.shape[-1]),
208+
device=grad_outputs.device,
209+
dtype=grad_outputs.dtype,
210+
)
211+
return grad_inputs, None, None, None, None
212+
191213
grad_inputs = torch.zeros(
192214
(ctx.num_weights, grad_outputs.shape[-1]),
193215
device=grad_outputs.device,

0 commit comments

Comments
 (0)