|
| 1 | +from typing import Union |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch import nn |
| 5 | +from transformers import add_start_docstrings |
| 6 | +from transformers.pipelines import Pipeline |
| 7 | +from transformers.utils import is_ipex_available |
| 8 | + |
| 9 | + |
| 10 | +IPEX_NOT_AVAILABLE_ERROR_MSG = ( |
| 11 | + "Intel PyTorch Extensions was not found." |
| 12 | + "please make sure you've installed the package or run " |
| 13 | + "pip install intel_extension_for_pytorch" |
| 14 | +) |
| 15 | + |
| 16 | +if is_ipex_available(): |
| 17 | + import intel_extension_for_pytorch as ipex |
| 18 | + |
| 19 | + |
| 20 | +class _ModelFallbackWrapper: |
| 21 | + |
| 22 | + __slots__ = ("_optimized", "_default") |
| 23 | + |
| 24 | + def __init__(self, optimized, default): |
| 25 | + self._optimized = optimized |
| 26 | + self._default = default |
| 27 | + |
| 28 | + def __call__(self, *args, **kwargs): |
| 29 | + try: |
| 30 | + return self._optimized(*args, **kwargs) |
| 31 | + except Exception: |
| 32 | + return self._default(*args, **kwargs) |
| 33 | + |
| 34 | + def __getattr__(self, item): |
| 35 | + if not item.startswith("__"): |
| 36 | + return getattr(self._default, item) |
| 37 | + else: |
| 38 | + return self.item |
| 39 | + |
| 40 | + |
| 41 | +@add_start_docstrings( |
| 42 | + """ |
| 43 | + inference_mode is an Intel specific context-manager analogous to PyTorch's inference_mode to use for inference |
| 44 | + workload on Intel CPUs, especially Intel Xeon Scalable CPUs. |
| 45 | + """, |
| 46 | +) |
| 47 | +class inference_mode: |
| 48 | + __slots__ = ("_model", "_dtype", "_graph_mode", "_verbose", "_original") |
| 49 | + |
| 50 | + def __init__(self, model: Union[nn.Module, Pipeline], dtype: torch.dtype = torch.float32, verbose: bool = False): |
| 51 | + """ |
| 52 | + Args: |
| 53 | + model (`torch.nn.Module` or `transformers.Pipeline`): |
| 54 | + The model or pipeline instance to optimize. |
| 55 | + dtype (`torch.dtype = torch.float32`), *optional*): |
| 56 | + The data type used to do the computation. |
| 57 | + Acceptable type are `torch.float32` (default) and `torch.bfloat16`. |
| 58 | + Please note `torch.bfloat16` requires `avx512_bf16` instructions set as present on |
| 59 | + 4th Generation of Intel Xeon Scalable CPUs (Sapphire Rapids). |
| 60 | + verbose (`boolean = False`, *optional*): |
| 61 | + Enable IPEx verbose output to see the kernels and optimizations applied. |
| 62 | + """ |
| 63 | + if not is_ipex_available(): |
| 64 | + raise ImportError(IPEX_NOT_AVAILABLE_ERROR_MSG) |
| 65 | + |
| 66 | + self._model = model |
| 67 | + self._verbose = ipex.utils.verbose.VERBOSE_ON if verbose else ipex.utils.verbose.VERBOSE_OFF |
| 68 | + self._dtype = dtype |
| 69 | + self._graph_mode = False # Let's keep for future use when it doesn't hang anymore |
| 70 | + self._original = None |
| 71 | + |
| 72 | + def __enter__(self): |
| 73 | + with torch.inference_mode(): |
| 74 | + with ipex.verbose(self._verbose): |
| 75 | + ipex.enable_onednn_fusion(True) |
| 76 | + if isinstance(self._model, Pipeline): |
| 77 | + self._original = self._model.model |
| 78 | + |
| 79 | + model = ipex.optimize( |
| 80 | + self._model.model, |
| 81 | + dtype=self._dtype, |
| 82 | + graph_mode=self._graph_mode, |
| 83 | + level="O1", |
| 84 | + auto_kernel_selection=True, |
| 85 | + ) |
| 86 | + |
| 87 | + # Enable automatic mixed precision (AMP) if we are going to target `bfloat16` |
| 88 | + with torch.cpu.amp.autocast(enabled=(self._dtype == torch.bfloat16)): |
| 89 | + # Patching model with the new one |
| 90 | + self._model.model = _ModelFallbackWrapper(model, self._original) |
| 91 | + return self._model |
| 92 | + else: |
| 93 | + self._original = self._model |
| 94 | + model = ipex.optimize( |
| 95 | + self._model, |
| 96 | + dtype=self._dtype, |
| 97 | + graph_mode=self._graph_mode, |
| 98 | + level="O1", |
| 99 | + auto_kernel_selection=True, |
| 100 | + ) |
| 101 | + |
| 102 | + # Enable automatic mixed precision (AMP) if we are going to target `bfloat16` |
| 103 | + with torch.cpu.amp.autocast(enabled=(self._dtype == torch.bfloat16)): |
| 104 | + return model |
| 105 | + |
| 106 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 107 | + self._model = self._original |
0 commit comments