sgl-project/sglang
View on GitHub[Performance] Remove instances of `torch.nonzero()` where appropriate
Open
#9,889 opened on Sep 2, 2025
good first issueperformance
Repository metrics
- Stars
- (28,442 stars)
- PR merge metrics
- (Avg merge 2d 1h) (1,000 merged PRs in 30d)
Description
Right now we have:
4 results - 4 files
python/sglang/srt/configs/janus_pro.py:
478 image_token_mask: torch.Tensor = (input_ids == self.image_id).to(torch.bool)
479: image_indices = image_token_mask.nonzero()
480 input_ids, num_image_tokens = self.add_image_token(
python/sglang/srt/models/gemma3_mm.py:
211 # Distinguish sequences by position id 0
212: start_indices = (positions == 0).cpu().nonzero()
213 num_seqs = len(start_indices)
python/sglang/srt/models/phi4mm_utils.py:
83 seq_range = torch.arange(0, x_len).unsqueeze(-1) # seq_range size: [x_len, 1]
84: idx = ((seq_range < end_pad) & (seq_range >= start_pad)).nonzero()[
85 :, 1
We should explore whether we can update these to reduce the host-device sync. You could profile it before trying to update to see if it really happens, or analyze the call sites deeply and test changes. However, if it doesn't force a sync, then updating it will do nothing and using some more advanced pytorch operations might be even more overhead. So edit the code judiciously. Why? See below.
[!CAUTION] When input is on CUDA, torch.nonzero() causes host-device synchronization.