Skip to content

Conversation

@kingder
Copy link
Collaborator

@kingder kingder commented Jul 11, 2025

No description provided.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @kingder, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request aims to enhance the performance of the radix_cache component by optimizing its core match function. The key change involves migrating from a standard Python loop-based comparison to a more efficient implementation utilizing torch.Tensor operations, which is designed to yield significant speed improvements for sequence matching.

Highlights

  • Performance Optimization: The match function within the radix_cache module has been refactored to leverage torch.Tensor operations for more efficient comparison of numerical sequences. This change is expected to significantly improve performance, especially for larger inputs, by utilizing vectorized operations.
  • Code Modernization: The previous Python loop-based comparison in the match function has been replaced with a more idiomatic and potentially hardware-accelerated implementation using torch operations, enhancing both performance and maintainability.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request optimizes the match function in the radix cache by using vectorized PyTorch operations. I've suggested using torch.argmax instead of torch.nonzero for better memory efficiency.

Comment on lines +85 to +98
def match(t1: torch.Tensor, t2: torch.Tensor) -> int:
# Ensure same shape for comparison: flatten and get min length
t1_flat = t1.flatten()
t2_flat = t2.flatten()
min_len = min(t1_flat.size(0), t2_flat.size(0))

# Compare elements and find first mismatch
diff = t1_flat[:min_len] != t2_flat[:min_len]
mismatch_indices = torch.nonzero(diff)

if mismatch_indices.numel() == 0:
return min_len # All matched up to min_len
else:
return mismatch_indices[0].item()
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider using torch.argmax instead of torch.nonzero for better efficiency. torch.nonzero creates a tensor of all indices where the condition is true, which can be memory-intensive. torch.argmax finds the index of the first True value without allocating memory for all mismatch indices.

Suggested change
def match(t1: torch.Tensor, t2: torch.Tensor) -> int:
# Ensure same shape for comparison: flatten and get min length
t1_flat = t1.flatten()
t2_flat = t2.flatten()
min_len = min(t1_flat.size(0), t2_flat.size(0))
# Compare elements and find first mismatch
diff = t1_flat[:min_len] != t2_flat[:min_len]
mismatch_indices = torch.nonzero(diff)
if mismatch_indices.numel() == 0:
return min_len # All matched up to min_len
else:
return mismatch_indices[0].item()
def match(t1: torch.Tensor, t2: torch.Tensor) -> int:
t1_flat = t1.flatten()
t2_flat = t2.flatten()
min_len = min(t1_flat.size(0), t2_flat.size(0))
if min_len == 0:
return 0
diff = t1_flat[:min_len] != t2_flat[:min_len]
if not torch.any(diff):
return min_len
return torch.argmax(diff.byte()).item()

@hiworldwzj hiworldwzj merged commit fc72ffa into ModelTC:main Jul 11, 2025
1 check passed
@kingder
Copy link
Collaborator Author

kingder commented Jul 11, 2025

import time
import torch
import random

def match(key, seq):
    i = 0
    for k, w in zip(key, seq):
        if k != w:
            break
        i += 1
    return i

def match2(t1: torch.Tensor, t2: torch.Tensor) -> int:
    # Ensure same shape for comparison: flatten and get min length
    t1_flat = t1.flatten()
    t2_flat = t2.flatten()
    min_len = min(t1.size(0), t2.size(0))

    # Compare elements and find first mismatch
    diff = t1[:min_len] != t2[:min_len]
    # print(diff)
    mismatch_indices = torch.nonzero(diff)
    # print(mismatch_indices)

    if mismatch_indices.numel() == 0:
        return min_len  # All matched up to min_len
    else:
        return mismatch_indices[0].item()

def generate_random_tensors(min_len=3, max_len=10, min_val=0, max_val=100):
    len1 = random.randint(min_len, max_len)
    len2 = random.randint(min_len, max_len)

    t1 = torch.randint(min_val, max_val, (len1,))
    t2 = torch.randint(min_val, max_val, (len2,))

    return t1, t2

start = time.time()

t1, t2 = 0, 0

for i in range(100):
    key, seq = generate_random_tensors(min_len=1000, max_len=10000)
    start = time.time()
    p1 = match2(key, seq)
    t1 += time.time() - start
    start = time.time()
    p2 = match(key, seq)
    t2 += time.time() - start
    assert p1 == p2, f"Mismatch: {p1} != {p2}"


print("Total time for 100 iterations:", t1, t2)

Total time for 100 iterations: 0.004180431365966797 1.0978515148162842

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants