<commit_before># Copyright The PyTorch Lightning 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional

from pytorch_lightning import _logger as log
from pytorch_lightning.plugins.apex import ApexPlugin
from pytorch_lightning.plugins.native_amp import NativeAMPPlugin
from pytorch_lightning.plugins.sharded_native_amp_plugin import ShardedNativeAMPPlugin
from pytorch_lightning.plugins.sharded_plugin import DDPShardedPlugin
from pytorch_lightning.utilities import APEX_AVAILABLE, NATIVE_AMP_AVALAIBLE, AMPType, rank_zero_warn, \
    FAIRSCALE_AVAILABLE
from pytorch_lightning.utilities.exceptions import MisconfigurationException


class PrecisionConnector:

    def __init__(self, trainer):
        self.trainer = trainer
        self.backend = None

    def on_trainer_init(self, precision, amp_level, amp_backend, plugins):
        # AMP init
        # These are the only lines needed after v0.8.0
        # we wrap the user's forward with autocast and give it back at the end of fit
        self.trainer.autocast_original_forward = None
        self.trainer.precision = precision
        self.trainer.scaler = None

        self.trainer.amp_level = amp_level
        self.init_amp(amp_backend, plugins)

    def init_amp(self, amp_type: str, plugins: Optional[list]):
        assert self.trainer.precision in (16, 32), 'only 32 or 16 bit precision supported'
        self.trainer.amp_backend = None
        self._setup_amp_backend(amp_type, plugins)

    def _setup_amp_backend(self, amp_type: str, plugins: Optional[list]):
        if self.trainer.precision != 16:
            # no AMP requested, so we can leave now
            return

        amp_type = amp_type.lower()
        assert amp_type in ('native', 'apex'), f'Unsupported amp type {amp_type}'
        if amp_type == 'native':
            if not NATIVE_AMP_AVALAIBLE:
                rank_zero_warn('You have asked for native AMP but your PyTorch version does not support it.'
                               ' Consider upgrading with `pip install torch>=1.6`.'
                               ' We will attempt to use NVIDIA Apex for this session.')
                amp_type = 'apex'
            else:
                self.trainer.amp_backend = AMPType.NATIVE
                if plugins and self._sharded_in_plugins(plugins):
                    if not FAIRSCALE_AVAILABLE:
                        raise MisconfigurationException('Sharded DDP Plugin requires Fairscale to be installed.')
                    log.info('Using Sharded 16bit plugin.')
                    self.backend = ShardedNativeAMPPlugin(self.trainer)
                else:
                    log.info('Using native 16bit precision.')
                    self.backend = NativeAMPPlugin(self.trainer)

        if amp_type == 'apex':
            if not APEX_AVAILABLE:
                rank_zero_warn('You have asked for Apex AMP but you have not installed it yet.'
                               ' Install apex first using this guide: https://github.com/NVIDIA/apex#linux')
            else:
                log.info('Using APEX 16bit precision.')
                self.trainer.amp_backend = AMPType.APEX
                self.backend = ApexPlugin(self.trainer)

        if not self.trainer.amp_backend:
            raise ModuleNotFoundError(
                f'You have asked for AMP support {amp_type}, but there is no support on your side yet.'
                f' Consider installing torch >= 1.6 or NVIDIA Apex.'
            )

    def connect(self, model):
        if self.backend:
            model, optimizers = self.backend.connect(model, self.trainer.optimizers)
            self.trainer.optimizers = optimizers

        return model

    def _sharded_in_plugins(self, plugins):
        for plugin in plugins:
            if isinstance(plugin, DDPShardedPlugin):
                return True
        return False
<commit_msg>Add additional check to ensure apex is not used with sharded<commit_after># Copyright The PyTorch Lightning 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional

from pytorch_lightning import _logger as log
from pytorch_lightning.plugins.apex import ApexPlugin
from pytorch_lightning.plugins.native_amp import NativeAMPPlugin
from pytorch_lightning.plugins.sharded_native_amp_plugin import ShardedNativeAMPPlugin
from pytorch_lightning.plugins.sharded_plugin import DDPShardedPlugin
from pytorch_lightning.utilities import APEX_AVAILABLE, NATIVE_AMP_AVALAIBLE, AMPType, rank_zero_warn, \
    FAIRSCALE_AVAILABLE
from pytorch_lightning.utilities.exceptions import MisconfigurationException


class PrecisionConnector:

    def __init__(self, trainer):
        self.trainer = trainer
        self.backend = None

    def on_trainer_init(self, precision, amp_level, amp_backend, plugins):
        # AMP init
        # These are the only lines needed after v0.8.0
        # we wrap the user's forward with autocast and give it back at the end of fit
        self.trainer.autocast_original_forward = None
        self.trainer.precision = precision
        self.trainer.scaler = None

        self.trainer.amp_level = amp_level
        self.init_amp(amp_backend, plugins)

    def init_amp(self, amp_type: str, plugins: Optional[list]):
        assert self.trainer.precision in (16, 32), 'only 32 or 16 bit precision supported'
        self.trainer.amp_backend = None
        self._setup_amp_backend(amp_type, plugins)

    def _setup_amp_backend(self, amp_type: str, plugins: Optional[list]):
        if self.trainer.precision != 16:
            # no AMP requested, so we can leave now
            return

        using_sharded_plugin = self._check_sharded_plugin(plugins)
        amp_type = amp_type.lower()
        assert amp_type in ('native', 'apex'), f'Unsupported amp type {amp_type}'
        if amp_type == 'native':
            if not NATIVE_AMP_AVALAIBLE:
                rank_zero_warn('You have asked for native AMP but your PyTorch version does not support it.'
                               ' Consider upgrading with `pip install torch>=1.6`.'
                               ' We will attempt to use NVIDIA Apex for this session.')
                amp_type = 'apex'
            else:
                self.trainer.amp_backend = AMPType.NATIVE
                if using_sharded_plugin:
                    log.info('Using sharded 16bit precision.')
                    self.backend = ShardedNativeAMPPlugin(self.trainer)
                else:
                    log.info('Using native 16bit precision.')
                    self.backend = NativeAMPPlugin(self.trainer)

        if amp_type == 'apex':
            if not APEX_AVAILABLE:
                rank_zero_warn('You have asked for Apex AMP but you have not installed it yet.'
                               ' Install apex first using this guide: https://github.com/NVIDIA/apex#linux')
            if using_sharded_plugin:
                rank_zero_warn(
                    'Sharded Plugin is not supported with Apex AMP, please using native AMP for 16 bit precision.')
            else:
                log.info('Using APEX 16bit precision.')
                self.trainer.amp_backend = AMPType.APEX
                self.backend = ApexPlugin(self.trainer)

        if not self.trainer.amp_backend:
            raise ModuleNotFoundError(
                f'You have asked for AMP support {amp_type}, but there is no support on your side yet.'
                f' Consider installing torch >= 1.6 or NVIDIA Apex.'
            )

    def connect(self, model):
        if self.backend:
            model, optimizers = self.backend.connect(model, self.trainer.optimizers)
            self.trainer.optimizers = optimizers

        return model

    def _check_sharded_plugin(self, plugins):
        if plugins and self._sharded_in_plugins(plugins):
            if not FAIRSCALE_AVAILABLE:
                raise MisconfigurationException('Sharded DDP Plugin requires Fairscale to be installed.')
            return True
        return False

    def _sharded_in_plugins(self, plugins):
        for plugin in plugins:
            if isinstance(plugin, DDPShardedPlugin):
                return True
        return False

{'fraction_non_alphanumeric': 0.06594841658504734, 'fraction_numerical': 0.006094243116770051, 'mean_word_length': 2.4201711946408633, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5393857', 'n_tokens_mistral': 2621, 'n_tokens_neox': 2432, 'n_words': 810}