index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,141 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/environments/kubeflow.py | 36,39 | 25,79 | creates_processes_externally | KubeflowEnvironment | 39,41 | 39,41 | class KubeflowEnvironment(ClusterEnvironment):
"""Environment for distributed training using the `PyTorchJob`_ operator from `Kubeflow`_.
This environment, unlike others, does not get auto-detected and needs to be passed to the Fabric/Trainer
constructor manually.
.. _PyTorchJob: https://www.kubeflow.... | class KubeflowEnvironment(ClusterEnvironment):
"""Environment for distributed training using the `PyTorchJob`_ operator from `Kubeflow`_.
This environment, unlike others, does not get auto-detected and needs to be passed to the Fabric/Trainer
constructor manually.
.. _PyTorchJob: https://www.kubeflow.... | return True
| return True
| 2 | 512 | 7 | 519 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,142 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/environments/lightning.py | 108,109 | 1,120 | find_free_network_port | 115,120 | 109,120 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
port = s.getsockname()[1]
s.close()
return port
| """Finds a free port on localhost.
It is useful in single-node training when we don't want to connect to a real main node but have to set the
`MASTER_PORT` environment variable.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
port = s.getsockname()[1]
s.close(... | 12 | 1,108 | 63 | 1,171 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,143 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/environments/lightning.py | 76,78 | 24,108 | world_size | LightningEnvironment | 78,80 | 78,80 | class LightningEnvironment(ClusterEnvironment):
"""The default environment used by Lightning for a single node or free cluster (not managed).
There are two modes the Lightning environment can operate with:
1. The user only launches the main process by :code:`python train.py ...` with no additional enviro... | class LightningEnvironment(ClusterEnvironment):
"""The default environment used by Lightning for a single node or free cluster (not managed).
There are two modes the Lightning environment can operate with:
1. The user only launches the main process by :code:`python train.py ...` with no additional enviro... | return self._world_size
| return self._world_size
| 2 | 822 | 11 | 833 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,145 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/environments/torchelastic.py | 54,57 | 27,94 | detect | TorchElasticEnvironment | 58,61 | 57,61 | class TorchElasticEnvironment(ClusterEnvironment):
"""Environment for fault-tolerant and elastic training with `torchelastic <https://pytorch.org/elastic/>`_"""
@property
@override
def creates_processes_externally(self) -> bool:
return True
@property
@override
def main_address(self... | class TorchElasticEnvironment(ClusterEnvironment):
"""Environment for fault-tolerant and elastic training with `torchelastic <https://pytorch.org/elastic/>`_"""
@property
@override
def creates_processes_externally(self) -> bool:
return True
@property
@override
def main_address(self... | # if not available (for example on MacOS), `is_torchelastic_launched` is not defined
return torch.distributed.is_available() and torch.distributed.is_torchelastic_launched()
| """Returns ``True`` if the current process was launched using the torchelastic command."""
# if not available (for example on MacOS), `is_torchelastic_launched` is not defined
return torch.distributed.is_available() and torch.distributed.is_torchelastic_launched()
| 16 | 774 | 63 | 837 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,146 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/io/torch_io.py | 36,38 | 28,97 | save_checkpoint | TorchCheckpointIO | 50,60 | 38,60 | class TorchCheckpointIO(CheckpointIO):
"""CheckpointIO that utilizes :func:`torch.save` and :func:`torch.load` to save and load checkpoints respectively,
common for most use cases.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
"""
@override
def save_check... | class TorchCheckpointIO(CheckpointIO):
"""CheckpointIO that utilizes :func:`torch.save` and :func:`torch.load` to save and load checkpoints respectively,
common for most use cases.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
"""
@override
def save_check... | if storage_options is not None:
raise TypeError(
"`Trainer.save_checkpoint(..., storage_options=...)` with `storage_options` arg"
f" is not supported for `{self.__class__.__name__}`. Please implement your custom `CheckpointIO`"
" to define how you'd li... | """Save model/training states as a checkpoint file through state-dump and file-write.
Args:
checkpoint: dict containing model and trainer state
path: write-target path
storage_options: not used in ``TorchCheckpointIO.save_checkpoint``
Raises:
Typ... | 40 | 597 | 153 | 750 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,147 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/amp.py | 114,115 | 1,123 | _optimizer_handles_unscaling | 122,123 | 115,123 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | return getattr(optimizer, "_step_supports_amp_scaling", False)
| """Determines whether a PyTorch optimizer handles unscaling gradients in the step method rather than through the
:class:`torch.cuda.amp.GradScaler`.
Since, the current implementation of this function checks a PyTorch internal variable on the optimizer, the return
value will only be reliable for built-i... | 4 | 1,497 | 23 | 1,520 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,148 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/amp.py | 78,84 | 28,114 | optimizer_step | MixedPrecision | 84,94 | 84,94 | class MixedPrecision(Precision):
"""Plugin for Automatic Mixed Precision (AMP) training with ``torch.autocast``.
Args:
precision: Whether to use ``torch.float16`` (``'16-mixed'``) or ``torch.bfloat16`` (``'bf16-mixed'``).
device: The device for ``torch.autocast``.
scaler: An optional :c... | class MixedPrecision(Precision):
"""Plugin for Automatic Mixed Precision (AMP) training with ``torch.autocast``.
Args:
precision: Whether to use ``torch.float16`` (``'16-mixed'``) or ``torch.bfloat16`` (``'bf16-mixed'``).
device: The device for ``torch.autocast``.
scaler: An optional :c... | if self.scaler is None:
# skip scaler logic, as bfloat16 does not require scaler
return super().optimizer_step(optimizer, **kwargs)
if isinstance(optimizer, LBFGS):
raise TypeError("AMP and the LBFGS optimizer are not compatible.")
# note: the scaler will skip... | if self.scaler is None:
# skip scaler logic, as bfloat16 does not require scaler
return super().optimizer_step(optimizer, **kwargs)
if isinstance(optimizer, LBFGS):
raise TypeError("AMP and the LBFGS optimizer are not compatible.")
# note: the scaler will skip... | 52 | 959 | 154 | 1,113 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,149 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/deepspeed.py | 70,72 | 33,101 | tensor_init_context | DeepSpeedPrecision | 72,76 | 72,76 | class DeepSpeedPrecision(Precision):
"""Precision plugin for DeepSpeed integration.
Args:
precision: Full precision (32-true), half precision (16-true, bf16-true) or
mixed precision (16-mixed, bf16-mixed).
Raises:
ValueError:
If unsupported ``precision`` is provided... | class DeepSpeedPrecision(Precision):
"""Precision plugin for DeepSpeed integration.
Args:
precision: Full precision (32-true), half precision (16-true, bf16-true) or
mixed precision (16-mixed, bf16-mixed).
Raises:
ValueError:
If unsupported ``precision`` is provided... | if "true" not in self.precision:
return nullcontext()
return _DtypeContextManager(self._desired_dtype)
| if "true" not in self.precision:
return nullcontext()
return _DtypeContextManager(self._desired_dtype)
| 9 | 714 | 41 | 755 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,150 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/double.py | 43,45 | 26,54 | forward_context | DoublePrecision | 45,47 | 45,47 | class DoublePrecision(Precision):
"""Plugin for training with double (``torch.float64``) precision."""
precision: Literal["64-true"] = "64-true"
@override
def convert_module(self, module: Module) -> Module:
return module.double()
@override
def tensor_init_context(self) -> ContextManag... | class DoublePrecision(Precision):
"""Plugin for training with double (``torch.float64``) precision."""
precision: Literal["64-true"] = "64-true"
@override
def convert_module(self, module: Module) -> Module:
return module.double()
@override
def tensor_init_context(self) -> ContextManag... | return self.tensor_init_context()
| return self.tensor_init_context()
| 2 | 300 | 14 | 314 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,151 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/fsdp.py | 76,78 | 35,162 | mixed_precision_config | FSDPPrecision | 78,102 | 78,102 | class FSDPPrecision(Precision):
"""Precision plugin for training with Fully Sharded Data Parallel (FSDP).
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Args:
precision: Full precision (32-true), half precision (16-true, bf16-true) or
mixed precisio... | class FSDPPrecision(Precision):
"""Precision plugin for training with Fully Sharded Data Parallel (FSDP).
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Args:
precision: Full precision (32-true), half precision (16-true, bf16-true) or
mixed precisio... | from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision as TorchMixedPrecision
if self.precision == "16-mixed":
param_dtype = torch.float32
reduce_dtype = buffer_dtype = torch.float16
elif self.precision == "bf16-mixed":
param_dtype = to... | from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision as TorchMixedPrecision
if self.precision == "16-mixed":
param_dtype = torch.float32
reduce_dtype = buffer_dtype = torch.float16
elif self.precision == "bf16-mixed":
param_dtype = to... | 80 | 1,321 | 355 | 1,676 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,152 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/half.py | 60,62 | 26,63 | convert_output | HalfPrecision | 62,63 | 62,63 | class HalfPrecision(Precision):
"""Plugin for training with half precision.
Args:
precision: Whether to use ``torch.float16`` (``'16-true'``) or ``torch.bfloat16`` (``'bf16-true'``).
"""
precision: Literal["bf16-true", "16-true"] = "16-true"
def __init__(self, precision: Literal["bf16-tr... | class HalfPrecision(Precision):
"""Plugin for training with half precision.
Args:
precision: Whether to use ``torch.float16`` (``'16-true'``) or ``torch.bfloat16`` (``'bf16-true'``).
"""
precision: Literal["bf16-true", "16-true"] = "16-true"
def __init__(self, precision: Literal["bf16-tr... | return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype())
| return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype())
| 5 | 430 | 42 | 472 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,153 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/precision.py | 56,57 | 39,163 | tensor_init_context | Precision | 58,60 | 57,60 | class Precision:
"""Base class for all plugins handling the precision-specific parts of the training.
The class attribute precision must be overwritten in child classes. The default value reflects fp32 training.
"""
precision: _PRECISION_INPUT_STR = "32-true"
def convert_module(self, module: Mod... | class Precision:
"""Base class for all plugins handling the precision-specific parts of the training.
The class attribute precision must be overwritten in child classes. The default value reflects fp32 training.
"""
precision: _PRECISION_INPUT_STR = "32-true"
def convert_module(self, module: Mod... | return nullcontext()
| """Controls how tensors get created (device, dtype)."""
return nullcontext()
| 2 | 1,061 | 9 | 1,070 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,154 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/plugins/precision/utils.py | 20,21 | 1,65 | _convert_fp_tensor | 21,25 | 21,25 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | return tensor.to(dst_type) if torch.is_floating_point(tensor) else tensor
# do not support using as a decorator or else `torch.get_default_dtype` will get picked up at initialization
| return tensor.to(dst_type) if torch.is_floating_point(tensor) else tensor
# do not support using as a decorator or else `torch.get_default_dtype` will get picked up at initialization
| 23 | 714 | 62 | 776 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,156 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/ddp.py | 226,228 | 225,240 | no_backward_sync | _DDPBackwardSyncControl | 230,240 | 228,240 | class _DDPBackwardSyncControl(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> ContextManager:
FILL_FUNC_BODY | class _DDPBackwardSyncControl(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> ContextManager:
"""Blocks gradient synchronization inside the :class:`~torch.nn.parallel.distributed.DistributedDataParallel`
wrapper."""
FILL_FUNC_BODY | if not enabled:
return nullcontext()
if not isinstance(module, DistributedDataParallel):
raise TypeError(
"Blocking backward sync is only possible if the module passed to"
f" `{self.__class__.__name__}.no_backward_sync` is wrapped in `DistributedD... | """Blocks gradient synchronization inside the :class:`~torch.nn.parallel.distributed.DistributedDataParallel`
wrapper."""
if not enabled:
return nullcontext()
if not isinstance(module, DistributedDataParallel):
raise TypeError(
"Blocking backward ... | 34 | 90 | 120 | 210 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,157 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/dp.py | 97,99 | 31,115 | get_module_state_dict | DataParallelStrategy | 99,103 | 99,103 | class DataParallelStrategy(ParallelStrategy):
"""Implements data-parallel training in a single process, i.e., the model gets replicated to each device and each
gets a split of the data."""
def __init__(
self,
accelerator: Optional[Accelerator] = None,
parallel_devices: Optional[List... | class DataParallelStrategy(ParallelStrategy):
"""Implements data-parallel training in a single process, i.e., the model gets replicated to each device and each
gets a split of the data."""
def __init__(
self,
accelerator: Optional[Accelerator] = None,
parallel_devices: Optional[List... | if isinstance(module, DataParallel):
module = module.module
return super().get_module_state_dict(module)
| if isinstance(module, DataParallel):
module = module.module
return super().get_module_state_dict(module)
| 8 | 846 | 39 | 885 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,160 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/fsdp.py | 746,748 | 745,764 | no_backward_sync | _FSDPBackwardSyncControl | 750,764 | 748,764 | class _FSDPBackwardSyncControl(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> ContextManager:
FILL_FUNC_BODY | class _FSDPBackwardSyncControl(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> ContextManager:
"""Blocks gradient synchronization inside the :class:`~torch.distributed.fsdp.FullyShardedDataParallel`
wrapper."""
FILL_FUNC_BODY | if not enabled:
return nullcontext()
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel
if not isinstance(module, FullyShardedDataParallel):
# the root must be wrapped
raise TypeError(
"Blocking backward sy... | """Blocks gradient synchronization inside the :class:`~torch.distributed.fsdp.FullyShardedDataParallel`
wrapper."""
if not enabled:
return nullcontext()
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel
if not isinstance(module, ... | 44 | 92 | 166 | 258 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,162 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/launchers/multiprocessing.py | 172,174 | 148,191 | capture | _GlobalStateSnapshot | 175,182 | 174,182 | @dataclass
class _GlobalStateSnapshot:
"""Captures a hand-selected set of (global) variables in modules and provides a way to restore them.
It facilitates and encapsulates the transfer of globals like PyTorch's deterministic flags or random generator state
across process boundaries when launching processes... | @dataclass
class _GlobalStateSnapshot:
"""Captures a hand-selected set of (global) variables in modules and provides a way to restore them.
It facilitates and encapsulates the transfer of globals like PyTorch's deterministic flags or random generator state
across process boundaries when launching processes... | return cls(
use_deterministic_algorithms=torch.are_deterministic_algorithms_enabled(),
use_deterministic_algorithms_warn_only=torch.is_deterministic_algorithms_warn_only_enabled(),
cudnn_benchmark=torch.backends.cudnn.benchmark,
rng_states=_collect_rng_states(),
... | """Capture a few global states from torch, numpy, etc., that we want to restore in a spawned worker process."""
return cls(
use_deterministic_algorithms=torch.are_deterministic_algorithms_enabled(),
use_deterministic_algorithms_warn_only=torch.is_deterministic_algorithms_warn_onl... | 7 | 381 | 112 | 493 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,163 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/launchers/multiprocessing.py | 84,86 | 39,148 | launch | _MultiProcessingLauncher | 97,125 | 86,125 | class _MultiProcessingLauncher(_Launcher):
r"""Launches processes that run a given function in parallel, and joins them all at the end.
The main process in which this launcher is invoked creates N so-called worker processes (using
:func:`torch.multiprocessing.start_processes`) that run the given function.
... | class _MultiProcessingLauncher(_Launcher):
r"""Launches processes that run a given function in parallel, and joins them all at the end.
The main process in which this launcher is invoked creates N so-called worker processes (using
:func:`torch.multiprocessing.start_processes`) that run the given function.
... | if self._start_method in ("fork", "forkserver"):
_check_bad_cuda_fork()
if self._start_method == "spawn":
_check_missing_main_guard()
# The default cluster environment in Lightning chooses a random free port number
# This needs to be done in the main process here... | """Launches processes that run the given function in parallel.
The function is allowed to have a return value. However, when all processes join, only the return value
of worker process 0 gets returned from this `launch` method in the main process.
Arguments:
function: The e... | 92 | 998 | 344 | 1,342 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,165 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/model_parallel.py | 301,302 | 296,313 | _set_requires_grad_sync | _FSDPNoSync | 302,308 | 302,308 | class _FSDPNoSync(ContextManager):
def __init__(self, module: Module, enabled: bool) -> None:
self._module = module
self._enabled = enabled
def _set_requires_grad_sync(self, requires_grad_sync: bool) -> None:
FILL_FUNC_BODY def __enter__(self) -> None:
self._set_requires_grad_sync(no... | class _FSDPNoSync(ContextManager):
def __init__(self, module: Module, enabled: bool) -> None:
self._module = module
self._enabled = enabled
def _set_requires_grad_sync(self, requires_grad_sync: bool) -> None:
FILL_FUNC_BODY def __enter__(self) -> None:
self._set_requires_grad_sync(no... | from torch.distributed._composable.fsdp import FSDP
for mod in self._module.modules():
if isinstance(mod, FSDP):
mod.set_requires_gradient_sync(requires_grad_sync, recurse=False)
| from torch.distributed._composable.fsdp import FSDP
for mod in self._module.modules():
if isinstance(mod, FSDP):
mod.set_requires_gradient_sync(requires_grad_sync, recurse=False)
| 13 | 161 | 75 | 236 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,166 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/model_parallel.py | 290,292 | 289,296 | no_backward_sync | _ParallelBackwardSyncControl | 293,296 | 292,296 | class _ParallelBackwardSyncControl(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> ContextManager:
FILL_FUNC_BODY | class _ParallelBackwardSyncControl(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> ContextManager:
"""Blocks gradient synchronization inside the FSDP2 modules."""
FILL_FUNC_BODY | return _FSDPNoSync(module=module, enabled=enabled)
| """Blocks gradient synchronization inside the FSDP2 modules."""
return _FSDPNoSync(module=module, enabled=enabled)
| 3 | 71 | 23 | 94 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,167 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/parallel.py | 88,90 | 30,115 | reduce_boolean_decision | ParallelStrategy | 102,110 | 90,110 | class ParallelStrategy(Strategy, ABC):
"""Strategy for training with multiple processes in parallel."""
def __init__(
self,
accelerator: Optional[Accelerator] = None,
parallel_devices: Optional[List[torch.device]] = None,
cluster_environment: Optional[ClusterEnvironment] = None,... | class ParallelStrategy(Strategy, ABC):
"""Strategy for training with multiple processes in parallel."""
def __init__(
self,
accelerator: Optional[Accelerator] = None,
parallel_devices: Optional[List[torch.device]] = None,
cluster_environment: Optional[ClusterEnvironment] = None,... | decision = torch.tensor(int(decision), device=self.root_device)
decision = self.all_reduce(
decision,
reduce_op=ReduceOp.SUM, # type: ignore[arg-type]
)
decision = bool(decision == self.world_size) if all else bool(decision)
return decision
| """Reduces a boolean decision over distributed processes. By default is analagous to ``all`` from the standard
library, returning ``True`` only if all input decisions evaluate to ``True``. If ``all`` is set to ``False``,
it behaves like ``any`` instead.
Args:
decision: A sin... | 24 | 863 | 99 | 962 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,168 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/registry.py | 44,52 | 19,113 | register | _StrategyRegistry | 62,84 | 52,84 | class _StrategyRegistry(dict):
"""This class is a Registry that stores information about the Training Strategies.
The Strategies are mapped to strings. These strings are names that identify
a strategy, e.g., "deepspeed". It also returns Optional description and
parameters to initialize the Strategy, wh... | class _StrategyRegistry(dict):
"""This class is a Registry that stores information about the Training Strategies.
The Strategies are mapped to strings. These strings are names that identify
a strategy, e.g., "deepspeed". It also returns Optional description and
parameters to initialize the Strategy, wh... | if not (name is None or isinstance(name, str)):
raise TypeError(f"`name` must be a str, found {name}")
if name in self and not override:
raise ValueError(f"'{name}' is already present in the registry. HINT: Use `override=True`.")
data: Dict[str, Any] = {}
data["... | """Registers a strategy mapped to a name and with required metadata.
Args:
name : the name that identifies a strategy, e.g. "deepspeed_stage_3"
strategy : strategy class
description : strategy description
override : overrides the registered strategy, if T... | 77 | 674 | 220 | 894 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,169 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/strategies/single_device.py | 77,79 | 29,89 | all_gather | SingleDeviceStrategy | 80,82 | 79,82 | class SingleDeviceStrategy(Strategy):
"""Strategy that handles communication on a single device."""
def __init__(
self,
device: _DEVICE = "cpu",
accelerator: Accelerator | None = None,
checkpoint_io: CheckpointIO | None = None,
precision: Precision | None = None,
):
... | class SingleDeviceStrategy(Strategy):
"""Strategy that handles communication on a single device."""
def __init__(
self,
device: _DEVICE = "cpu",
accelerator: Accelerator | None = None,
checkpoint_io: CheckpointIO | None = None,
precision: Precision | None = None,
):
... | return tensor
| """Perform a ``all_gather`` on all processes."""
return tensor
| 2 | 555 | 7 | 562 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,172 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/apply_func.py | 71,72 | 1,130 | move_data_to_device | 88,106 | 72,106 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | if isinstance(device, str):
device = torch.device(device)
def batch_to(data: Any) -> Any:
kwargs = {}
# Don't issue non-blocking transfers to CPU
# Same with MPS due to a race condition bug: https://github.com/pytorch/pytorch/issues/83015
if isinstance(data, Tensor) and ... | """Transfers a collection of data to the given device. Any object that defines a method ``to(device)`` will be
moved and all other objects in the collection will be left untouched.
Args:
batch: A tensor or collection of tensors or anything that has a method ``.to(...)``.
See :func:`appl... | 74 | 1,177 | 254 | 1,431 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,173 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/consolidate_checkpoint.py | 13,14 | 1,80 | _parse_cli_args | 14,40 | 14,40 | import logging
from argparse import ArgumentParser, Namespace
from pathlib import Path
import torch
from lightning.fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3
from lightning.fabric.utilities.load import _METADATA_FILENAME, _load_distributed_checkpoint
_log = logging.getLogger(__name__)
def _parse_cli_... | import logging
from argparse import ArgumentParser, Namespace
from pathlib import Path
import torch
from lightning.fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3
from lightning.fabric.utilities.load import _METADATA_FILENAME, _load_distributed_checkpoint
_log = logging.getLogger(__name__)
def _parse_cli_... | parser = ArgumentParser(
description=(
"Converts a distributed/sharded checkpoint into a single file that can be loaded with `torch.load()`."
" Only supports FSDP sharded checkpoints at the moment."
),
)
parser.add_argument(
"checkpoint_folder",
type=s... | parser = ArgumentParser(
description=(
"Converts a distributed/sharded checkpoint into a single file that can be loaded with `torch.load()`."
" Only supports FSDP sharded checkpoints at the moment."
),
)
parser.add_argument(
"checkpoint_folder",
type=s... | 102 | 613 | 265 | 878 | import logging
from argparse import ArgumentParser, Namespace
from pathlib import Path
import torch
from lightning.fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3
from lightning.fabric.utilities.load import _METADATA_FILENAME, _load_distributed_checkpoint
_log = logging.getLogger(__name__)
def _parse_cli_... | import logging
from argparse import ArgumentParser, Namespace
from pathlib import Path
import torch
from lightning.fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3
from lightning.fabric.utilities.load import _METADATA_FILENAME, _load_distributed_checkpoint
_log = logging.getLogger(__name__)
def _parse_cli_... | |
1,174 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/device_dtype_mixin.py | 109,112 | 1,121 | _update_properties | 112,121 | 112,121 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | for module in root.modules():
if not isinstance(module, _DeviceDtypeModuleMixin):
continue
# cannot use `module.to()` because we don't actually want to move the model in case there are multiple
# devices types (such as partial meta parameters)
if device is not None:
... | for module in root.modules():
if not isinstance(module, _DeviceDtypeModuleMixin):
continue
# cannot use `module.to()` because we don't actually want to move the model in case there are multiple
# devices types (such as partial meta parameters)
if device is not None:
... | 51 | 1,208 | 110 | 1,318 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,175 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/device_dtype_mixin.py | 57,59 | 22,109 | cuda | _DeviceDtypeModuleMixin | 71,78 | 59,78 | class _DeviceDtypeModuleMixin(Module):
__jit_unused_properties__: List[str] = ["device", "dtype"]
def __init__(self) -> None:
super().__init__()
self._dtype: Union[str, torch.dtype] = torch.get_default_dtype()
self._device = torch.device("cpu")
@property
def dtype(self) -> Unio... | class _DeviceDtypeModuleMixin(Module):
__jit_unused_properties__: List[str] = ["device", "dtype"]
def __init__(self) -> None:
super().__init__()
self._dtype: Union[str, torch.dtype] = torch.get_default_dtype()
self._device = torch.device("cpu")
@property
def dtype(self) -> Unio... | if device is None:
device = torch.device("cuda", torch.cuda.current_device())
elif isinstance(device, int):
device = torch.device("cuda", index=device)
_update_properties(self, device=device)
return super().cuda(device=device)
| """Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers
different objects. So it should be called before constructing optimizer if the module will live on GPU while
being optimized.
Arguments:
device: If specified, all paramete... | 19 | 885 | 88 | 973 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,178 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/distributed.py | 342,343 | 307,347 | reset | _DatasetSamplerWrapper | 344,347 | 343,347 | class _DatasetSamplerWrapper(Dataset):
"""Dataset to create indexes from `Sampler` or `Iterable`"""
def __init__(self, sampler: Union[Sampler, Iterable]) -> None:
if not isinstance(sampler, Sized):
raise TypeError(
"You seem to have configured a sampler in your DataLoader wh... | class _DatasetSamplerWrapper(Dataset):
"""Dataset to create indexes from `Sampler` or `Iterable`"""
def __init__(self, sampler: Union[Sampler, Iterable]) -> None:
if not isinstance(sampler, Sized):
raise TypeError(
"You seem to have configured a sampler in your DataLoader wh... | self._sampler_list = list(self._sampler)
| """Reset the sampler list in order to get new sampling."""
self._sampler_list = list(self._sampler)
| 3 | 511 | 21 | 532 | import contextlib
import logging
import os
import time
from contextlib import nullcontext
from datetime import timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable, Iterator, List, Optional, Sized, Union
import torch
import torch.nn.functional as F
from lightning_utilities.core.imports im... | import contextlib
import logging
import os
import time
from contextlib import nullcontext
from datetime import timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable, Iterator, List, Optional, Sized, Union
import torch
import torch.nn.functional as F
from lightning_utilities.core.imports im... |
1,180 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/load.py | 188,190 | 173,201 | persistent_load | _LazyLoadingUnpickler | 190,201 | 190,201 | class _LazyLoadingUnpickler(pickle.Unpickler):
def __init__(self, file: IO, file_reader: torch.PyTorchFileReader) -> None:
super().__init__(file)
self.file_reader = file_reader
@override
def find_class(self, module: str, name: str) -> Any:
if module == "torch._utils" and name == "_r... | class _LazyLoadingUnpickler(pickle.Unpickler):
def __init__(self, file: IO, file_reader: torch.PyTorchFileReader) -> None:
super().__init__(file)
self.file_reader = file_reader
@override
def find_class(self, module: str, name: str) -> Any:
if module == "torch._utils" and name == "_r... | from torch.storage import TypedStorage
_, cls, _, _, _ = pid
with warnings.catch_warnings():
# The TypedStorage APIs have heavy deprecations in torch, suppress all these warnings for now
warnings.simplefilter("ignore")
storage = TypedStorage(dtype=cls().dtype... | from torch.storage import TypedStorage
_, cls, _, _, _ = pid
with warnings.catch_warnings():
# The TypedStorage APIs have heavy deprecations in torch, suppress all these warnings for now
warnings.simplefilter("ignore")
storage = TypedStorage(dtype=cls().dtype... | 38 | 287 | 112 | 399 | # Copyright 2023 MathInf GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this files from this repository except in compliance
# with the License reproduced below (also at
# http://www.apache.org/licenses/LICENSE-2.0).
#
# Unless required by applicable law or agreed to in writi... | # Copyright 2023 MathInf GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this files from this repository except in compliance
# with the License reproduced below (also at
# http://www.apache.org/licenses/LICENSE-2.0).
#
# Unless required by applicable law or agreed to in writi... |
1,181 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/load.py | 52,62 | 39,173 | rebuild_from_type_v2 | _NotYetLoadedTensor | 62,74 | 62,74 | class _NotYetLoadedTensor:
def __init__(
self,
metatensor: Tensor,
archiveinfo: "_LazyLoadingUnpickler",
storageinfo: tuple,
rebuild_args: tuple,
) -> None:
self.metatensor = metatensor
self.archiveinfo = archiveinfo
self.storageinfo = storageinfo
... | class _NotYetLoadedTensor:
def __init__(
self,
metatensor: Tensor,
archiveinfo: "_LazyLoadingUnpickler",
storageinfo: tuple,
rebuild_args: tuple,
) -> None:
self.metatensor = metatensor
self.archiveinfo = archiveinfo
self.storageinfo = storageinfo
... | ret = func(*args)
if isinstance(ret, _NotYetLoadedTensor):
old_lt = ret._load_tensor
def _load_tensor() -> Any:
t = old_lt()
return torch._tensor._rebuild_from_type_v2(lambda: t, new_type, (), state)
ret._load_tensor = _load_tensor #... | ret = func(*args)
if isinstance(ret, _NotYetLoadedTensor):
old_lt = ret._load_tensor
def _load_tensor() -> Any:
t = old_lt()
return torch._tensor._rebuild_from_type_v2(lambda: t, new_type, (), state)
ret._load_tensor = _load_tensor #... | 35 | 1,268 | 154 | 1,422 | # Copyright 2023 MathInf GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this files from this repository except in compliance
# with the License reproduced below (also at
# http://www.apache.org/licenses/LICENSE-2.0).
#
# Unless required by applicable law or agreed to in writi... | # Copyright 2023 MathInf GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this files from this repository except in compliance
# with the License reproduced below (also at
# http://www.apache.org/licenses/LICENSE-2.0).
#
# Unless required by applicable law or agreed to in writi... |
1,182 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/logger.py | 23,24 | 1,169 | _convert_params | 33,43 | 24,43 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # in case converting from namespace
if isinstance(params, Namespace):
params = vars(params)
if params is None:
params = {}
return params
| """Ensure parameters are a dict or convert to dict if necessary.
Args:
params: Target to be converted to a dictionary
Returns:
params as a dictionary
"""
# in case converting from namespace
if isinstance(params, Namespace):
params = vars(params)
if params is None:... | 21 | 1,685 | 58 | 1,743 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,183 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/optimizer.py | 31,32 | 1,35 | _optimizer_to_device | 33,35 | 32,35 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | for p, v in optimizer.state.items():
optimizer.state[p] = apply_to_collection(v, Tensor, move_data_to_device, device, allow_frozen=True)
| """Moves the state of a single optimizer to the device."""
for p, v in optimizer.state.items():
optimizer.state[p] = apply_to_collection(v, Tensor, move_data_to_device, device, allow_frozen=True)
| 12 | 357 | 55 | 412 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,184 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/rank_zero.py | 39,40 | 1,88 | _get_rank | 40,51 | 40,51 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # SLURM_PROCID can be set even if SLURM is not managing the multiprocessing,
# therefore LOCAL_RANK needs to be checked first
rank_keys = ("RANK", "LOCAL_RANK", "SLURM_PROCID", "JSM_NAMESPACE_RANK")
for key in rank_keys:
rank = os.environ.get(key)
if rank is not None:
return ... | # SLURM_PROCID can be set even if SLURM is not managing the multiprocessing,
# therefore LOCAL_RANK needs to be checked first
rank_keys = ("RANK", "LOCAL_RANK", "SLURM_PROCID", "JSM_NAMESPACE_RANK")
for key in rank_keys:
rank = os.environ.get(key)
if rank is not None:
return ... | 55 | 856 | 152 | 1,008 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,185 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/registry.py | 63,64 | 1,68 | _register_classes | 64,68 | 64,68 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | for _, member in getmembers(module, isclass):
if issubclass(member, parent) and is_overridden(method, member, parent):
register_fn = getattr(member, method)
register_fn(registry)
| for _, member in getmembers(module, isclass):
if issubclass(member, parent) and is_overridden(method, member, parent):
register_fn = getattr(member, method)
register_fn(registry)
| 18 | 707 | 64 | 771 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,186 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/seed.py | 19,20 | 1,127 | seed_everything | 20,65 | 20,65 | import logging
import os
import random
from random import getstate as python_get_rng_state
from random import setstate as python_set_rng_state
from typing import Any, Dict, Optional
import numpy as np
import torch
from lightning.fabric.utilities.rank_zero import _get_rank, rank_prefixed_message, rank_zero_only, rank_... | import logging
import os
import random
from random import getstate as python_get_rng_state
from random import setstate as python_set_rng_state
from typing import Any, Dict, Optional
import numpy as np
import torch
from lightning.fabric.utilities.rank_zero import _get_rank, rank_prefixed_message, rank_zero_only, rank_... | r"""Function that sets the seed for pseudo-random number generators in: torch, numpy, and Python's random module.
In addition, sets the following environment variables:
- ``PL_GLOBAL_SEED``: will be passed to spawned subprocesses (e.g. ddp_spawn backend).
- ``PL_SEED_WORKERS``: (optional) is set to 1 i... | r"""Function that sets the seed for pseudo-random number generators in: torch, numpy, and Python's random module.
In addition, sets the following environment variables:
- ``PL_GLOBAL_SEED``: will be passed to spawned subprocesses (e.g. ddp_spawn backend).
- ``PL_SEED_WORKERS``: (optional) is set to 1 i... | 204 | 1,217 | 645 | 1,862 | import logging
import os
import random
from random import getstate as python_get_rng_state
from random import setstate as python_set_rng_state
from typing import Any, Dict, Optional
import numpy as np
import torch
from lightning.fabric.utilities.rank_zero import _get_rank, rank_prefixed_message, rank_zero_only, rank_... | import logging
import os
import random
from random import getstate as python_get_rng_state
from random import setstate as python_set_rng_state
from typing import Any, Dict, Optional
import numpy as np
import torch
from lightning.fabric.utilities.rank_zero import _get_rank, rank_prefixed_message, rank_zero_only, rank_... | |
1,187 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/types.py | 69,69 | 65,72 | rank | CollectibleGroup | 69,70 | 69,70 | @runtime_checkable
class CollectibleGroup(Protocol):
def size(self) -> int: ...
FILL_FUNC_BODY
| @runtime_checkable
class CollectibleGroup(Protocol):
def size(self) -> int: ...
FILL_FUNC_BODY
| def rank(self) -> int: ...
| def rank(self) -> int: ...
| 5 | 39 | 13 | 52 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,188 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/types.py | 95,95 | 85,96 | load_state_dict | Optimizable | 95,96 | 95,96 | @runtime_checkable
class Optimizable(Steppable, Protocol):
"""To structurally type ``optimizer``"""
param_groups: List[Dict[Any, Any]]
defaults: Dict[Any, Any]
state: DefaultDict[Tensor, Any]
def state_dict(self) -> Dict[str, Dict[Any, Any]]: ...
FILL_FUNC_BODY | @runtime_checkable
class Optimizable(Steppable, Protocol):
"""To structurally type ``optimizer``"""
param_groups: List[Dict[Any, Any]]
defaults: Dict[Any, Any]
state: DefaultDict[Tensor, Any]
def state_dict(self) -> Dict[str, Dict[Any, Any]]: ...
FILL_FUNC_BODY | def load_state_dict(self, state_dict: Dict[str, Dict[Any, Any]]) -> None: ...
| def load_state_dict(self, state_dict: Dict[str, Dict[Any, Any]]) -> None: ...
| 9 | 108 | 34 | 142 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,189 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/types.py | 82,82 | 72,85 | step | Steppable | 82,83 | 82,83 | @runtime_checkable
class Steppable(Protocol):
"""To structurally type ``optimizer.step()``"""
@overload
def step(self, closure: None = ...) -> None: ...
@overload
def step(self, closure: Callable[[], float]) -> float: ...
FILL_FUNC_BODY
| @runtime_checkable
class Steppable(Protocol):
"""To structurally type ``optimizer.step()``"""
@overload
def step(self, closure: None = ...) -> None: ...
@overload
def step(self, closure: Callable[[], float]) -> float: ...
FILL_FUNC_BODY
| def step(self, closure: Optional[Callable[[], float]] = ...) -> Optional[float]: ...
| def step(self, closure: Optional[Callable[[], float]] = ...) -> Optional[float]: ...
| 10 | 93 | 28 | 121 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,190 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/types.py | 62,62 | 56,65 | load_state_dict | _Stateful | 62,63 | 62,63 | @runtime_checkable
class _Stateful(Protocol[_DictKey]):
"""This class is used to detect if an object is stateful using `isinstance(obj, _Stateful)`."""
def state_dict(self) -> Dict[_DictKey, Any]: ...
FILL_FUNC_BODY
| @runtime_checkable
class _Stateful(Protocol[_DictKey]):
"""This class is used to detect if an object is stateful using `isinstance(obj, _Stateful)`."""
def state_dict(self) -> Dict[_DictKey, Any]: ...
FILL_FUNC_BODY
| def load_state_dict(self, state_dict: Dict[_DictKey, Any]) -> None: ...
| def load_state_dict(self, state_dict: Dict[_DictKey, Any]) -> None: ...
| 8 | 84 | 31 | 115 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,191 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/fabric/utilities/warnings.py | 27,28 | 1,60 | disable_possible_user_warnings | 37,40 | 28,40 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | warnings.filterwarnings("ignore", module=module, category=PossibleUserWarning)
| """Ignore warnings of the category ``PossibleUserWarning`` from Lightning.
For more granular control over which warnings to ignore, use :func:`warnings.filterwarnings` directly.
Args:
module: Name of the module for which the warnings should be ignored (e.g., ``'lightning.pytorch.strategies'``).
... | 3 | 610 | 26 | 636 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,192 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/_graveyard/_torchmetrics.py | 10,11 | 1,21 | compare_version | 11,15 | 11,15 | from typing import Callable
import torchmetrics
from lightning_utilities.core.imports import compare_version as _compare_version
from lightning.pytorch.utilities.imports import _TORCHMETRICS_GREATER_EQUAL_0_8_0
from lightning.pytorch.utilities.migration.utils import _patch_pl_to_mirror_if_necessary
def compare_vers... | from typing import Callable
import torchmetrics
from lightning_utilities.core.imports import compare_version as _compare_version
from lightning.pytorch.utilities.imports import _TORCHMETRICS_GREATER_EQUAL_0_8_0
from lightning.pytorch.utilities.migration.utils import _patch_pl_to_mirror_if_necessary
def compare_vers... | new_package = _patch_pl_to_mirror_if_necessary(package)
return _compare_version(new_package, op, version, use_base_version)
| new_package = _patch_pl_to_mirror_if_necessary(package)
return _compare_version(new_package, op, version, use_base_version)
| 8 | 314 | 50 | 364 | from typing import Callable
import torchmetrics
from lightning_utilities.core.imports import compare_version as _compare_version
from lightning.pytorch.utilities.imports import _TORCHMETRICS_GREATER_EQUAL_0_8_0
from lightning.pytorch.utilities.migration.utils import _patch_pl_to_mirror_if_necessary
def compare_vers... | from typing import Callable
import torchmetrics
from lightning_utilities.core.imports import compare_version as _compare_version
from lightning.pytorch.utilities.imports import _TORCHMETRICS_GREATER_EQUAL_0_8_0
from lightning.pytorch.utilities.migration.utils import _patch_pl_to_mirror_if_necessary
def compare_vers... | |
1,193 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/_graveyard/hpu.py | 7,8 | 1,91 | _patch_sys_modules | 8,16 | 8,16 | import sys
from typing import Any
import lightning.pytorch as pl
def _patch_sys_modules() -> None:
FILL_FUNC_BODYclass HPUAccelerator:
auto_device_count = ...
get_parallel_devices = ...
is_available = ...
parse_devices = ...
setup_device = ...
teardown = ...
def __init__(self, *_: Any, *... | import sys
from typing import Any
import lightning.pytorch as pl
def _patch_sys_modules() -> None:
FILL_FUNC_BODYclass HPUAccelerator:
auto_device_count = ...
get_parallel_devices = ...
is_available = ...
parse_devices = ...
setup_device = ...
teardown = ...
def __init__(self, *_: Any, *... | self = sys.modules[__name__]
sys.modules["lightning.pytorch.accelerators.hpu"] = self
sys.modules["lightning.pytorch.strategies.hpu_parallel"] = self
sys.modules["lightning.pytorch.strategies.single_hpu"] = self
sys.modules["lightning.pytorch.plugins.io.hpu_plugin"] = self
sys.modules["lightning... | self = sys.modules[__name__]
sys.modules["lightning.pytorch.accelerators.hpu"] = self
sys.modules["lightning.pytorch.strategies.hpu_parallel"] = self
sys.modules["lightning.pytorch.strategies.single_hpu"] = self
sys.modules["lightning.pytorch.plugins.io.hpu_plugin"] = self
sys.modules["lightning... | 18 | 975 | 140 | 1,115 | import sys
from typing import Any
import lightning.pytorch as pl
def _patch_sys_modules() -> None:
FILL_FUNC_BODYclass HPUAccelerator:
auto_device_count = ...
get_parallel_devices = ...
is_available = ...
parse_devices = ...
setup_device = ...
teardown = ...
def __init__(self, *_: Any, *... | import sys
from typing import Any
import lightning.pytorch as pl
def _patch_sys_modules() -> None:
FILL_FUNC_BODYclass HPUAccelerator:
auto_device_count = ...
get_parallel_devices = ...
is_available = ...
parse_devices = ...
setup_device = ...
teardown = ...
def __init__(self, *_: Any, *... | |
1,194 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/_graveyard/hpu.py | 45,46 | 33,49 | get_device_stats | HPUParallelStrategy | 46,49 | 46,49 | class HPUParallelStrategy:
def __init__(self, *_: Any, **__: Any) -> None:
raise NotImplementedError(
"The `HPUParallelStrategy` class has been moved to an external package."
" Install the extension package as `pip install lightning-habana`"
" and import with `from lightn... | class HPUParallelStrategy:
def __init__(self, *_: Any, **__: Any) -> None:
raise NotImplementedError(
"The `HPUParallelStrategy` class has been moved to an external package."
" Install the extension package as `pip install lightning-habana`"
" and import with `from lightn... | raise NotImplementedError
| raise NotImplementedError
| 2 | 188 | 13 | 201 | import sys
from typing import Any
import lightning.pytorch as pl
def _patch_sys_modules() -> None:
self = sys.modules[__name__]
sys.modules["lightning.pytorch.accelerators.hpu"] = self
sys.modules["lightning.pytorch.strategies.hpu_parallel"] = self
sys.modules["lightning.pytorch.strategies.single_hpu... | import sys
from typing import Any
import lightning.pytorch as pl
def _patch_sys_modules() -> None:
self = sys.modules[__name__]
sys.modules["lightning.pytorch.accelerators.hpu"] = self
sys.modules["lightning.pytorch.strategies.hpu_parallel"] = self
sys.modules["lightning.pytorch.strategies.single_hpu... |
1,195 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/_graveyard/precision.py | 58,59 | 1,87 | _patch_classes | 59,85 | 59,85 | import sys
from typing import TYPE_CHECKING, Any, Literal, Optional
import lightning.pytorch as pl
from lightning.fabric.utilities.rank_zero import rank_zero_deprecation
from lightning.pytorch.plugins.precision import (
BitsandbytesPrecision,
DeepSpeedPrecision,
DoublePrecision,
FSDPPrecision,
Half... | import sys
from typing import TYPE_CHECKING, Any, Literal, Optional
import lightning.pytorch as pl
from lightning.fabric.utilities.rank_zero import rank_zero_deprecation
from lightning.pytorch.plugins.precision import (
BitsandbytesPrecision,
DeepSpeedPrecision,
DoublePrecision,
FSDPPrecision,
Half... | classes_map = (
# module name, old name, new class
("bitsandbytes", "BitsandbytesPrecisionPlugin", BitsandbytesPrecision),
("deepspeed", "DeepSpeedPrecisionPlugin", DeepSpeedPrecision),
("double", "DoublePrecisionPlugin", DoublePrecision),
("fsdp", "FSDPPrecisionPlugin", FSDP... | classes_map = (
# module name, old name, new class
("bitsandbytes", "BitsandbytesPrecisionPlugin", BitsandbytesPrecision),
("deepspeed", "DeepSpeedPrecisionPlugin", DeepSpeedPrecision),
("double", "DoublePrecisionPlugin", DoublePrecision),
("fsdp", "FSDPPrecisionPlugin", FSDP... | 81 | 635 | 458 | 1,093 | import sys
from typing import TYPE_CHECKING, Any, Literal, Optional
import lightning.pytorch as pl
from lightning.fabric.utilities.rank_zero import rank_zero_deprecation
from lightning.pytorch.plugins.precision import (
BitsandbytesPrecision,
DeepSpeedPrecision,
DoublePrecision,
FSDPPrecision,
Half... | import sys
from typing import TYPE_CHECKING, Any, Literal, Optional
import lightning.pytorch as pl
from lightning.fabric.utilities.rank_zero import rank_zero_deprecation
from lightning.pytorch.plugins.precision import (
BitsandbytesPrecision,
DeepSpeedPrecision,
DoublePrecision,
FSDPPrecision,
Half... | |
1,196 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/_graveyard/tpu.py | 111,112 | 1,126 | _patch_classes | 112,122 | 112,122 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | setattr(pl.strategies, "SingleTPUStrategy", SingleTPUStrategy)
setattr(pl.accelerators, "TPUAccelerator", TPUAccelerator)
setattr(pl.plugins, "TPUPrecisionPlugin", TPUPrecisionPlugin)
setattr(pl.plugins.precision, "TPUPrecisionPlugin", TPUPrecisionPlugin)
setattr(pl.plugins, "TPUBf16PrecisionPlugin"... | setattr(pl.strategies, "SingleTPUStrategy", SingleTPUStrategy)
setattr(pl.accelerators, "TPUAccelerator", TPUAccelerator)
setattr(pl.plugins, "TPUPrecisionPlugin", TPUPrecisionPlugin)
setattr(pl.plugins.precision, "TPUPrecisionPlugin", TPUPrecisionPlugin)
setattr(pl.plugins, "TPUBf16PrecisionPlugin"... | 24 | 1,330 | 236 | 1,566 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,197 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/_graveyard/tpu.py | 46,48 | 35,52 | register_strategies | SingleTPUStrategy | 48,52 | 48,52 | class SingleTPUStrategy(SingleDeviceXLAStrategy):
"""Legacy class.
Use :class:`~lightning.pytorch.strategies.single_xla.SingleDeviceXLAStrategy` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
rank_zero_deprecation("The 'single_tpu' strategy is deprecated. Use 'single_xla'... | class SingleTPUStrategy(SingleDeviceXLAStrategy):
"""Legacy class.
Use :class:`~lightning.pytorch.strategies.single_xla.SingleDeviceXLAStrategy` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
rank_zero_deprecation("The 'single_tpu' strategy is deprecated. Use 'single_xla'... | if "single_tpu" not in strategy_registry:
strategy_registry.register("single_tpu", cls, description="Legacy class. Use `single_xla` instead.")
| if "single_tpu" not in strategy_registry:
strategy_registry.register("single_tpu", cls, description="Legacy class. Use `single_xla` instead.")
| 12 | 169 | 55 | 224 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,198 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/accelerators/accelerator.py | 37,38 | 22,48 | get_device_stats | Accelerator | 47,48 | 38,48 | class Accelerator(_Accelerator, ABC):
"""The Accelerator base class for Lightning PyTorch.
.. warning:: Writing your own accelerator is an :ref:`experimental <versioning:Experimental API>` feature.
"""
def setup(self, trainer: "pl.Trainer") -> None:
"""Called by the Trainer to set up the acc... | class Accelerator(_Accelerator, ABC):
"""The Accelerator base class for Lightning PyTorch.
.. warning:: Writing your own accelerator is an :ref:`experimental <versioning:Experimental API>` feature.
"""
def setup(self, trainer: "pl.Trainer") -> None:
"""Called by the Trainer to set up the acc... | raise NotImplementedError
| """Get stats for a given device.
Args:
device: device for which to get stats
Returns:
Dictionary of device stats
"""
raise NotImplementedError
| 2 | 205 | 9 | 214 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,199 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/accelerators/cpu.py | 92,93 | 1,104 | get_cpu_stats | 93,104 | 93,104 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | if not _PSUTIL_AVAILABLE:
raise ModuleNotFoundError(
f"Fetching CPU device stats requires `psutil` to be installed. {str(_PSUTIL_AVAILABLE)}"
)
import psutil
return {
_CPU_VM_PERCENT: psutil.virtual_memory().percent,
_CPU_PERCENT: psutil.cpu_percent(),
_C... | if not _PSUTIL_AVAILABLE:
raise ModuleNotFoundError(
f"Fetching CPU device stats requires `psutil` to be installed. {str(_PSUTIL_AVAILABLE)}"
)
import psutil
return {
_CPU_VM_PERCENT: psutil.virtual_memory().percent,
_CPU_PERCENT: psutil.cpu_percent(),
_C... | 27 | 862 | 137 | 999 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,200 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/accelerators/cpu.py | 74,77 | 27,85 | register_accelerators | CPUAccelerator | 77,85 | 77,85 | class CPUAccelerator(Accelerator):
"""Accelerator for CPU devices."""
@override
def setup_device(self, device: torch.device) -> None:
"""
Raises:
MisconfigurationException:
If the selected device is not CPU.
"""
if device.type != "cpu":
... | class CPUAccelerator(Accelerator):
"""Accelerator for CPU devices."""
@override
def setup_device(self, device: torch.device) -> None:
"""
Raises:
MisconfigurationException:
If the selected device is not CPU.
"""
if device.type != "cpu":
... | accelerator_registry.register(
"cpu",
cls,
description=cls.__name__,
)
# CPU device metrics
| accelerator_registry.register(
"cpu",
cls,
description=cls.__name__,
)
# CPU device metrics
| 9 | 449 | 47 | 496 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,201 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/accelerators/cuda.py | 117,118 | 1,173 | get_nvidia_gpu_stats | 131,167 | 118,167 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | nvidia_smi_path = shutil.which("nvidia-smi")
if nvidia_smi_path is None:
raise FileNotFoundError("nvidia-smi: command not found")
gpu_stat_metrics = [
("utilization.gpu", "%"),
("memory.used", "MB"),
("memory.free", "MB"),
("utilization.memory", "%"),
("fan.s... | """Get GPU stats including memory, fan speed, and temperature from nvidia-smi.
Args:
device: GPU device for which to get stats
Returns:
A dictionary mapping the metrics to their values.
Raises:
FileNotFoundError:
If nvidia-smi installation not found
"""
nv... | 92 | 1,419 | 435 | 1,854 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,202 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/accelerators/cuda.py | 55,57 | 34,117 | set_nvidia_flags | CUDAAccelerator | 57,63 | 57,63 | class CUDAAccelerator(Accelerator):
"""Accelerator for NVIDIA CUDA devices."""
@override
def setup_device(self, device: torch.device) -> None:
"""
Raises:
MisconfigurationException:
If the selected device is not GPU.
"""
if device.type != "cuda":
... | class CUDAAccelerator(Accelerator):
"""Accelerator for NVIDIA CUDA devices."""
@override
def setup_device(self, device: torch.device) -> None:
"""
Raises:
MisconfigurationException:
If the selected device is not GPU.
"""
if device.type != "cuda":
... | # set the correct cuda visible devices (using pci order)
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
all_gpu_ids = ",".join(str(x) for x in range(num_cuda_devices()))
devices = os.getenv("CUDA_VISIBLE_DEVICES", all_gpu_ids)
_log.info(f"LOCAL_RANK: {local_rank} - CUDA_VISIBLE_D... | # set the correct cuda visible devices (using pci order)
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
all_gpu_ids = ",".join(str(x) for x in range(num_cuda_devices()))
devices = os.getenv("CUDA_VISIBLE_DEVICES", all_gpu_ids)
_log.info(f"LOCAL_RANK: {local_rank} - CUDA_VISIBLE_D... | 29 | 686 | 146 | 832 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,203 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/accelerators/mps.py | 97,98 | 1,109 | get_device_stats | 98,109 | 98,109 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | if not _PSUTIL_AVAILABLE:
raise ModuleNotFoundError(
f"Fetching MPS device stats requires `psutil` to be installed. {str(_PSUTIL_AVAILABLE)}"
)
import psutil
return {
_VM_PERCENT: psutil.virtual_memory().percent,
_PERCENT: psutil.cpu_percent(),
_SWAP_PERC... | if not _PSUTIL_AVAILABLE:
raise ModuleNotFoundError(
f"Fetching MPS device stats requires `psutil` to be installed. {str(_PSUTIL_AVAILABLE)}"
)
import psutil
return {
_VM_PERCENT: psutil.virtual_memory().percent,
_PERCENT: psutil.cpu_percent(),
_SWAP_PERC... | 27 | 976 | 132 | 1,108 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,204 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/accelerators/mps.py | 60,63 | 28,92 | get_parallel_devices | MPSAccelerator | 64,69 | 63,69 | class MPSAccelerator(Accelerator):
"""Accelerator for Metal Apple Silicon GPU devices.
.. warning:: Use of this accelerator beyond import and instantiation is experimental.
"""
@override
def setup_device(self, device: torch.device) -> None:
"""
Raises:
Misconfiguratio... | class MPSAccelerator(Accelerator):
"""Accelerator for Metal Apple Silicon GPU devices.
.. warning:: Use of this accelerator beyond import and instantiation is experimental.
"""
@override
def setup_device(self, device: torch.device) -> None:
"""
Raises:
Misconfiguratio... | parsed_devices = MPSAccelerator.parse_devices(devices)
assert parsed_devices is not None
return [torch.device("mps", i) for i in range(len(parsed_devices))]
| """Gets parallel devices for the Accelerator."""
parsed_devices = MPSAccelerator.parse_devices(devices)
assert parsed_devices is not None
return [torch.device("mps", i) for i in range(len(parsed_devices))]
| 15 | 533 | 61 | 594 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,207 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/device_stats_monitor.py | 161,162 | 1,163 | _prefix_metric_keys | 162,163 | 162,163 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | return {prefix + separator + k: v for k, v in metrics_dict.items()}
| return {prefix + separator + k: v for k, v in metrics_dict.items()}
| 12 | 1,717 | 25 | 1,742 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,208 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/device_stats_monitor.py | 60,67 | 33,161 | setup | DeviceStatsMonitor | 67,80 | 67,80 | class DeviceStatsMonitor(Callback):
r"""Automatically monitors and logs device stats during training, validation and testing stage.
``DeviceStatsMonitor`` is a special callback as it requires a ``logger`` to passed as argument to the ``Trainer``.
Args:
cpu_stats: if ``None``, it will log CPU stats ... | class DeviceStatsMonitor(Callback):
r"""Automatically monitors and logs device stats during training, validation and testing stage.
``DeviceStatsMonitor`` is a special callback as it requires a ``logger`` to passed as argument to the ``Trainer``.
Args:
cpu_stats: if ``None``, it will log CPU stats ... | if stage != "fit":
return
if not trainer.loggers:
raise MisconfigurationException("Cannot use `DeviceStatsMonitor` callback with `Trainer(logger=False)`.")
# warn in setup to warn once
device = trainer.strategy.root_device
if self._cpu_stats is None and ... | if stage != "fit":
return
if not trainer.loggers:
raise MisconfigurationException("Cannot use `DeviceStatsMonitor` callback with `Trainer(logger=False)`.")
# warn in setup to warn once
device = trainer.strategy.root_device
if self._cpu_stats is None and ... | 51 | 1,246 | 163 | 1,409 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,210 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/finetuning.py | 416,418 | 333,455 | finetune_function | BackboneFinetuning | 419,455 | 418,455 | class BackboneFinetuning(BaseFinetuning):
r"""Finetune a backbone model based on a learning rate user-defined scheduling.
When the backbone learning rate reaches the current model learning rate
and ``should_align`` is set to True, it will align with it for the rest of the training.
Args:
unfre... | class BackboneFinetuning(BaseFinetuning):
r"""Finetune a backbone model based on a learning rate user-defined scheduling.
When the backbone learning rate reaches the current model learning rate
and ``should_align`` is set to True, it will align with it for the rest of the training.
Args:
unfre... | if epoch == self.unfreeze_backbone_at_epoch:
current_lr = optimizer.param_groups[0]["lr"]
initial_backbone_lr = (
self.backbone_initial_lr
if self.backbone_initial_lr is not None
else current_lr * self.backbone_initial_ratio_lr
... | """Called when the epoch begins."""
if epoch == self.unfreeze_backbone_at_epoch:
current_lr = optimizer.param_groups[0]["lr"]
initial_backbone_lr = (
self.backbone_initial_lr
if self.backbone_initial_lr is not None
else current_lr *... | 90 | 1,128 | 538 | 1,666 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,212 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/gradient_accumulation_scheduler.py | 103,105 | 34,141 | on_train_start | GradientAccumulationScheduler | 106,138 | 105,138 | class GradientAccumulationScheduler(Callback):
r"""Change gradient accumulation factor according to scheduling.
Args:
scheduling: scheduling in format {epoch: accumulation_factor}
Note:
The argument scheduling is a dictionary. Each key represent an epoch and
its associated accumula... | class GradientAccumulationScheduler(Callback):
r"""Change gradient accumulation factor according to scheduling.
Args:
scheduling: scheduling in format {epoch: accumulation_factor}
Note:
The argument scheduling is a dictionary. Each key represent an epoch and
its associated accumula... |
if not pl_module.automatic_optimization:
raise RuntimeError(
"""Automatic gradient accumulation and the `GradientAccumulationScheduler` is not supported for
manual optimization. Please remove the callback or switch to automatic optimization."""
)
... | """Performns a configuration validation before training starts and raises errors for incompatible settings."""
if not pl_module.automatic_optimization:
raise RuntimeError(
"""Automatic gradient accumulation and the `GradientAccumulationScheduler` is not supported for
... | 131 | 925 | 501 | 1,426 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,213 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/lr_finder.py | 111,112 | 32,131 | lr_find | LearningRateFinder | 112,128 | 112,128 | class LearningRateFinder(Callback):
"""The ``LearningRateFinder`` callback enables the user to do a range test of good initial learning rates, to
reduce the amount of guesswork in picking a good starting learning rate.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
... | class LearningRateFinder(Callback):
"""The ``LearningRateFinder`` callback enables the user to do a range test of good initial learning rates, to
reduce the amount of guesswork in picking a good starting learning rate.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
... | with isolate_rng():
self.optimal_lr = _lr_find(
trainer,
pl_module,
min_lr=self._min_lr,
max_lr=self._max_lr,
num_training=self._num_training_steps,
mode=self._mode,
early_stop_threshold=s... | with isolate_rng():
self.optimal_lr = _lr_find(
trainer,
pl_module,
min_lr=self._min_lr,
max_lr=self._max_lr,
num_training=self._num_training_steps,
mode=self._mode,
early_stop_threshold=s... | 19 | 976 | 167 | 1,143 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,216 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/model_summary.py | 73,74 | 39,95 | _summary | ModelSummary | 74,80 | 74,80 | class ModelSummary(Callback):
r"""Generates a summary of all layers in a :class:`~lightning.pytorch.core.LightningModule`.
Args:
max_depth: The maximum depth of layer nesting that the summary will include. A value of 0 turns the
layer summary off.
**summarize_kwargs: Additional argu... | class ModelSummary(Callback):
r"""Generates a summary of all layers in a :class:`~lightning.pytorch.core.LightningModule`.
Args:
max_depth: The maximum depth of layer nesting that the summary will include. A value of 0 turns the
layer summary off.
**summarize_kwargs: Additional argu... | from lightning.pytorch.strategies.deepspeed import DeepSpeedStrategy
if isinstance(trainer.strategy, DeepSpeedStrategy) and trainer.strategy.zero_stage_3:
return DeepSpeedSummary(pl_module, max_depth=self._max_depth)
return summarize(pl_module, max_depth=self._max_depth)
| from lightning.pytorch.strategies.deepspeed import DeepSpeedStrategy
if isinstance(trainer.strategy, DeepSpeedStrategy) and trainer.strategy.zero_stage_3:
return DeepSpeedSummary(pl_module, max_depth=self._max_depth)
return summarize(pl_module, max_depth=self._max_depth)
| 15 | 579 | 99 | 678 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,217 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/on_exception_checkpoint.py | 69,71 | 31,72 | teardown | OnExceptionCheckpoint | 71,72 | 71,72 | class OnExceptionCheckpoint(Checkpoint):
"""Used to save a checkpoint on exception.
Args:
dirpath: directory to save the checkpoint file.
filename: checkpoint filename. This must not include the extension.
Raises:
ValueError:
If ``filename`` is empty.
Example:
... | class OnExceptionCheckpoint(Checkpoint):
"""Used to save a checkpoint on exception.
Args:
dirpath: directory to save the checkpoint file.
filename: checkpoint filename. This must not include the extension.
Raises:
ValueError:
If ``filename`` is empty.
Example:
... | trainer.strategy.remove_checkpoint(self.ckpt_path)
| trainer.strategy.remove_checkpoint(self.ckpt_path)
| 1 | 398 | 21 | 419 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,218 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/prediction_writer.py | 114,116 | 46,163 | setup | BasePredictionWriter | 116,119 | 116,119 | class BasePredictionWriter(Callback):
"""Base class to implement how the predictions should be stored.
Args:
write_interval: When to write.
Example::
import torch
from lightning.pytorch.callbacks import BasePredictionWriter
class CustomWriter(BasePredictionWriter):
... | class BasePredictionWriter(Callback):
"""Base class to implement how the predictions should be stored.
Args:
write_interval: When to write.
Example::
import torch
from lightning.pytorch.callbacks import BasePredictionWriter
class CustomWriter(BasePredictionWriter):
... | if is_param_in_hook_signature(pl_module.predict_step, "dataloader_iter", explicit=True):
raise NotImplementedError("The `PredictionWriterCallback` does not support using `dataloader_iter`.")
| if is_param_in_hook_signature(pl_module.predict_step, "dataloader_iter", explicit=True):
raise NotImplementedError("The `PredictionWriterCallback` does not support using `dataloader_iter`.")
| 12 | 1,341 | 66 | 1,407 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,219 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/prediction_writer.py | 37,39 | 32,46 | on_batch | WriteInterval | 39,41 | 39,41 | class WriteInterval(LightningEnum):
BATCH = "batch"
EPOCH = "epoch"
BATCH_AND_EPOCH = "batch_and_epoch"
@property
def on_batch(self) -> bool:
FILL_FUNC_BODY @property
def on_epoch(self) -> bool:
return self in (self.EPOCH, self.BATCH_AND_EPOCH)
| class WriteInterval(LightningEnum):
BATCH = "batch"
EPOCH = "epoch"
BATCH_AND_EPOCH = "batch_and_epoch"
@property
def on_batch(self) -> bool:
FILL_FUNC_BODY @property
def on_epoch(self) -> bool:
return self in (self.EPOCH, self.BATCH_AND_EPOCH)
| return self in (self.BATCH, self.BATCH_AND_EPOCH)
| return self in (self.BATCH, self.BATCH_AND_EPOCH)
| 5 | 117 | 25 | 142 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,221 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/rich_model_summary.py | 67,76 | 23,115 | summarize | RichModelSummary | 76,115 | 76,115 | class RichModelSummary(ModelSummary):
r"""Generates a summary of all layers in a :class:`~lightning.pytorch.core.LightningModule` with `rich text
formatting <https://github.com/Textualize/rich>`_.
Install it with pip:
.. code-block:: bash
pip install rich
.. code-block:: python
... | class RichModelSummary(ModelSummary):
r"""Generates a summary of all layers in a :class:`~lightning.pytorch.core.LightningModule` with `rich text
formatting <https://github.com/Textualize/rich>`_.
Install it with pip:
.. code-block:: bash
pip install rich
.. code-block:: python
... | from rich import get_console
from rich.table import Table
console = get_console()
header_style: str = summarize_kwargs.get("header_style", "bold magenta")
table = Table(header_style=header_style)
table.add_column(" ", style="dim")
table.add_column("Name", justif... | from rich import get_console
from rich.table import Table
console = get_console()
header_style: str = summarize_kwargs.get("header_style", "bold magenta")
table = Table(header_style=header_style)
table.add_column(" ", style="dim")
table.add_column("Name", justif... | 96 | 500 | 495 | 995 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,222 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/callbacks/spike.py | 12,21 | 11,32 | on_train_batch_end | SpikeDetection | 21,32 | 21,32 | class SpikeDetection(FabricSpikeDetection, Callback):
@torch.no_grad()
def on_train_batch_end( # type: ignore
self,
trainer: "pl.Trainer",
pl_module: "pl.LightningModule",
outputs: Union[torch.Tensor, Mapping[str, torch.Tensor]],
batch: Any,
batch_idx: int,
)... | class SpikeDetection(FabricSpikeDetection, Callback):
@torch.no_grad()
def on_train_batch_end( # type: ignore
self,
trainer: "pl.Trainer",
pl_module: "pl.LightningModule",
outputs: Union[torch.Tensor, Mapping[str, torch.Tensor]],
batch: Any,
batch_idx: int,
)... | if isinstance(outputs, torch.Tensor):
loss = outputs.detach()
elif isinstance(outputs, Mapping):
loss = outputs["loss"].detach()
else:
raise TypeError(f"outputs have to be of type torch.Tensor or Mapping, got {type(outputs).__qualname__}")
if self.exc... | if isinstance(outputs, torch.Tensor):
loss = outputs.detach()
elif isinstance(outputs, Mapping):
loss = outputs["loss"].detach()
else:
raise TypeError(f"outputs have to be of type torch.Tensor or Mapping, got {type(outputs).__qualname__}")
if self.exc... | 42 | 129 | 188 | 317 | import os
from typing import Any, Mapping, Union
import torch
import lightning.pytorch as pl
from lightning.fabric.utilities.spike import SpikeDetection as FabricSpikeDetection
from lightning.pytorch.callbacks.callback import Callback
class SpikeDetection(FabricSpikeDetection, Callback):
@torch.no_grad()
de... | import os
from typing import Any, Mapping, Union
import torch
import lightning.pytorch as pl
from lightning.fabric.utilities.spike import SpikeDetection as FabricSpikeDetection
from lightning.pytorch.callbacks.callback import Callback
class SpikeDetection(FabricSpikeDetection, Callback):
@torch.no_grad()
de... |
1,227 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/core/mixins/hparams_mixin.py | 32,34 | 1,178 | _given_hyperparameters_context | 34,43 | 34,43 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | hparams = hparams.copy()
hparams["_instantiator"] = instantiator
token = _given_hyperparameters.set(hparams)
try:
yield
finally:
_given_hyperparameters.reset(token)
| hparams = hparams.copy()
hparams["_instantiator"] = instantiator
token = _given_hyperparameters.set(hparams)
try:
yield
finally:
_given_hyperparameters.reset(token)
| 13 | 1,880 | 73 | 1,953 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,228 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/core/mixins/hparams_mixin.py | 140,142 | 43,178 | _to_hparams_dict | HyperparametersMixin | 142,152 | 142,152 | class HyperparametersMixin:
__jit_unused_properties__: List[str] = ["hparams", "hparams_initial"]
def __init__(self) -> None:
super().__init__()
self._log_hyperparams = False
def save_hyperparameters(
self,
*args: Any,
ignore: Optional[Union[Sequence[str], str]] = N... | class HyperparametersMixin:
__jit_unused_properties__: List[str] = ["hparams", "hparams_initial"]
def __init__(self) -> None:
super().__init__()
self._log_hyperparams = False
def save_hyperparameters(
self,
*args: Any,
ignore: Optional[Union[Sequence[str], str]] = N... | if isinstance(hp, Namespace):
hp = vars(hp)
if isinstance(hp, dict):
hp = AttributeDict(hp)
elif isinstance(hp, _PRIMITIVE_TYPES):
raise ValueError(f"Primitives {_PRIMITIVE_TYPES} are not allowed.")
elif not isinstance(hp, _ALLOWED_CONFIG_TYPES):
... | if isinstance(hp, Namespace):
hp = vars(hp)
if isinstance(hp, dict):
hp = AttributeDict(hp)
elif isinstance(hp, _PRIMITIVE_TYPES):
raise ValueError(f"Primitives {_PRIMITIVE_TYPES} are not allowed.")
elif not isinstance(hp, _ALLOWED_CONFIG_TYPES):
... | 33 | 1,410 | 139 | 1,549 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,230 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/core/optimizer.py | 61,63 | 38,173 | toggle_model | LightningOptimizer | 73,84 | 63,84 | class LightningOptimizer:
"""This class is used to wrap the user optimizers and handle properly the backward and optimizer_step logic across
accelerators, AMP, accumulate_grad_batches.
Note: The purpose of this wrapper is only to define new methods and redirect the `.step()` call. The internal
state ``... | class LightningOptimizer:
"""This class is used to wrap the user optimizers and handle properly the backward and optimizer_step logic across
accelerators, AMP, accumulate_grad_batches.
Note: The purpose of this wrapper is only to define new methods and redirect the `.step()` call. The internal
state ``... | # local import here to avoid circular import
from lightning.pytorch.loops.utilities import _block_parallel_sync_behavior
assert self._strategy is not None
lightning_module = self._strategy.lightning_module
assert lightning_module is not None
with _block_parallel_sync_beh... | """This function is just a helper for advanced users.
Considering the current optimizer as A and all other optimizers as B.
Toggling means all parameters from B exclusive to A will have ``requires_grad`` set to False.
When performing gradient accumulation, there is no need to perform g... | 32 | 1,317 | 138 | 1,455 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,231 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/core/optimizer.py | 407,409 | 382,419 | step | _MockOptimizer | 409,412 | 409,412 | class _MockOptimizer(Optimizer):
"""The `_MockOptimizer` will be used inplace of an optimizer in the event that `None` is returned from
:meth:`~lightning.pytorch.core.LightningModule.configure_optimizers`."""
def __init__(self) -> None:
super().__init__([torch.zeros(1)], {})
@override
def ... | class _MockOptimizer(Optimizer):
"""The `_MockOptimizer` will be used inplace of an optimizer in the event that `None` is returned from
:meth:`~lightning.pytorch.core.LightningModule.configure_optimizers`."""
def __init__(self) -> None:
super().__init__([torch.zeros(1)], {})
@override
def ... | if closure is not None:
return closure()
| if closure is not None:
return closure()
| 7 | 369 | 17 | 386 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,232 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/boring_classes.py | 164,165 | 155,190 | setup | BoringDataModule | 165,177 | 165,177 | class BoringDataModule(LightningDataModule):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self) -> None:
super().__init__()
self.random_full = RandomDataset(32, 64 * 4)
def setup(self, stage: str) -> None:
FILL_FUNC_BODY def train_d... | class BoringDataModule(LightningDataModule):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self) -> None:
super().__init__()
self.random_full = RandomDataset(32, 64 * 4)
def setup(self, stage: str) -> None:
FILL_FUNC_BODY def train_d... | if stage == "fit":
self.random_train = Subset(self.random_full, indices=range(64))
if stage in ("fit", "validate"):
self.random_val = Subset(self.random_full, indices=range(64, 64 * 2))
if stage == "test":
self.random_test = Subset(self.random_full, indices=... | if stage == "fit":
self.random_train = Subset(self.random_full, indices=range(64))
if stage in ("fit", "validate"):
self.random_val = Subset(self.random_full, indices=range(64, 64 * 2))
if stage == "test":
self.random_test = Subset(self.random_full, indices=... | 46 | 226 | 175 | 401 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,233 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/boring_classes.py | 137,138 | 94,155 | configure_optimizers | BoringModel | 138,142 | 138,142 | class BoringModel(LightningModule):
"""Testing PL Module.
Use as follows:
- subclass
- modify the behavior for what you want
.. warning:: This is meant for testing/debugging and is experimental.
Example::
class TestModel(BoringModel):
def training_step(self, ...):
... | class BoringModel(LightningModule):
"""Testing PL Module.
Use as follows:
- subclass
- modify the behavior for what you want
.. warning:: This is meant for testing/debugging and is experimental.
Example::
class TestModel(BoringModel):
def training_step(self, ...):
... | optimizer = torch.optim.SGD(self.parameters(), lr=0.1)
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1)
return [optimizer], [lr_scheduler]
| optimizer = torch.optim.SGD(self.parameters(), lr=0.1)
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1)
return [optimizer], [lr_scheduler]
| 11 | 601 | 74 | 675 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,234 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/boring_classes.py | 227,228 | 209,231 | configure_optimizers | DemoModel | 228,231 | 228,231 | class DemoModel(LightningModule):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self, out_dim: int = 10, learning_rate: float = 0.02):
super().__init__()
self.l1 = torch.nn.Linear(32, out_dim)
self.learning_rate = learning_rate
... | class DemoModel(LightningModule):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self, out_dim: int = 10, learning_rate: float = 0.02):
super().__init__()
self.l1 = torch.nn.Linear(32, out_dim)
self.learning_rate = learning_rate
... | return torch.optim.Adam(self.parameters(), lr=self.learning_rate)
| return torch.optim.Adam(self.parameters(), lr=self.learning_rate)
| 3 | 228 | 29 | 257 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,235 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/boring_classes.py | 199,200 | 190,209 | training_step | ManualOptimBoringModel | 200,209 | 200,209 | class ManualOptimBoringModel(BoringModel):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self) -> None:
super().__init__()
self.automatic_optimization = False
def training_step(self, batch: Any, batch_idx: int) -> STEP_OUTPUT:
FILL_FUNC... | class ManualOptimBoringModel(BoringModel):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self) -> None:
super().__init__()
self.automatic_optimization = False
def training_step(self, batch: Any, batch_idx: int) -> STEP_OUTPUT:
FILL_FUNC... | opt = self.optimizers()
assert isinstance(opt, (Optimizer, LightningOptimizer))
loss = self.step(batch)
opt.zero_grad()
self.manual_backward(loss)
opt.step()
return loss
| opt = self.optimizers()
assert isinstance(opt, (Optimizer, LightningOptimizer))
loss = self.step(batch)
opt.zero_grad()
self.manual_backward(loss)
opt.step()
return loss
| 15 | 107 | 79 | 186 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,236 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/boring_classes.py | 245,246 | 231,258 | forward | Net | 246,258 | 246,258 | class Net(nn.Module):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.drop... | class Net(nn.Module):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.drop... | x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
return F.log_softmax(x, d... | x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
return F.log_softmax(x, d... | 38 | 215 | 161 | 376 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,238 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/transformer.py | 150,151 | 145,160 | add_word | Dictionary | 151,156 | 151,156 | class Dictionary:
def __init__(self) -> None:
self.word2idx: Dict[str, int] = {}
self.idx2word: List[str] = []
def add_word(self, word: str) -> int:
FILL_FUNC_BODY def __len__(self) -> int:
return len(self.idx2word)
| class Dictionary:
def __init__(self) -> None:
self.word2idx: Dict[str, int] = {}
self.idx2word: List[str] = []
def add_word(self, word: str) -> int:
FILL_FUNC_BODY def __len__(self) -> int:
return len(self.idx2word)
| if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
return self.word2idx[word]
| if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
return self.word2idx[word]
| 13 | 100 | 63 | 163 | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... |
1,239 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/transformer.py | 204,205 | 184,207 | train_dataloader | LightningTransformer | 205,207 | 205,207 | class LightningTransformer(LightningModule):
def __init__(self, vocab_size: int = 33278) -> None:
super().__init__()
self.model = Transformer(vocab_size=vocab_size)
def forward(self, inputs: Tensor, target: Tensor) -> Tensor:
return self.model(inputs, target)
def training_step(self... | class LightningTransformer(LightningModule):
def __init__(self, vocab_size: int = 33278) -> None:
super().__init__()
self.model = Transformer(vocab_size=vocab_size)
def forward(self, inputs: Tensor, target: Tensor) -> Tensor:
return self.model(inputs, target)
def training_step(self... | dataset = WikiText2()
return DataLoader(dataset)
| dataset = WikiText2()
return DataLoader(dataset)
| 5 | 278 | 19 | 297 | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... |
1,240 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/transformer.py | 95,96 | 76,105 | _init_pos_encoding | PositionalEncoding | 96,105 | 96,105 | class PositionalEncoding(nn.Module):
def __init__(self, dim: int, dropout: float = 0.1, max_len: int = 5000) -> None:
super().__init__()
self.dropout = nn.Dropout(p=dropout)
self.dim = dim
self.max_len = max_len
self.pe: Optional[Tensor] = None
def forward(self, x: Tenso... | class PositionalEncoding(nn.Module):
def __init__(self, dim: int, dropout: float = 0.1, max_len: int = 5000) -> None:
super().__init__()
self.dropout = nn.Dropout(p=dropout)
self.dim = dim
self.max_len = max_len
self.pe: Optional[Tensor] = None
def forward(self, x: Tenso... | pe = torch.zeros(self.max_len, self.dim, device=device)
position = torch.arange(0, self.max_len, dtype=torch.float, device=device).unsqueeze(1)
div_term = torch.exp(torch.arange(0, self.dim, 2, device=device).float() * (-math.log(10000.0) / self.dim))
pe[:, 0::2] = torch.sin(position * d... | pe = torch.zeros(self.max_len, self.dim, device=device)
position = torch.arange(0, self.max_len, dtype=torch.float, device=device).unsqueeze(1)
div_term = torch.exp(torch.arange(0, self.dim, 2, device=device).float() * (-math.log(10000.0) / self.dim))
pe[:, 0::2] = torch.sin(position * d... | 39 | 315 | 192 | 507 | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... |
1,241 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/transformer.py | 59,60 | 31,76 | forward | Transformer | 60,76 | 60,76 | class Transformer(nn.Module):
def __init__(
self,
vocab_size: int = 33278, # default for WikiText2
ninp: int = 200,
nhead: int = 2,
nhid: int = 200,
nlayers: int = 2,
dropout: float = 0.2,
) -> None:
super().__init__()
self.pos_encoder = P... | class Transformer(nn.Module):
def __init__(
self,
vocab_size: int = 33278, # default for WikiText2
ninp: int = 200,
nhead: int = 2,
nhid: int = 200,
nlayers: int = 2,
dropout: float = 0.2,
) -> None:
super().__init__()
self.pos_encoder = P... | _, t = inputs.shape
# we assume target is already shifted w.r.t. inputs
if mask is None:
mask = torch.tril(torch.ones(t, t, device=inputs.device)) == 1
mask = mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, 0.0)
src = self.pos_encoder(s... | _, t = inputs.shape
# we assume target is already shifted w.r.t. inputs
if mask is None:
mask = torch.tril(torch.ones(t, t, device=inputs.device)) == 1
mask = mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, 0.0)
src = self.pos_encoder(s... | 61 | 336 | 246 | 582 | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... |
1,242 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/demos/transformer.py | 130,132 | 105,145 | download | WikiText2 | 132,145 | 132,145 | class WikiText2(Dataset):
"""Mini version of WikiText2."""
def __init__(self, data_dir: Path = Path("./data"), block_size: int = 35, download: bool = True) -> None:
super().__init__()
self.path = data_dir / "wikitext-2.txt"
if download:
self.download(self.path)
self.... | class WikiText2(Dataset):
"""Mini version of WikiText2."""
def __init__(self, data_dir: Path = Path("./data"), block_size: int = 35, download: bool = True) -> None:
super().__init__()
self.path = data_dir / "wikitext-2.txt"
if download:
self.download(self.path)
self.... | if not _REQUESTS_AVAILABLE:
raise ModuleNotFoundError(str(_REQUESTS_AVAILABLE))
import requests
os.makedirs(destination.parent, exist_ok=True)
url = "https://raw.githubusercontent.com/pytorch/examples/main/word_language_model/data/wikitext-2/train.txt"
if os.path.ex... | if not _REQUESTS_AVAILABLE:
raise ModuleNotFoundError(str(_REQUESTS_AVAILABLE))
import requests
os.makedirs(destination.parent, exist_ok=True)
url = "https://raw.githubusercontent.com/pytorch/examples/main/word_language_model/data/wikitext-2/train.txt"
if os.path.ex... | 21 | 306 | 156 | 462 | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... | """Demo of a simple transformer language model.
Code is adapted from the PyTorch examples at
https://github.com/pytorch/examples/blob/main/word_language_model
"""
import math
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.function... |
1,243 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loggers/csv_logs.py | 148,151 | 72,172 | log_hyperparams | CSVLogger | 151,154 | 151,154 | class CSVLogger(Logger, FabricCSVLogger):
r"""Log to local file system in yaml and CSV format.
Logs are saved to ``os.path.join(save_dir, name, version)``.
Example:
>>> from lightning.pytorch import Trainer
>>> from lightning.pytorch.loggers import CSVLogger
>>> logger = CSVLogger(... | class CSVLogger(Logger, FabricCSVLogger):
r"""Log to local file system in yaml and CSV format.
Logs are saved to ``os.path.join(save_dir, name, version)``.
Example:
>>> from lightning.pytorch import Trainer
>>> from lightning.pytorch.loggers import CSVLogger
>>> logger = CSVLogger(... | params = _convert_params(params)
self.experiment.log_hparams(params)
| params = _convert_params(params)
self.experiment.log_hparams(params)
| 4 | 964 | 29 | 993 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,244 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loggers/csv_logs.py | 64,66 | 41,72 | save | ExperimentWriter | 67,72 | 66,72 | class ExperimentWriter(_FabricExperimentWriter):
r"""Experiment writer for CSVLogger.
Currently, supports to log hyperparameters and metrics in YAML and CSV
format, respectively.
This logger supports logging to remote filesystems via ``fsspec``. Make sure you have it installed.
Args:
log_... | class ExperimentWriter(_FabricExperimentWriter):
r"""Experiment writer for CSVLogger.
Currently, supports to log hyperparameters and metrics in YAML and CSV
format, respectively.
This logger supports logging to remote filesystems via ``fsspec``. Make sure you have it installed.
Args:
log_... | hparams_file = os.path.join(self.log_dir, self.NAME_HPARAMS_FILE)
save_hparams_to_yaml(hparams_file, self.hparams)
return super().save()
| """Save recorded hparams and metrics into files."""
hparams_file = os.path.join(self.log_dir, self.NAME_HPARAMS_FILE)
save_hparams_to_yaml(hparams_file, self.hparams)
return super().save()
| 8 | 245 | 66 | 311 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,245 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loggers/logger.py | 100,105 | 1,151 | merge_dicts | 138,151 | 105,151 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | agg_key_funcs = agg_key_funcs or {}
keys = list(functools.reduce(operator.or_, [set(d.keys()) for d in dicts]))
d_out: Dict = defaultdict(dict)
for k in keys:
fn = agg_key_funcs.get(k)
values_to_agg = [v for v in [d_in.get(k) for d_in in dicts] if v is not None]
if isinstance(va... | """Merge a sequence with dictionaries into one dictionary by aggregating the same keys with some given function.
Args:
dicts:
Sequence of dictionaries to be merged.
agg_key_funcs:
Mapping from key name to function. This function will aggregate a
list of value... | 56 | 1,384 | 214 | 1,598 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,246 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loggers/logger.py | 61,63 | 50,100 | experiment | DummyLogger | 64,66 | 63,66 | class DummyLogger(Logger):
"""Dummy logger for internal use.
It is useful if we want to disable user's logger for a feature, but still ensure that user code can run
"""
def __init__(self) -> None:
super().__init__()
self._experiment = DummyExperiment()
@property
def experimen... | class DummyLogger(Logger):
"""Dummy logger for internal use.
It is useful if we want to disable user's logger for a feature, but still ensure that user code can run
"""
def __init__(self) -> None:
super().__init__()
self._experiment = DummyExperiment()
@property
def experimen... | return self._experiment
| """Return the experiment object associated with this logger."""
return self._experiment
| 2 | 378 | 10 | 388 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,247 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loggers/logger.py | 43,45 | 31,50 | save_dir | Logger | 47,50 | 45,50 | class Logger(FabricLogger, ABC):
"""Base class for experiment loggers."""
def after_save_checkpoint(self, checkpoint_callback: ModelCheckpoint) -> None:
"""Called after model checkpoint callback saves a new checkpoint.
Args:
checkpoint_callback: the model checkpoint callback instan... | class Logger(FabricLogger, ABC):
"""Base class for experiment loggers."""
def after_save_checkpoint(self, checkpoint_callback: ModelCheckpoint) -> None:
"""Called after model checkpoint callback saves a new checkpoint.
Args:
checkpoint_callback: the model checkpoint callback instan... | return None
| """Return the root directory where experiment logs get saved, or `None` if the logger does not save data
locally."""
return None
| 2 | 147 | 9 | 156 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,248 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loggers/utilities.py | 32,33 | 1,96 | _scan_checkpoints | 40,59 | 33,59 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # get checkpoints to be saved with associated score
checkpoints = {}
if hasattr(checkpoint_callback, "last_model_path") and hasattr(checkpoint_callback, "current_score"):
checkpoints[checkpoint_callback.last_model_path] = (checkpoint_callback.current_score, "latest")
if hasattr(checkpoint_callb... | """Return the checkpoints to be logged.
Args:
checkpoint_callback: Checkpoint callback reference.
logged_model_time: dictionary containing the logged model times.
"""
# get checkpoints to be saved with associated score
checkpoints = {}
if hasattr(checkpoint_callback, "last_mode... | 78 | 897 | 325 | 1,222 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,249 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/loop.py | 52,53 | 20,96 | state_dict | _Loop | 61,74 | 53,74 | class _Loop:
"""Basic Loops interface."""
def __init__(self, trainer: "pl.Trainer") -> None:
self._restarting = False
self.trainer = trainer
@property
def restarting(self) -> bool:
"""Whether the state of this loop was reloaded and it needs to restart."""
return self._r... | class _Loop:
"""Basic Loops interface."""
def __init__(self, trainer: "pl.Trainer") -> None:
self._restarting = False
self.trainer = trainer
@property
def restarting(self) -> bool:
"""Whether the state of this loop was reloaded and it needs to restart."""
return self._r... | if destination is None:
destination = {}
destination[prefix + "state_dict"] = self.on_save_checkpoint()
for k, v in self.__dict__.items():
key = prefix + k
if isinstance(v, _BaseProgress):
destination[key] = v.state_dict()
elif is... | """The state dict is determined by the state and progress of this loop and all its children.
Args:
destination: An existing dictionary to update with this loop's state. By default a new dictionary
is returned.
prefix: A prefix for each key in the state dictionary... | 37 | 665 | 125 | 790 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,250 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/optimization/automatic.py | 126,129 | 90,148 | closure | Closure | 129,142 | 129,142 | class Closure(AbstractClosure[ClosureResult]):
"""An implementation of a :class:`AbstractClosure` for automatic optimization in Lightning that combines three
elementary closures into one: ``training_step``, ``backward`` and ``zero_grad``.
The Closure gets created by the training loop(s) and is then passed ... | class Closure(AbstractClosure[ClosureResult]):
"""An implementation of a :class:`AbstractClosure` for automatic optimization in Lightning that combines three
elementary closures into one: ``training_step``, ``backward`` and ``zero_grad``.
The Closure gets created by the training loop(s) and is then passed ... | step_output = self._step_fn()
if step_output.closure_loss is None:
self.warning_cache.warn("`training_step` returned `None`. If this was on purpose, ignore this warning...")
if self._zero_grad_fn is not None:
self._zero_grad_fn()
if self._backward_fn is not Non... | step_output = self._step_fn()
if step_output.closure_loss is None:
self.warning_cache.warn("`training_step` returned `None`. If this was on purpose, ignore this warning...")
if self._zero_grad_fn is not None:
self._zero_grad_fn()
if self._backward_fn is not Non... | 37 | 529 | 145 | 674 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,251 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/optimization/automatic.py | 59,61 | 34,90 | from_training_step_output | ClosureResult | 61,85 | 61,85 | @dataclass
class ClosureResult(OutputResult):
"""A container to hold the result of a :class:`Closure` call.
It is created from the output of :meth:`~lightning.pytorch.core.LightningModule.training_step`.
Attributes:
closure_loss: The loss with a graph attached.
loss: A detached copy of the... | @dataclass
class ClosureResult(OutputResult):
"""A container to hold the result of a :class:`Closure` call.
It is created from the output of :meth:`~lightning.pytorch.core.LightningModule.training_step`.
Attributes:
closure_loss: The loss with a graph attached.
loss: A detached copy of the... | closure_loss, extra = None, {}
if isinstance(training_step_output, Mapping):
closure_loss = training_step_output.get("loss")
if closure_loss is None:
raise MisconfigurationException(
"In automatic_optimization, when `training_step` returns a d... | closure_loss, extra = None, {}
if isinstance(training_step_output, Mapping):
closure_loss = training_step_output.get("loss")
if closure_loss is None:
raise MisconfigurationException(
"In automatic_optimization, when `training_step` returns a d... | 112 | 348 | 312 | 660 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,252 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/optimization/automatic.py | 243,248 | 151,322 | _optimizer_step | _AutomaticOptimization | 256,280 | 248,280 | class _AutomaticOptimization(_Loop):
"""Performs automatic optimization (forward, zero grad, backward, optimizer step)"""
output_result_cls = ClosureResult
def __init__(self, trainer: "pl.Trainer") -> None:
super().__init__(trainer)
self.optim_progress: _OptimizationProgress = _Optimizatio... | class _AutomaticOptimization(_Loop):
"""Performs automatic optimization (forward, zero grad, backward, optimizer step)"""
output_result_cls = ClosureResult
def __init__(self, trainer: "pl.Trainer") -> None:
super().__init__(trainer)
self.optim_progress: _OptimizationProgress = _Optimizatio... | trainer = self.trainer
# wraps into LightningOptimizer only for running step
optimizer = trainer.strategy._lightning_optimizers[0]
# if `strategy.handles_gradient_accumulation`, this method will be called to route into the strategy, but we
# need to check again if `should_accum... | """Performs the optimizer step and some sanity checking.
Args:
batch_idx: the index of the current batch
train_step_and_backward_closure: the closure function performing the train step and computing the
gradients. By default, called by the optimizer (if possible)... | 62 | 1,720 | 269 | 1,989 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,253 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/optimization/closure.py | 45,46 | 29,69 | consume_result | AbstractClosure | 52,61 | 46,61 | class AbstractClosure(ABC, Generic[T]):
"""Abstract base class for optimizer closures in Lightning.
Formally, a closure is binding variables from an external scope to a function that does a computation on these
variables without taking them explicitly as input. This has the benefit that a closure can be pa... | class AbstractClosure(ABC, Generic[T]):
"""Abstract base class for optimizer closures in Lightning.
Formally, a closure is binding variables from an external scope to a function that does a computation on these
variables without taking them explicitly as input. This has the benefit that a closure can be pa... | if self._result is None:
raise MisconfigurationException(
"The closure hasn't been executed."
" HINT: did you call `optimizer_closure()` in your `optimizer_step` hook? It could also happen because"
" the `optimizer.step(optimizer_closure)` call did not... | """The cached result from the last time the closure was called.
Once accessed, the internal reference gets reset and the consumer will have to hold on to the reference as long
as necessary.
"""
if self._result is None:
raise MisconfigurationException(
... | 46 | 328 | 118 | 446 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,254 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/optimization/closure.py | 25,26 | 23,29 | asdict | OutputResult | 26,29 | 26,29 | @dataclass
class OutputResult:
def asdict(self) -> Dict[str, Any]:
FILL_FUNC_BODY | @dataclass
class OutputResult:
def asdict(self) -> Dict[str, Any]:
FILL_FUNC_BODY | raise NotImplementedError
| raise NotImplementedError
| 2 | 37 | 13 | 50 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,255 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/optimization/manual.py | 45,47 | 32,68 | from_training_step_output | ManualResult | 47,63 | 47,63 | @dataclass
class ManualResult(OutputResult):
"""A container to hold the result returned by ``_ManualOptimization``.
It is created from the output of :meth:`~lightning.pytorch.core.LightningModule.training_step`.
Attributes:
extra: Anything returned by the ``training_step``.
"""
extra: Di... | @dataclass
class ManualResult(OutputResult):
"""A container to hold the result returned by ``_ManualOptimization``.
It is created from the output of :meth:`~lightning.pytorch.core.LightningModule.training_step`.
Attributes:
extra: Anything returned by the ``training_step``.
"""
extra: Di... | extra = {}
if isinstance(training_step_output, dict):
extra = training_step_output.copy()
elif isinstance(training_step_output, Tensor):
extra = {"loss": training_step_output}
elif training_step_output is not None:
raise MisconfigurationException(
... | extra = {}
if isinstance(training_step_output, dict):
extra = training_step_output.copy()
elif isinstance(training_step_output, Tensor):
extra = {"loss": training_step_output}
elif training_step_output is not None:
raise MisconfigurationException(
... | 59 | 191 | 179 | 370 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,256 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/optimization/manual.py | 121,122 | 71,137 | on_run_end | _ManualOptimization | 123,130 | 122,130 | class _ManualOptimization(_Loop):
"""A special loop implementing what is known in Lightning as Manual Optimization where the optimization happens
entirely in the :meth:`~lightning.pytorch.core.LightningModule.training_step` and therefore the user is responsible
for back-propagating gradients and making call... | class _ManualOptimization(_Loop):
"""A special loop implementing what is known in Lightning as Manual Optimization where the optimization happens
entirely in the :meth:`~lightning.pytorch.core.LightningModule.training_step` and therefore the user is responsible
for back-propagating gradients and making call... | output, self._output = self._output, {} # free memory
# reset logic around the optimizer step
for lightning_optimizer in self.trainer.strategy._lightning_optimizers:
lightning_optimizer._on_before_step = do_nothing_closure
lightning_optimizer._on_after_step = do_nothing_... | """Returns the result of this loop, i.e., the post-processed outputs from the training step."""
output, self._output = self._output, {} # free memory
# reset logic around the optimizer step
for lightning_optimizer in self.trainer.strategy._lightning_optimizers:
lightning_opt... | 27 | 774 | 97 | 871 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,257 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 30,32 | 20,41 | from_state_dict | _BaseProgress | 32,36 | 32,36 | @dataclass
class _BaseProgress:
"""Mixin that implements state-loading utilities for dataclasses."""
def state_dict(self) -> dict:
return asdict(self)
def load_state_dict(self, state_dict: dict) -> None:
self.__dict__.update(state_dict)
@classmethod
def from_state_dict(cls, state_... | @dataclass
class _BaseProgress:
"""Mixin that implements state-loading utilities for dataclasses."""
def state_dict(self) -> dict:
return asdict(self)
def load_state_dict(self, state_dict: dict) -> None:
self.__dict__.update(state_dict)
@classmethod
def from_state_dict(cls, state_... | obj = cls()
obj.load_state_dict(state_dict)
return obj
| obj = cls()
obj.load_state_dict(state_dict)
return obj
| 6 | 156 | 30 | 186 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,258 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 204,206 | 184,215 | reset_on_run | _BatchProgress | 206,209 | 206,209 | @dataclass
class _BatchProgress(_Progress):
"""Tracks batch progress.
These counters are local to a trainer rank. By default, they are not globally synced across all ranks.
Args:
total: Tracks the total batch progress.
current: Tracks the current batch progress.
is_last_batch: Whet... | @dataclass
class _BatchProgress(_Progress):
"""Tracks batch progress.
These counters are local to a trainer rank. By default, they are not globally synced across all ranks.
Args:
total: Tracks the total batch progress.
current: Tracks the current batch progress.
is_last_batch: Whet... | super().reset_on_run()
self.is_last_batch = False
| super().reset_on_run()
self.is_last_batch = False
| 4 | 243 | 25 | 268 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,259 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 282,283 | 263,291 | reset_on_run | _OptimizationProgress | 283,285 | 283,285 | @dataclass
class _OptimizationProgress(_BaseProgress):
"""Track optimization progress.
Args:
optimizer: Tracks optimizer progress.
"""
optimizer: _OptimizerProgress = field(default_factory=_OptimizerProgress)
@property
def optimizer_steps(self) -> int:
return self.optimizer.s... | @dataclass
class _OptimizationProgress(_BaseProgress):
"""Track optimization progress.
Args:
optimizer: Tracks optimizer progress.
"""
optimizer: _OptimizerProgress = field(default_factory=_OptimizerProgress)
@property
def optimizer_steps(self) -> int:
return self.optimizer.s... | self.optimizer.reset_on_run()
| self.optimizer.reset_on_run()
| 1 | 231 | 16 | 247 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,260 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 249,250 | 231,263 | reset_on_run | _OptimizerProgress | 250,253 | 250,253 | @dataclass
class _OptimizerProgress(_BaseProgress):
"""Track optimizer progress.
Args:
step: Tracks ``optimizer.step`` calls.
zero_grad: Tracks ``optimizer.zero_grad`` calls.
"""
step: _Progress = field(default_factory=lambda: _Progress.from_defaults(_ReadyCompletedTracker))
zero_... | @dataclass
class _OptimizerProgress(_BaseProgress):
"""Track optimizer progress.
Args:
step: Tracks ``optimizer.step`` calls.
zero_grad: Tracks ``optimizer.zero_grad`` calls.
"""
step: _Progress = field(default_factory=lambda: _Progress.from_defaults(_ReadyCompletedTracker))
zero_... | self.step.reset_on_run()
self.zero_grad.reset_on_run()
| self.step.reset_on_run()
self.zero_grad.reset_on_run()
| 2 | 300 | 30 | 330 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,261 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 119,121 | 98,125 | reset_on_restart | _ProcessedTracker | 121,125 | 121,125 | @dataclass
class _ProcessedTracker(_StartedTracker):
"""Track an event's progress.
Args:
ready: Intended to track the number of events ready to start.
started: Intended to be incremented after the event is started (e.g. after ``on_*_start`` runs).
processed: Intended to be incremented a... | @dataclass
class _ProcessedTracker(_StartedTracker):
"""Track an event's progress.
Args:
ready: Intended to track the number of events ready to start.
started: Intended to be incremented after the event is started (e.g. after ``on_*_start`` runs).
processed: Intended to be incremented a... | super().reset_on_restart()
self.processed = self.completed
| super().reset_on_restart()
self.processed = self.completed
| 4 | 229 | 28 | 257 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,262 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 152,153 | 125,184 | increment_processed | _Progress | 153,158 | 153,158 | @dataclass
class _Progress(_BaseProgress):
"""Track aggregated and current progress.
Args:
total: Intended to track the total progress of an event.
current: Intended to track the current progress of an event.
"""
total: _ReadyCompletedTracker = field(default_factory=_ProcessedTracker)... | @dataclass
class _Progress(_BaseProgress):
"""Track aggregated and current progress.
Args:
total: Intended to track the total progress of an event.
current: Intended to track the current progress of an event.
"""
total: _ReadyCompletedTracker = field(default_factory=_ProcessedTracker)... | if not isinstance(self.total, _ProcessedTracker):
raise TypeError(f"`{self.total.__class__.__name__}` doesn't have a `processed` attribute")
self.total.processed += 1
self.current.processed += 1
| if not isinstance(self.total, _ProcessedTracker):
raise TypeError(f"`{self.total.__class__.__name__}` doesn't have a `processed` attribute")
self.total.processed += 1
self.current.processed += 1
| 17 | 582 | 75 | 657 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,263 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 56,58 | 41,72 | reset | _ReadyCompletedTracker | 59,62 | 58,62 | @dataclass
class _ReadyCompletedTracker(_BaseProgress):
"""Track an event's progress.
Args:
ready: Intended to track the number of events ready to start.
completed: Intended to be incremented after the event completes (e.g. after ``on_*_end`` runs).
These attributes should be increased in ... | @dataclass
class _ReadyCompletedTracker(_BaseProgress):
"""Track an event's progress.
Args:
ready: Intended to track the number of events ready to start.
completed: Intended to be incremented after the event completes (e.g. after ``on_*_end`` runs).
These attributes should be increased in ... | self.ready = 0
self.completed = 0
| """Reset the state."""
self.ready = 0
self.completed = 0
| 6 | 228 | 19 | 247 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,264 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/pytorch/loops/progress.py | 87,89 | 72,98 | reset | _StartedTracker | 89,92 | 89,92 | @dataclass
class _StartedTracker(_ReadyCompletedTracker):
"""Track an event's progress.
Args:
ready: Intended to track the number of events ready to start.
started: Intended to be incremented after the event is started (e.g. after ``on_*_start`` runs).
completed: Intended to be incremen... | @dataclass
class _StartedTracker(_ReadyCompletedTracker):
"""Track an event's progress.
Args:
ready: Intended to track the number of events ready to start.
started: Intended to be incremented after the event is started (e.g. after ``on_*_start`` runs).
completed: Intended to be incremen... | super().reset()
self.started = 0
| super().reset()
self.started = 0
| 4 | 223 | 18 | 241 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.