@@ -846,10 +846,22 @@ def _process_batch_output(self):
846846 batch = self .output_tokens [1 ]
847847 accept_num = tokens [2 : batch + 2 ]
848848 elif self .use_logprobs :
849- batch = self .output_tokens [1 , 0 ]
850- tokens = tokens [2 : batch * (K + 1 ) + 2 ].reshape ([batch , K + 1 ])[:, : (K + 1 )]
851- scores = self .output_scores [: batch * (K + 1 )].numpy ().reshape ([batch , K + 1 ])[:, : (K + 1 )]
849+ # mtext[1] packs bsz (low 16 bits) and actual_topk (high 16 bits).
850+ # actual_topk = max_num_logprobs written by save_output_topk, which
851+ # equals the actual number of logprob columns in this step's message
852+ # (top_logprobs+1 across the batch). Using actual_topk as stride
853+ # avoids processing the K+1=21 fixed-size slots when fewer are needed.
854+ packed = int (self .output_tokens [1 , 0 ])
855+ batch = packed & 0xFFFF
856+ actual_topk = (packed >> 16 ) & 0xFFFF
857+ tokens = tokens [2 : batch * actual_topk + 2 ].reshape ([batch , actual_topk ])
858+ scores = self .output_scores [: batch * actual_topk ].numpy ().reshape ([batch , actual_topk ])
852859 ranks = self .output_ranks [:batch ].numpy ()
860+ # Pre-convert the full [batch, actual_topk] arrays to Python lists once,
861+ # avoiding per-row .tolist() calls inside the loop below.
862+ tokens_lists = tokens .tolist ()
863+ scores_lists = scores .tolist ()
864+ ranks_list = ranks .tolist ()
853865 else :
854866 batch = self .output_tokens [1 , 0 ]
855867 tokens = tokens [2 : batch + 2 ]
@@ -1022,10 +1034,11 @@ def _process_batch_output(self):
10221034 topk_logprobs = scores [i , batch_token_index , :].tolist ()
10231035 sampled_rank = ranks [i , batch_token_index ].item ()
10241036 else :
1025- result .outputs .logprob = float (scores [i , 0 ])
1026- topk_token_ids = tokens [i , :].tolist ()
1027- topk_logprobs = scores [i , :].tolist ()
1028- sampled_rank = ranks [i ].item ()
1037+ # Use pre-converted lists (batch .tolist() done before the loop).
1038+ result .outputs .logprob = scores_lists [i ][0 ]
1039+ topk_token_ids = tokens_lists [i ]
1040+ topk_logprobs = scores_lists [i ]
1041+ sampled_rank = ranks_list [i ]
10291042
10301043 if result .outputs .top_logprobs is None :
10311044 result .outputs .top_logprobs = LogprobsLists (
0 commit comments