Skip to content

[tune] best practices for parallel hyper-param search on a pytorch-lightning module ? #8976

Closed

Description

@orm011

what does the ray community see as good ways to interface with pytorch lightning?

I'm new to Ray, and to some extent to pytorch lightning (less than a month). My use case was as follows.

I developed a model as a LightningModule. l tried a few hyperparameters that seem relevant. I wanted to do a more thorough hyperparameter search parallelized across trials, and I saw the tutorial on different hyperparameter search schedulers, which seem helpful to me so I would like to use tune for that reason as well.

Ideally, I would take my pytorch lightning module and that would be enough for ray.tune to do the search (perhaps with minor modifications to the dataloader methods, to control number of workers), it doesn’t look like there is a tutorial on this at the moment.

My first take was to make a trainable interface that wraps both the LightningModule and a pl.Trainer. The current downside is that pl.Trainer.fit() is not very flexible from what I can tell. I cannot specify for it to run only for one more epoch, instead I need to work around it to try coercing it to do that. Here is what I ended up doing roughly,
https://gist.github.com/orm011/6b8e7465a2a80124f97fd9bb7b8a87ec

I trained a few things with it, but I’m not sure epoch and learning rate are being adjusted properly. The tensorflow logs at least don’t show the learning rate changing.

Do you recommend some other way of achieving the same goal (without the downsides)? There is probably also a question for the pytorch lightning project in here, about how to use their Trainer for a situations like this, but I will take that up separately.

Activity

  1. added
    question
    on Jun 16, 2020
  2. richardliaw commented on Jun 16, 2020

    @richardliaw
    Contributor

    You should be able to do this with a PTL callback. Create a custom callback and then simply call tune.report inside the callback (see the Keras callback for an example) .

    Can you try this out and let me know if that works?

  3. self-assigned this
    on Jun 16, 2020
  4. richardliaw commented on Jun 30, 2020

    @richardliaw
    Contributor

    Hey @orm011, we just merged a walkthrough for using Tune with Pytorch Lightning. Would you be interested in giving it a try? https://docs.ray.io/en/master/tune/tutorials/tune-pytorch-lightning.html

  5. orm011 commented on Jul 2, 2020

    @orm011
    Author

    Thanks, that was helpful. I got what I needed working.

    About your tutorial, I tried it out, the Asha part worked well.
    I checked the population based one, mostly to see what the checkpointing and resuming would look like.

    This code worked for me.

    class CheckpointCallback(Callback):
        def on_validation_end(self, trainer, pl_module):
            path = tune.make_checkpoint_dir(trainer.global_step)
            trainer.save_checkpoint(os.path.join(path, "checkpoint"))
            tune.save_checkpoint(path)
    
    def train_mnist_tune_checkpoint(config, checkpoint=None):
        if checkpoint is None or len(checkpoint) == 0: # sometimes gets {} as input.
            checkpoint_path = None
        else:
            checkpoint_path = os.path.join(checkpoint, "checkpoint")
    
        trainer = pl.Trainer(
            max_epochs=10,
            gpus=1,
            progress_bar_refresh_rate=0,
            callbacks=[CheckpointCallback(),
                       TuneReportCallback(), 
                       pl.callbacks.LearningRateLogger()
                      ],
            resume_from_checkpoint=checkpoint_path)
        
        model = LightningMNISTClassifier(config)
        trainer.fit(model)
    

    By worked I mean it the state was preserved, including optimizer and learning rate scheduler state in the trainer. (not just the epoch). This might be the desirable way to reload for a scheduler that stops and later wants to resume training from an old checkpoint as if nothing happened.

    On the other hand, I was logging the learning rates and I did not see jumps on the plot, despite perturbations from PBT being logged by ray.tune. Maybe the config perturbations get overwritten by reloading through the trainer the way I do. Perhaps that's why you were reloading differently, but simply reloading the model without reloading the Trainer could break something else, eg, if we are not perturbing the training rate. I'm not familiar with the pbt scheduler so maybe I'm missing the point.

    Here's a notebook of your code, but with modifications as above, and a couple other things people new to pl and or ray.tune may run into, as I did.

    1. type hiccups with tune.choice() (causing tensorboard to not log num layers hyperparam, and dataloader to fail if we modify the batch size, though I saw you made it into an int() there.
    2. type hiccups with output metrics from pytorch lightning (causing dataframe to have tensors in it) also
    3. {} being fed as checkpoint, causing os.path.join() to fail.
    4. showing how to set the gpu stuff (ie, you set your gpu to 1 in trainer)

    https://github.com/orm011/some_nbs/blob/6999682c36d7ec493c8bd60e66a3b0efcde1c084/ray_pl%20(1).ipynb

    PS one slight remaining pain point is that there are separate loggers for pl, and for tune (same model effectively gets two log folders and two entries in tensorboard). Ideally I'd give the Trainer the logger from tune (or something to identify it) so that things logged from both sides fall under the same name and color in tensorboard.

  6. krfricke commented on Jul 2, 2020

    @krfricke
    Contributor

    Thanks for your feedback, Oscar. I'll look at this closer next week. It seems there are some things we might include in the walkthrough, but other things might have to be addressed in Tune/PBT (like the {} checkpoint paths). I'll get back to this.

  7. orm011 commented on Jul 2, 2020

    @orm011
    Author

    Yeah, thanks for looking into it. These two tools are a great combo for people working with pytorch. The trainer callback API in PL may allow for PBT perturbations to be done after all model and trainer state has been restored,and before training resumes, but it is hard to tell without reading PL code what the state of the system is meant to be when each callback method is invoked.

  8. reopened this on Jul 2, 2020
  9. added
    tune
    on Jul 8, 2020
  10. krfricke commented on Jul 13, 2020

    @krfricke
    Contributor

    Just as a quick update, we are working on a small PR addressing some of these issues. We will fix the PT tensor conversion with tensor.item() and add GPU support (the former is actually necessary for the latter to work).
    For the empty checkpoints, a general if checkpoint: should suffice, so we will use that.

    We will discuss the tune.choice() and logging redirection later. It's a bit unfortunate that PTL cannot deal with numpy int64 types. A possible solution would be to use random.choice instead of np.random.choice internally. I'll get back to you on that later.

    Thanks for your insights, it's very helpful.

  11. krfricke commented on Jul 13, 2020

    @krfricke
    Contributor

    We address all your issues in this PR: #9451

    We decided to use random.choice() for tune.choice(), preserving types like primitive integers. For reference, this is how you can put the PTL logs into the trial root dir, so it doesn't show up twice in tensorboard:

        trainer = pl.Trainer(
            max_epochs=num_epochs,
            gpus=num_gpus,
            logger=TensorBoardLogger(
                save_dir=tune.get_trial_dir(), name="", version="."),
            progress_bar_refresh_rate=0,
            callbacks=[TuneReportCallback()])
    

    The version="." is actually a bit hacky, since PyTorch lightning tries to force us to use log_dir/version_name for tensorboard logs. By using "." we trick os.path.join in using the root directory.

    Lastly I'll look into the logging of perturbed parameters sometime later this or early next week.

    If there's something else, please let me know.

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

Metadata

Metadata

Assignees

Labels

questiontune

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions