diff --git a/megatron/core/inference/moe/activations.py b/megatron/core/inference/moe/activations.py index 169d8499116..b69d092cc1b 100644 --- a/megatron/core/inference/moe/activations.py +++ b/megatron/core/inference/moe/activations.py @@ -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 diff --git a/megatron/core/inference/text_generation_server/dynamic_text_gen_server/endpoints/completions.py b/megatron/core/inference/text_generation_server/dynamic_text_gen_server/endpoints/completions.py index d2279b0d07d..6f57a863c1c 100644 --- a/megatron/core/inference/text_generation_server/dynamic_text_gen_server/endpoints/completions.py +++ b/megatron/core/inference/text_generation_server/dynamic_text_gen_server/endpoints/completions.py @@ -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 @@ -92,6 +93,8 @@ async def completions(): if isinstance(stop, str): stop = [stop] + ignore_eos = bool(req.get("ignore_eos", False)) + sampling_params = SamplingParams( temperature=temperature, top_k=top_k, @@ -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 @@ -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)) @@ -160,6 +165,8 @@ 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: @@ -167,6 +174,17 @@ async def completions(): 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 @@ -230,20 +248,49 @@ async def completions(): "top_logprobs": top_logprobs, } - choices.append({"index": request_idx, "text": text_output, "logprobs": logprobs_data}) + choice_data = { + "index": request_idx, + "text": text_output, + "logprobs": logprobs_data, + "finish_reason": finish_reason, + "prompt_token_ids": result["prompt_tokens"], + "generation_token_ids": result["generated_tokens"], + "generation_log_probs": result.get("generated_log_probs", []), + } + choice_data["policy_epoch"] = result["policy_epoch"] + choice_data["kv_cache_epoch"] = result["kv_cache_epoch"] + choice_data["num_evictions"] = sum( + 1 for e in result["events"] if e.get("type") == "EVICT" + ) + if result["routing_indices"] is not None: - choices[-1]["moe_topk_indices"] = result["routing_indices"] + choice_data["moe_topk_indices"] = result["routing_indices"] prompt_length = ( len(result["prompt_tokens"]) if result["prompt_tokens"] is not None else 0 ) if prompt_length: - choices[-1]["prompt_moe_topk_indices"] = result["routing_indices"][ + choice_data["prompt_moe_topk_indices"] = result["routing_indices"][ :prompt_length ] + choices.append(choice_data) 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", # as per the openAI spec + "created": int(time.time()), + "model": "EMPTY", + "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}") diff --git a/megatron/core/ssm/ops/mamba_ssm.py b/megatron/core/ssm/ops/mamba_ssm.py index 4e079da8a31..672b00cf7dc 100644 --- a/megatron/core/ssm/ops/mamba_ssm.py +++ b/megatron/core/ssm/ops/mamba_ssm.py @@ -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 @@ -41,6 +43,15 @@ def softplus(dt): return tl.math.log1p(tl.exp(dt)) +@triton.jit +def fast_exp(x): + """ + Fast calculation of exponent via exponent of 2. + """ + 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}) @@ -49,7 +60,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, @@ -223,14 +234,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) @@ -368,15 +379,23 @@ 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