class CometLogger(LightningLoggerBase): r""" Log using `Comet.ml <https://www.comet.ml>`_. Install it with pip: .. code-block:: bash pip install comet-ml Comet requires either an API Key (online mode) or a local directory path (offline mode). **ONLINE MODE** .. code-block:: python import os from pytorch_lightning import Trainer from pytorch_lightning.loggers import CometLogger # arguments made to CometLogger are passed on to the comet_ml.Experiment class comet_logger = CometLogger( api_key=os.environ.get('COMET_API_KEY'), workspace=os.environ.get('COMET_WORKSPACE'), # Optional save_dir='.', # Optional project_name='default_project', # Optional rest_api_key=os.environ.get('COMET_REST_API_KEY'), # Optional experiment_name='default' # Optional ) trainer = Trainer(logger=comet_logger) **OFFLINE MODE** .. code-block:: python from pytorch_lightning.loggers import CometLogger # arguments made to CometLogger are passed on to the comet_ml.Experiment class comet_logger = CometLogger( save_dir='.', workspace=os.environ.get('COMET_WORKSPACE'), # Optional project_name='default_project', # Optional rest_api_key=os.environ.get('COMET_REST_API_KEY'), # Optional experiment_name='default' # Optional ) trainer = Trainer(logger=comet_logger) Args: api_key: Required in online mode. API key, found on Comet.ml. If not given, this will be loaded from the environment variable COMET_API_KEY or ~/.comet.config if either exists. save_dir: Required in offline mode. The path for the directory to save local comet logs. If given, this also sets the directory for saving checkpoints. project_name: Optional. Send your experiment to a specific project. Otherwise will be sent to Uncategorized Experiments. If the project name does not already exist, Comet.ml will create a new project. rest_api_key: Optional. Rest API key found in Comet.ml settings. This is used to determine version number experiment_name: Optional. String representing the name for this particular experiment on Comet.ml. experiment_key: Optional. If set, restores from existing experiment. offline: If api_key and save_dir are both given, this determines whether the experiment will be in online or offline mode. This is useful if you use save_dir to control the checkpoints directory and have a ~/.comet.config file but still want to run offline experiments. \**kwargs: Additional arguments like `workspace`, `log_code`, etc. used by :class:`CometExperiment` can be passed as keyword arguments in this logger. """ def __init__(self, api_key: Optional[str] = None, save_dir: Optional[str] = None, project_name: Optional[str] = None, rest_api_key: Optional[str] = None, experiment_name: Optional[str] = None, experiment_key: Optional[str] = None, offline: bool = False, **kwargs): if comet_ml is None: raise ImportError( "You want to use `comet_ml` logger which is not installed yet," " install it with `pip install comet-ml`.") super().__init__() self._experiment = None # Determine online or offline mode based on which arguments were passed to CometLogger api_key = api_key or comet_ml.config.get_api_key( None, comet_ml.config.get_config()) if api_key is not None and save_dir is not None: self.mode = "offline" if offline else "online" self.api_key = api_key self._save_dir = save_dir elif api_key is not None: self.mode = "online" self.api_key = api_key self._save_dir = None elif save_dir is not None: self.mode = "offline" self._save_dir = save_dir else: # If neither api_key nor save_dir are passed as arguments, raise an exception raise MisconfigurationException( "CometLogger requires either api_key or save_dir during initialization." ) log.info(f"CometLogger will be initialized in {self.mode} mode") self._project_name = project_name self._experiment_key = experiment_key self._experiment_name = experiment_name self._kwargs = kwargs self._future_experiment_key = None if rest_api_key is not None: # Comet.ml rest API, used to determine version number self.rest_api_key = rest_api_key self.comet_api = API(self.rest_api_key) else: self.rest_api_key = None self.comet_api = None self._kwargs = kwargs @property @rank_zero_experiment def experiment(self): r""" Actual Comet object. To use Comet features in your :class:`~pytorch_lightning.core.lightning.LightningModule` do the following. Example:: self.logger.experiment.some_comet_function() """ if self._experiment is not None: return self._experiment if self._future_experiment_key is not None: os.environ["COMET_EXPERIMENT_KEY"] = self._future_experiment_key self._future_experiment_key = None try: if self.mode == "online": if self._experiment_key is None: self._experiment = CometExperiment( api_key=self.api_key, project_name=self._project_name, **self._kwargs, ) self._experiment_key = self._experiment.get_key() else: self._experiment = CometExistingExperiment( api_key=self.api_key, project_name=self._project_name, previous_experiment=self._experiment_key, **self._kwargs, ) else: self._experiment = CometOfflineExperiment( offline_directory=self.save_dir, project_name=self._project_name, **self._kwargs, ) finally: os.environ.pop("COMET_EXPERIMENT_KEY", None) if self._experiment_name: self._experiment.set_name(self._experiment_name) return self._experiment @rank_zero_only def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None: params = self._convert_params(params) params = self._flatten_dict(params) self.experiment.log_parameters(params) @rank_zero_only def log_metrics(self, metrics: Dict[str, Union[torch.Tensor, float]], step: Optional[int] = None) -> None: assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0" # Comet.ml expects metrics to be a dictionary of detached tensors on CPU for key, val in metrics.items(): if is_tensor(val): metrics[key] = val.cpu().detach() metrics_without_epoch = metrics.copy() epoch = metrics_without_epoch.pop('epoch', None) self.experiment.log_metrics(metrics_without_epoch, step=step, epoch=epoch) def reset_experiment(self): self._experiment = None @rank_zero_only def finalize(self, status: str) -> None: r""" When calling ``self.experiment.end()``, that experiment won't log any more data to Comet. That's why, if you need to log any more data, you need to create an ExistingCometExperiment. For example, to log data when testing your model after training, because when training is finalized :meth:`CometLogger.finalize` is called. This happens automatically in the :meth:`~CometLogger.experiment` property, when ``self._experiment`` is set to ``None``, i.e. ``self.reset_experiment()``. """ self.experiment.end() self.reset_experiment() @property def save_dir(self) -> Optional[str]: return self._save_dir @property def name(self) -> str: # Don't create an experiment if we don't have one if self._experiment is not None and self._experiment.project_name is not None: return self._experiment.project_name if self._project_name is not None: return self._project_name return "comet-default" @property def version(self) -> str: # Don't create an experiment if we don't have one if self._experiment is not None: return self._experiment.id if self._experiment_key is not None: return self._experiment_key if self._future_experiment_key is not None: return self._future_experiment_key # Pre-generate an experiment key self._future_experiment_key = comet_ml.generate_guid() return self._future_experiment_key def __getstate__(self): state = self.__dict__.copy() # Save the experiment id in case an experiment object already exists, # this way we could create an ExistingExperiment pointing to the same # experiment state[ "_experiment_key"] = self._experiment.id if self._experiment is not None else None # Remove the experiment object as it contains hard to pickle objects # (like network connections), the experiment object will be recreated if # needed later state["_experiment"] = None return state
class CometLogger(LightningLoggerBase): r""" Log using `Comet.ml <https://www.comet.ml>`_. Install it with pip: .. code-block:: bash pip install comet-ml Comet requires either an API Key (online mode) or a local directory path (offline mode). **ONLINE MODE** Example: >>> import os >>> from pytorch_lightning import Trainer >>> from pytorch_lightning.loggers import CometLogger >>> # arguments made to CometLogger are passed on to the comet_ml.Experiment class >>> comet_logger = CometLogger( ... api_key=os.environ.get('COMET_API_KEY'), ... workspace=os.environ.get('COMET_WORKSPACE'), # Optional ... save_dir='.', # Optional ... project_name='default_project', # Optional ... rest_api_key=os.environ.get('COMET_REST_API_KEY'), # Optional ... experiment_name='default' # Optional ... ) >>> trainer = Trainer(logger=comet_logger) **OFFLINE MODE** Example: >>> from pytorch_lightning.loggers import CometLogger >>> # arguments made to CometLogger are passed on to the comet_ml.Experiment class >>> comet_logger = CometLogger( ... save_dir='.', ... workspace=os.environ.get('COMET_WORKSPACE'), # Optional ... project_name='default_project', # Optional ... rest_api_key=os.environ.get('COMET_REST_API_KEY'), # Optional ... experiment_name='default' # Optional ... ) >>> trainer = Trainer(logger=comet_logger) Args: api_key: Required in online mode. API key, found on Comet.ml save_dir: Required in offline mode. The path for the directory to save local comet logs workspace: Optional. Name of workspace for this user project_name: Optional. Send your experiment to a specific project. Otherwise will be sent to Uncategorized Experiments. If the project name does not already exist, Comet.ml will create a new project. rest_api_key: Optional. Rest API key found in Comet.ml settings. This is used to determine version number experiment_name: Optional. String representing the name for this particular experiment on Comet.ml. experiment_key: Optional. If set, restores from existing experiment. """ def __init__(self, api_key: Optional[str] = None, save_dir: Optional[str] = None, workspace: Optional[str] = None, project_name: Optional[str] = None, rest_api_key: Optional[str] = None, experiment_name: Optional[str] = None, experiment_key: Optional[str] = None, **kwargs): if not _COMET_AVAILABLE: raise ImportError( 'You want to use `comet_ml` logger which is not installed yet,' ' install it with `pip install comet-ml`.') super().__init__() self._experiment = None # Determine online or offline mode based on which arguments were passed to CometLogger if api_key is not None: self.mode = "online" self.api_key = api_key elif save_dir is not None: self.mode = "offline" self.save_dir = save_dir else: # If neither api_key nor save_dir are passed as arguments, raise an exception raise MisconfigurationException( "CometLogger requires either api_key or save_dir during initialization." ) log.info(f"CometLogger will be initialized in {self.mode} mode") self.workspace = workspace self.project_name = project_name self.experiment_key = experiment_key self._kwargs = kwargs if rest_api_key is not None: # Comet.ml rest API, used to determine version number self.rest_api_key = rest_api_key self.comet_api = API(self.rest_api_key) else: self.rest_api_key = None self.comet_api = None if experiment_name: try: self.name = experiment_name except TypeError: log.exception( "Failed to set experiment name for comet.ml logger") self._kwargs = kwargs @property def experiment(self) -> CometBaseExperiment: r""" Actual Comet object. To use Comet features in your :class:`~pytorch_lightning.core.lightning.LightningModule` do the following. Example:: self.logger.experiment.some_comet_function() """ if self._experiment is not None: return self._experiment if self.mode == "online": if self.experiment_key is None: self._experiment = CometExperiment( api_key=self.api_key, workspace=self.workspace, project_name=self.project_name, **self._kwargs) self.experiment_key = self._experiment.get_key() else: self._experiment = CometExistingExperiment( api_key=self.api_key, workspace=self.workspace, project_name=self.project_name, previous_experiment=self.experiment_key, **self._kwargs) else: self._experiment = CometOfflineExperiment( offline_directory=self.save_dir, workspace=self.workspace, project_name=self.project_name, **self._kwargs) return self._experiment @rank_zero_only def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None: params = self._convert_params(params) params = self._flatten_dict(params) self.experiment.log_parameters(params) @rank_zero_only def log_metrics(self, metrics: Dict[str, Union[torch.Tensor, float]], step: Optional[int] = None) -> None: # Comet.ml expects metrics to be a dictionary of detached tensors on CPU for key, val in metrics.items(): if is_tensor(val): metrics[key] = val.cpu().detach() self.experiment.log_metrics(metrics, step=step) def reset_experiment(self): self._experiment = None @rank_zero_only def finalize(self, status: str) -> None: r""" When calling ``self.experiment.end()``, that experiment won't log any more data to Comet. That's why, if you need to log any more data, you need to create an ExistingCometExperiment. For example, to log data when testing your model after training, because when training is finalized :meth:`CometLogger.finalize` is called. This happens automatically in the :meth:`~CometLogger.experiment` property, when ``self._experiment`` is set to ``None``, i.e. ``self.reset_experiment()``. """ self.experiment.end() self.reset_experiment() @property def name(self) -> str: return str(self.experiment.project_name) @name.setter def name(self, value: str) -> None: self.experiment.set_name(value) @property def version(self) -> str: return self.experiment.id
logdir = join(home, 'ckpt/swissroll/' + args.sugg) os.makedirs(logdir, exist_ok=True) # comet experiment init if args.offline: experiment = OfflineExperiment(offline_directory=join(logdir, 'comet'), parse_args=False, project_name='swissroll-' + args.tag, workspace="wronnyhuang") else: experiment = Experiment(api_key="vPCPPZrcrUBitgoQkvzxdsh9k", parse_args=False, project_name='swissroll-' + args.tag, workspace="wronnyhuang") open(join(logdir, 'comet_expt_key.txt'), 'w+').write(experiment.get_key()) if any([a.find('nhidden1') != -1 for a in sys.argv[1:]]): args.nhidden = [ args.nhidden1, args.nhidden2, args.nhidden3, args.nhidden4, args.nhidden5, args.nhidden6 ] experiment.log_parameters(vars(args)) experiment.set_name(args.sugg) print(sys.argv) os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu) np.random.seed(args.seed) tf.set_random_seed(args.seed) # make dataset X, y = twospirals(args.ndata // 2, noise=args.noise)
class CometLogger(LightningLoggerBase): r""" Log using `comet.ml <https://www.comet.ml>`_. """ def __init__(self, api_key: Optional[str] = None, save_dir: Optional[str] = None, workspace: Optional[str] = None, project_name: Optional[str] = None, rest_api_key: Optional[str] = None, experiment_name: Optional[str] = None, experiment_key: Optional[str] = None, **kwargs): r""" Requires either an API Key (online mode) or a local directory path (offline mode) .. code-block:: python # ONLINE MODE from pytorch_lightning.loggers import CometLogger # arguments made to CometLogger are passed on to the comet_ml.Experiment class comet_logger = CometLogger( api_key=os.environ["COMET_API_KEY"], workspace=os.environ["COMET_WORKSPACE"], # Optional project_name="default_project", # Optional rest_api_key=os.environ["COMET_REST_API_KEY"], # Optional experiment_name="default" # Optional ) trainer = Trainer(logger=comet_logger) .. code-block:: python # OFFLINE MODE from pytorch_lightning.loggers import CometLogger # arguments made to CometLogger are passed on to the comet_ml.Experiment class comet_logger = CometLogger( save_dir=".", workspace=os.environ["COMET_WORKSPACE"], # Optional project_name="default_project", # Optional rest_api_key=os.environ["COMET_REST_API_KEY"], # Optional experiment_name="default" # Optional ) trainer = Trainer(logger=comet_logger) Args: api_key (str): Required in online mode. API key, found on Comet.ml save_dir (str): Required in offline mode. The path for the directory to save local comet logs workspace (str): Optional. Name of workspace for this user project_name (str): Optional. Send your experiment to a specific project. Otherwise will be sent to Uncategorized Experiments. If project name does not already exists Comet.ml will create a new project. rest_api_key (str): Optional. Rest API key found in Comet.ml settings. This is used to determine version number experiment_name (str): Optional. String representing the name for this particular experiment on Comet.ml. experiment_key (str): Optional. If set, restores from existing experiment. """ super().__init__() self._experiment = None # Determine online or offline mode based on which arguments were passed to CometLogger if api_key is not None: self.mode = "online" self.api_key = api_key elif save_dir is not None: self.mode = "offline" self.save_dir = save_dir else: # If neither api_key nor save_dir are passed as arguments, raise an exception raise MisconfigurationException( "CometLogger requires either api_key or save_dir during initialization." ) logger.info(f"CometLogger will be initialized in {self.mode} mode") self.workspace = workspace self.project_name = project_name self.experiment_key = experiment_key self._kwargs = kwargs if rest_api_key is not None: # Comet.ml rest API, used to determine version number self.rest_api_key = rest_api_key self.comet_api = API(self.rest_api_key) else: self.rest_api_key = None self.comet_api = None if experiment_name: try: self.name = experiment_name except TypeError as e: logger.exception( "Failed to set experiment name for comet.ml logger") @property def experiment(self) -> CometBaseExperiment: r""" Actual comet object. To use comet features do the following. Example:: self.logger.experiment.some_comet_function() """ if self._experiment is not None: return self._experiment if self.mode == "online": if self.experiment_key is None: self._experiment = CometExperiment( api_key=self.api_key, workspace=self.workspace, project_name=self.project_name, **self._kwargs) self.experiment_key = self._experiment.get_key() else: self._experiment = CometExistingExperiment( api_key=self.api_key, workspace=self.workspace, project_name=self.project_name, previous_experiment=self.experiment_key, **self._kwargs) else: self._experiment = CometOfflineExperiment( offline_directory=self.save_dir, workspace=self.workspace, project_name=self.project_name, **self._kwargs) return self._experiment @rank_zero_only def log_hyperparams(self, params: argparse.Namespace): self.experiment.log_parameters(vars(params)) @rank_zero_only def log_metrics(self, metrics: Dict[str, Union[torch.Tensor, float]], step: Optional[int] = None): # Comet.ml expects metrics to be a dictionary of detached tensors on CPU for key, val in metrics.items(): if is_tensor(val): metrics[key] = val.cpu().detach() self.experiment.log_metrics(metrics, step=step) def reset_experiment(self): self._experiment = None @rank_zero_only def finalize(self, status: str): r""" When calling self.experiment.end(), that experiment won't log any more data to Comet. That's why, if you need to log any more data you need to create an ExistingCometExperiment. For example, to log data when testing your model after training, because when training is finalized CometLogger.finalize is called. This happens automatically in the CometLogger.experiment property, when self._experiment is set to None i.e. self.reset_experiment(). """ self.experiment.end() self.reset_experiment() @property def name(self) -> str: return self.experiment.project_name @name.setter def name(self, value: str): self.experiment.set_name(value) @property def version(self) -> str: return self.experiment.id
class CometLogger(Logger): def __init__( self, batch_size: int, snapshot_dir: Optional[str] = None, snapshot_mode: str = "last", snapshot_gap: int = 1, exp_set: Optional[str] = None, use_print_exp: bool = False, saved_exp: Optional[str] = None, **kwargs, ): """ :param kwargs: passed to comet's Experiment at init. """ if use_print_exp: self.experiment = PrintExperiment() else: from comet_ml import Experiment, ExistingExperiment, OfflineExperiment if saved_exp: self.experiment = ExistingExperiment( previous_experiment=saved_exp, **kwargs ) else: try: self.experiment = Experiment(**kwargs) except ValueError: # no API key log_dir = Path.home() / "logs" log_dir.mkdir(exist_ok=True) self.experiment = OfflineExperiment(offline_directory=str(log_dir)) self.experiment.log_parameter("complete", False) if exp_set: self.experiment.log_parameter("exp_set", exp_set) if snapshot_dir: snapshot_dir = Path(snapshot_dir) / self.experiment.get_key() # log_traj_window (int): How many trajectories to hold in deque for computing performance statistics. self.log_traj_window = 100 self._cum_metrics = { "n_unsafe_actions": 0, "constraint_used": 0, "cum_completed_trajs": 0, "logging_time": 0, } self._new_completed_trajs = 0 self._last_step = 0 self._start_time = self._last_time = time() self._last_snapshot_upload = 0 self._snaphot_upload_time = 30 * 60 super().__init__(batch_size, snapshot_dir, snapshot_mode, snapshot_gap) def log_fast( self, step: int, traj_infos: Sequence[Dict[str, float]], opt_info: Optional[Tuple[Sequence[float], ...]] = None, test: bool = False, ) -> None: if not traj_infos: return start = time() self._new_completed_trajs += len(traj_infos) self._cum_metrics["cum_completed_trajs"] += len(traj_infos) # TODO: do we need to support sum(t[k]) if key in k? # without that, this doesn't include anything from extra eval samplers for key in self._cum_metrics: if key == "cum_completed_trajs": continue self._cum_metrics[key] += sum(t.get(key, 0) for t in traj_infos) self._cum_metrics["logging_time"] += time() - start def log( self, step: int, traj_infos: Sequence[Dict[str, float]], opt_info: Optional[Tuple[Sequence[float], ...]] = None, test: bool = False, ): self.log_fast(step, traj_infos, opt_info, test) start = time() with (self.experiment.test() if test else nullcontext()): step *= self.batch_size if opt_info is not None: # grad norm is left on the GPU for some reason # https://github.com/astooke/rlpyt/issues/163 self.experiment.log_metrics( { k: np.mean(v) for k, v in opt_info._asdict().items() if k != "gradNorm" }, step=step, ) if traj_infos: agg_vals = {} for key in traj_infos[0].keys(): if key in self._cum_metrics: continue agg_vals[key] = sum(t[key] for t in traj_infos) / len(traj_infos) self.experiment.log_metrics(agg_vals, step=step) if not test: now = time() self.experiment.log_metrics( { "new_completed_trajs": self._new_completed_trajs, "steps_per_second": (step - self._last_step) / (now - self._last_time), }, step=step, ) self._last_time = now self._last_step = step self._new_completed_trajs = 0 self.experiment.log_metrics(self._cum_metrics, step=step) self._cum_metrics["logging_time"] += time() - start def log_metric(self, name, val): self.experiment.log_metric(name, val) def log_parameters(self, parameters): self.experiment.log_parameters(parameters) def log_config(self, config): self.experiment.log_parameter("config", json.dumps(convert_dict(config))) def upload_snapshot(self): if self.snapshot_dir: self.experiment.log_asset(self._previous_snapshot_fname) def save_itr_params( self, step: int, params: Dict[str, Any], metric: Optional[float] = None ) -> None: super().save_itr_params(step, params, metric) now = time() if now - self._last_snapshot_upload > self._snaphot_upload_time: self._last_snapshot_upload = now self.upload_snapshot() def shutdown(self, error: bool = False) -> None: if not error: self.upload_snapshot() self.experiment.log_parameter("complete", True) self.experiment.end()
metrics.append(FinalTargetAccuracy(ignore_index=pad, eos_id=tgt.eos_id)) if 'sym_rwr_acc' in opt.metrics: metrics.append( SymbolRewritingAccuracy(input_vocab=input_vocab, output_vocab=output_vocab, use_output_eos=use_output_eos, output_sos_symbol=tgt.SYM_SOS, output_pad_symbol=tgt.pad_token, output_eos_symbol=tgt.SYM_EOS, output_unk_symbol=tgt.unk_token)) checkpoint_path = os.path.join(opt.output_dir, opt.load_checkpoint) if opt.resume else None # create trainer expt_dir = os.path.join(opt.output_dir, experiment.get_key()) t = SupervisedTrainer(expt_dir=expt_dir) seq2seq, logs = t.train(model=seq2seq, data=train, dev_data=dev, monitor_data=monitor_data, num_epochs=opt.epochs, optimizer=opt.optim, teacher_forcing_ratio=opt.teacher_forcing_ratio, learning_rate=opt.lr, resume_training=opt.resume, checkpoint_path=checkpoint_path, losses=losses, metrics=metrics, loss_weights=loss_weights,