-
Notifications
You must be signed in to change notification settings - Fork 1
Support printing tensors with custom names or titles ; support delimiter of multi dim tensor ; simplify code #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this 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 @fzyzcjy, 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 significantly improves the tensor debugging utility by introducing the capability to print tensors with custom, user-defined names or titles. This feature provides clearer identification of tensors in debug logs, making it easier to track specific data during complex computations. The changes span both the CUDA C++ kernels, which now accept and print these names, and the Python interface, which handles the encoding and efficient transfer of string data to the GPU.
Highlights
- Feature: Custom Tensor Naming: Implemented the ability to associate and print custom string names or titles alongside tensor data during debugging. This enhances the clarity and traceability of debug output by providing more context for printed tensors.
- C++ Kernel Refactoring: Introduced a new
__device__
helper functionPrintCommon
incsrc/debug_print.cu
to centralize the logic for printing tensor addresses and the new custom names. All existingPrint*Tensor*D
CUDA kernels were updated to accept an additionalname_ptr
argument and utilize this new common helper, reducing code duplication. - Python API and Memory Management: Refactored the Python
debug_print.print_tensor
function to accept an optionalname
argument. This involved creating_Buffer
and_DebugPrinter
classes to manage pre-allocated GPU memory for storing string names, ensuring efficient allocation and transfer of these names to the CUDA kernels. Aninitialize()
function was added to set up the_DebugPrinter
singleton.
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
-
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. ↩
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request adds a valuable feature for debugging by allowing custom names to be printed with tensors. The C++ changes are well-structured, refactoring common code into a helper function. However, the Python implementation has a few significant issues that need to be addressed:
- A critical bug in tensor creation that prevents the feature from working.
- A resource management issue where the name buffer is never reset, which will cause crashes in long-running applications.
- An API design that requires explicit initialization, making it less user-friendly.
I've provided suggestions to fix these issues. Once they are addressed, this will be a great addition to the library.
debug_print/__init__.py
Outdated
if len(name) > 0: | ||
name_bytes = name.encode("utf-8") | ||
name_buffer = self._buffers[x.device.index].allocate(len(name_bytes) + 1) | ||
tmp = torch.empty(list(name_bytes) + [0], dtype=torch.uint8, device="cpu") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a critical bug in how the temporary tensor for the name is created. torch.empty()
expects a shape (a tuple of integers), but it's being passed list(name_bytes) + [0]
, which is a list of byte values. This will create a tensor with incorrect dimensions (e.g., for name="a"
, it tries to create a tensor of shape (97, 0)
), causing a RuntimeError
during the copy_
operation.
You should use torch.tensor()
to create a tensor from data.
tmp = torch.empty(list(name_bytes) + [0], dtype=torch.uint8, device="cpu") | |
tmp = torch.tensor(list(name_bytes) + [0], dtype=torch.uint8, device="cpu") |
debug_print/__init__.py
Outdated
class _Buffer: | ||
def __init__(self, device_index: int): | ||
self._tensor = torch.zeros((10_000_000,), dtype=torch.char, device=f"cuda:{device_index}") | ||
self._used_len = 0 | ||
|
||
def allocate(self, size: int): | ||
output = self._tensor[self._used_len: self._used_len + size] | ||
self._used_len += size | ||
assert self._used_len <= len(self._tensor) | ||
return output |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The _Buffer
class implements a simple bump allocator by incrementing _used_len
but never resets it. In applications that capture CUDA graphs multiple times or in other long-running scenarios, this will lead to buffer exhaustion and an AssertionError
.
Consider adding a mechanism to reset the buffer. For example, you could add a reset()
method to _DebugPrinter
that users can call before a new graph capture session to reset the _used_len
of each buffer.
debug_print/__init__.py
Outdated
def initialize(): | ||
global _printer | ||
assert _printer is None | ||
_printer = _DebugPrinter() | ||
|
||
|
||
def print_tensor(x: torch.Tensor, print_ptr: bool = False): | ||
print_tensor_kernel(x, print_ptr) | ||
def print_tensor(x: torch.Tensor, name: str = "", print_ptr: bool = False): | ||
_printer(x=x, name=name, print_ptr=print_ptr) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation requires the user to explicitly call initialize()
before using print_tensor
. If not called, print_tensor
will raise an error because _printer
is None
. This is not ideal for usability, and the provided example.py
does not call initialize()
, meaning it would fail.
A better approach is to use lazy initialization, where the _DebugPrinter
is created on the first call to print_tensor
. This simplifies the API for the user by removing the need for an explicit initialization step.
def initialize(): | |
global _printer | |
assert _printer is None | |
_printer = _DebugPrinter() | |
def print_tensor(x: torch.Tensor, print_ptr: bool = False): | |
print_tensor_kernel(x, print_ptr) | |
def print_tensor(x: torch.Tensor, name: str = "", print_ptr: bool = False): | |
_printer(x=x, name=name, print_ptr=print_ptr) | |
def print_tensor(x: torch.Tensor, name: str = "", print_ptr: bool = False): | |
global _printer | |
if _printer is None: | |
_printer = _DebugPrinter() | |
_printer(x=x, name=name, print_ptr=print_ptr) |
csrc/debug_print.cu
Outdated
__device__ void PrintCommon(void* x, const char* name_ptr, const bool print_ptr) { | ||
if (name_ptr != nullptr) { | ||
printf("name: %s\n", name_ptr); | ||
} | ||
if (print_ptr) { | ||
printf("addr: %lld\n", x); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This reverts commit bacaf8c.
Close #1
API is suboptimal but I have no time to improve it currently, anyway it seems useable now.
output