Source code for lightning.pytorch.plugins.precision.xla
# 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 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.importosfromfunctoolsimportpartialfromtypingimportAny,Callableimporttorchfromtyping_extensionsimportget_args,overrideimportlightning.pytorchasplfromlightning.fabric.accelerators.xlaimport_XLA_AVAILABLEfromlightning.fabric.plugins.precision.xlaimport_PRECISION_INPUTfromlightning.fabric.utilities.typesimportOptimizablefromlightning.pytorch.plugins.precision.precisionimportPrecisionfromlightning.pytorch.utilities.exceptionsimportMisconfigurationException
[docs]classXLAPrecision(Precision):"""Plugin for training with XLA. Args: precision: Full precision (32-true) or half precision (16-true, bf16-true). Raises: ValueError: If unsupported ``precision`` is provided. """def__init__(self,precision:_PRECISION_INPUT="32-true")->None:ifnot_XLA_AVAILABLE:raiseModuleNotFoundError(str(_XLA_AVAILABLE))supported_precision=get_args(_PRECISION_INPUT)ifprecisionnotinsupported_precision:raiseValueError(f"`precision={precision!r})` is not supported in XLA."f" `precision` must be one of: {supported_precision}.")self.precision=precisionifprecision=="16-true":os.environ["XLA_USE_F16"]="1"self._desired_dtype=torch.float16elifprecision=="bf16-true":os.environ["XLA_USE_BF16"]="1"self._desired_dtype=torch.bfloat16else:self._desired_dtype=torch.float32
[docs]@overridedefoptimizer_step(# type: ignore[override]self,optimizer:Optimizable,model:"pl.LightningModule",closure:Callable[[],Any],**kwargs:Any,)->Any:importtorch_xla.core.xla_modelasxmclosure=partial(self._xla_wrap_closure,optimizer,closure)closure=partial(self._wrap_closure,model,optimizer,closure)closure_result=optimizer.step(closure=closure,**kwargs)xm.mark_step()skipped_backward=closure_resultisNone# in manual optimization, the closure does not return a valueifmodel.automatic_optimizationandskipped_backward:# we lack coverage here so disable this - something to explore if there's demandraiseMisconfigurationException("Skipping backward by returning `None` from your `training_step` is not implemented with XLA."" Please, open an issue in `https://github.com/Lightning-AI/pytorch-lightning/issues`"" requesting this feature.")returnclosure_result
To analyze traffic and optimize your experience, we serve cookies on this
site. By clicking or navigating, you agree to allow our usage of cookies.
Read PyTorch Lightning's
Privacy Policy.