Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
2 changes: 1 addition & 1 deletion megatron/core/inference/moe/activations.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def _squared_relu_kernel(input_ptr, output_ptr, src_idx_ptr, M, N, BLOCK_N: tl.c
def padded_squared_relu(x: torch.Tensor, permutation_map: torch.Tensor) -> torch.Tensor:
"""Squared ReLU activation that skips padding rows."""
M, N = x.shape
out = torch.zeros(M, N, dtype=x.dtype, device=x.device)
out = torch.empty(M, N, dtype=x.dtype, device=x.device)
BLOCK_N = min(triton.next_power_of_2(N), 1024)
_squared_relu_kernel[(M,)](x, out, permutation_map, M, N, BLOCK_N=BLOCK_N)
return out
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio
import logging
import time
import uuid

from megatron.core.inference.inference_request import unwrap_serialized_tensors
from megatron.core.inference.sampling_params import SamplingParams
Expand Down Expand Up @@ -92,6 +93,8 @@ async def completions():
if isinstance(stop, str):
stop = [stop]

ignore_eos = bool(req.get("ignore_eos", False))
Comment thread
sidsingh-nvidia marked this conversation as resolved.
Resolved

sampling_params = SamplingParams(
temperature=temperature,
top_k=top_k,
Expand All @@ -101,6 +104,7 @@ async def completions():
skip_prompt_log_probs=skip_prompt_log_probs,
num_tokens_to_generate=int(req.get("max_tokens", 16)),
stop_words=stop,
termination_id=-1 if ignore_eos else None,
)
except ValueError as e:
return f"Invalid sampling parameter: {e}", 400
Expand All @@ -117,6 +121,7 @@ async def completions():
skip_prompt_log_probs=sampling_params.skip_prompt_log_probs,
num_tokens_to_generate=sampling_params.num_tokens_to_generate,
stop_words=sampling_params.stop_words,
termination_id=sampling_params.termination_id,
)
tasks.append(client.add_request(prompt_tokens, per_req_params))

Expand Down Expand Up @@ -160,13 +165,26 @@ async def completions():

# --- 5. Format Response (matching old_completions.py) ---
choices = []
total_completion_tokens = 0
prompt_tokens_counts = []

request_idx = 0
for completed_request in batch_results:
result = unwrap_serialized_tensors(completed_request)
full_text = result["generated_text"] or ""
text_output = (prompts_as_strings[request_idx] + full_text) if echo else full_text

generated_tokens = result.get("generated_tokens") or []
prompt_tokens_list = result.get("prompt_tokens") or []
total_completion_tokens += len(generated_tokens)
prompt_tokens_counts.append(len(prompt_tokens_list))

finish_reason = "length"
sampling_params_result = result.get("sampling_params") or {}
num_tokens_requested = sampling_params_result.get("num_tokens_to_generate")
if num_tokens_requested is None or len(generated_tokens) < num_tokens_requested:
finish_reason = "stop"

logprobs_data = None
if sampling_params.return_log_probs:
# Get prompt tokens and logprobs
Expand Down Expand Up @@ -230,7 +248,12 @@ async def completions():
"top_logprobs": top_logprobs,
}

choices.append({"index": request_idx, "text": text_output, "logprobs": logprobs_data})
choices.append({
"index": request_idx,
"text": text_output,
"logprobs": logprobs_data,
"finish_reason": finish_reason,
})
if result["routing_indices"] is not None:
choices[-1]["moe_topk_indices"] = result["routing_indices"]
prompt_length = (
Expand All @@ -243,7 +266,19 @@ async def completions():

request_idx += 1

return jsonify({"choices": choices})
prompt_token_count = max(prompt_tokens_counts) if prompt_tokens_counts else 0
return jsonify({
"id": str(uuid.uuid4()),
"object": "text_completion",
"created": int(time.time()),
"model": "EMPTY",
Comment thread
sidsingh-nvidia marked this conversation as resolved.
Resolved
"choices": choices,
"usage": {
"prompt_tokens": prompt_token_count,
"completion_tokens": total_completion_tokens,
"total_tokens": prompt_token_count + total_completion_tokens,
},
})

except ImportError as e:
logger.warning(f"Could not import quart: {e}")
logger.warning(f"Could not import quart: {e}")
43 changes: 30 additions & 13 deletions megatron/core/ssm/ops/mamba_ssm.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
# Copyright (c) 2024, Tri Dao, Albert Gu.

# Some of this code was adopted from https://github.com/state-spaces/mamba/
# and https://github.com/vllm-project/vllm.
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this source tree.


import torch
from packaging import version

Expand Down Expand Up @@ -41,6 +43,12 @@ def softplus(dt):
return tl.math.log1p(tl.exp(dt))


@triton.jit
def fast_exp(x):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have seen this trick before but does this change numerics at all, as in is accuracy of models training without it giving the same accuracy? also assuming this is used for both training and inference so we dont get larger train/inference diff

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if these kernels are used in training. I do not see a backwards pass here, so I assume they are not.

Concerns about numerics are valid. This trick is borrowed from vLLM, so atleast it has some precedent.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we verify that our functional tests still pass at least?

LOG2E = tl.constexpr(1.4426950408889634)
return tl.math.exp2(LOG2E * x)


@triton.heuristics({"HAS_DT_BIAS": lambda args: args["dt_bias_ptr"] is not None})
@triton.heuristics({"HAS_D": lambda args: args["D_ptr"] is not None})
@triton.heuristics({"HAS_Z": lambda args: args["z_ptr"] is not None})
Expand All @@ -49,7 +57,7 @@ def softplus(dt):
)
@triton.heuristics({"HAS_INT_STATE": lambda args: args["int_state_ptr"] is not None})
@triton.heuristics({"BLOCK_SIZE_DSTATE": lambda args: triton.next_power_of_2(args["dstate"])})
@triton.jit
@triton.jit(do_not_specialize=["batch"])
def _selective_scan_update_kernel(
# Pointers to matrices
state_ptr,
Expand Down Expand Up @@ -223,14 +231,14 @@ def _selective_scan_update_kernel(
dt += tl.load(dt_bias_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32)
if DT_SOFTPLUS:
dt = tl.where(dt <= 20.0, softplus(dt), dt)
dA = tl.exp(A * dt[:, None])
dA = fast_exp(A * dt[:, None])
else:
dt = tl.load(dt_ptr + s * stride_dt_seq).to(tl.float32)
if HAS_DT_BIAS:
dt += tl.load(dt_bias_ptr).to(tl.float32)
if DT_SOFTPLUS:
dt = tl.where(dt <= 20.0, softplus(dt), dt)
dA = tl.exp(A * dt)
dA = fast_exp(A * dt)

# Load B and C
B = tl.load(B_s_ptrs, mask=offs_n < dstate, other=0.0).to(tl.float32)
Expand Down Expand Up @@ -368,15 +376,24 @@ def selective_state_update(
(z.stride(0), z.stride(1), z.stride(2), z.stride(3)) if z is not None else (0, 0, 0, 0)
)

BLOCK_SIZE_M, num_warps = (
(32, 4)
if dstate <= 16
else (
(16, 4)
if dstate <= 32
else ((8, 4) if dstate <= 64 else ((4, 4) if dstate <= 128 else ((4, 8))))
)
)
is_blackwell = torch.cuda.get_device_capability(x.device)[0] >= 10


# Default
BLOCK_SIZE_M, num_warps = 4, 8
if dstate <= 16:
BLOCK_SIZE_M, num_warps = 32, 4
elif dstate <= 32:
BLOCK_SIZE_M, num_warps = 16, 4
elif dstate <= 64:
BLOCK_SIZE_M, num_warps = 8, 4
else:
# dstate > 64
if is_blackwell:
# Optimized for B200 with dstate>64
BLOCK_SIZE_M, num_warps = 32, 8
elif dstate <= 128:
BLOCK_SIZE_M, num_warps = 4, 4

tie_hdim = (
A.stride(-1) == 0
Expand Down Expand Up @@ -451,4 +468,4 @@ def selective_state_update(
if is_seq_unsq:
out = out.squeeze(1)

return out
return out
Loading