Add gdb print methods support same as pytorch-lldb (#140935)

`pytorch-lldb` support pretty printing size and key_set of tensor via #97101

Add same pretty printing for gdb debugging.

**Test Result**

```bash
$ gdb python
(gdb) break at::native::negative
(gdb) r
>>> import torch
>>> t = torch.tensor([1, 2, 3, 4], dtype=torch.float64)
>>> t.negative()
Thread 1 "python" hit Breakpoint 1, at::native::negative (self=...) at /home/zong/code/pytorch/aten/src/ATen/native/UnaryOps.cpp:854
854	Tensor negative(const Tensor& self) { return self.neg(); }
```

**Before**
```bash
(gdb) p self.key_set()
$2 = {repr_ = 1271310352385}

(gdb) p self.sizes()
$3 = {Data = 0x9cb488, Length = 1}

```

**After**
```bash
(gdb) torch-int-array-ref-repr self.sizes()
[4]
(gdb) torch-dispatch-keyset-repr self.key_set()
DispatchKeySet(CPU, ADInplaceOrView, AutogradCPU, AutocastCPU)
```

```bash
$ lintrunner
```
![image](https://github.com/user-attachments/assets/b720e284-13b1-4581-ae3a-963f6482fdb2)

Pull Request resolved: https://github.com/pytorch/pytorch/pull/140935
Approved by: https://github.com/drisspg
This commit is contained in:
zeshengzong
2024-11-19 01:28:28 +00:00
committed by PyTorch MergeBot
parent 98e6e69b1b
commit 5b326d6b61

View File

@ -55,4 +55,53 @@ class TensorRepr(gdb.Command): # type: ignore[misc, no-any-unimported]
gdb.parse_and_eval(f"(void)free({int(res)})")
class IntArrayRefRepr(gdb.Command): # type: ignore[misc, no-any-unimported]
"""
Print human readable representation of c10::IntArrayRef
"""
def __init__(self) -> None:
gdb.Command.__init__(
self, "torch-int-array-ref-repr", gdb.COMMAND_USER, gdb.COMPLETE_EXPRESSION
)
def invoke(self, args: str, from_tty: bool) -> None:
args = gdb.string_to_argv(args)
if len(args) != 1:
print("Usage: torch-int-array-ref-repr EXP")
return
name = args[0]
with DisableBreakpoints():
res = gdb.parse_and_eval(f"torch::gdb::int_array_ref_string({name})")
res = str(res)
print(res[res.find('"') + 1 : -1])
class DispatchKeysetRepr(gdb.Command): # type: ignore[misc, no-any-unimported]
"""
Print human readable representation of c10::DispatchKeyset
"""
def __init__(self) -> None:
gdb.Command.__init__(
self,
"torch-dispatch-keyset-repr",
gdb.COMMAND_USER,
gdb.COMPLETE_EXPRESSION,
)
def invoke(self, args: str, from_tty: bool) -> None:
args = gdb.string_to_argv(args)
if len(args) != 1:
print("Usage: torch-dispatch-keyset-repr EXP")
return
keyset = args[0]
with DisableBreakpoints():
res = gdb.parse_and_eval(f"torch::gdb::dispatch_keyset_string({keyset})")
res = str(res)
print(res[res.find('"') + 1 : -1])
TensorRepr()
IntArrayRefRepr()
DispatchKeysetRepr()