Skip to content
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

Log TensorBoard histograms #19743

Open
dominicgkerr opened this issue Apr 7, 2024 · 2 comments · May be fixed by #19851
Open

Log TensorBoard histograms #19743

dominicgkerr opened this issue Apr 7, 2024 · 2 comments · May be fixed by #19851
Labels
feature Is an improvement or enhancement needs triage Waiting to be triaged by maintainers

Comments

@dominicgkerr
Copy link
Contributor

dominicgkerr commented Apr 7, 2024

Description & Motivation

I'd like to be able to log histograms using TensorBoard. Looking at how multiple/single scalars are currently logged by lightning.fabric.loggers.TensorBoardLogger [1], I think SummaryWriter.add_histogram [2] could be called (non-empty torch.Tensor instances) in a similar way

Unfortunately, values passed into LightningModule.log are first type-checked by LightningModule.__to_tensor [3] - this enforces values to be either dict or single-value (0Dim) torch.Tensor instances. So in order to support histograms, this check would need to be loosen slightly...

Pitch

Firstly, I'm proposing [4] becomes:

if not (torch.numel(value) == 1 or (torch.numel(value) > 0 and value.ndim == 1)):
    raise ValueError(
        f"`self.log({name}, {value})` was called, but the tensor must have a single element,"
        f"or a single non-empty dimension. You can try doing `self.log({name}, {value}.mean())`"
    )

and [1] becomes (say):

try:
    if isinstance(v, dict):
        self.experiment.add_scalars(k, v, step)
    elif isinstance(v, Tensor):
        self.experiment.add_histogram(k, v, step)
    else:
        self.experiment.add_scalar(k, v, step)

# TODO(fabric): specify the possible exception
except Exception as ex:
    raise ValueError(
        f"\n you tried to log {v} which is currently not supported. Try a dict or a scalar/tensor."
    ) from ex

I'm sure you're keen not to modify LightnginModule too much, but I couldn't figure out a way to pass 1+Dim Tensor instances through to the TensorBoardLogger without loosing the type checking.

Alternatives

As a workaround, I'm currently using a subclass of LightningModule that overloads the .log method [5] with:

def log(self, name: str, value: _METRIC, *args, **kwargs):
    if isinstance(value, Tensor) and value.ndim > 0:
        for logger in self.loggers:
            if isinstance(logger, TensorBoardLogger):
                logger.experiment.add_histogram(name, value, self.global_step)

    else:
        super().log(name, value, *args, **kwargs)

Introducing TensorBoard specifics into the LightningModule class, is a horrible hack (hence wanting to incorporate the "nicer" fix above!)

Additional context

I'm very happy to open a PR (I have one written up from exploring potential implementations) is the above sounds reasonable?

Many thanks!

cc @Borda

@dominicgkerr dominicgkerr added feature Is an improvement or enhancement needs triage Waiting to be triaged by maintainers labels Apr 7, 2024
@dominicgkerr
Copy link
Contributor Author

@Borda Hello! Do you have any thoughts or concerns about this feature request? Would opening a PR implementing the above be helpful? Let me know if you need anymore information. Many thanks

@dominicgkerr dominicgkerr linked a pull request May 6, 2024 that will close this issue
10 tasks
@dominicgkerr
Copy link
Contributor Author

Hi, I've open a PR (#19851) to help illustrate the above description/request. Please let me know if there's anything else I can do to help - thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Is an improvement or enhancement needs triage Waiting to be triaged by maintainers
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant