Elffuss BraidHub

kikocis/SpatialLM public

main · 3.6 KiBRawPermalink
1import os
2import importlib.metadata
3import importlib.util
4from functools import lru_cache
5from typing import TYPE_CHECKING
6
7import torch
8from packaging import version
9from transformers.utils import (
10 is_torch_cuda_available,
11 is_torch_mps_available,
12 is_torch_npu_available,
13 is_torch_xpu_available,
14)
15from transformers.utils.versions import require_version
16
17from ..framework import logging
18
19if TYPE_CHECKING:
20 from packaging.version import Version
21
22logger = logging.get_logger(__name__)
23
24
25def has_length(dataset):
26 """
27 Checks if the dataset implements __len__() and it doesn't raise an error
28 """
29 try:
30 return len(dataset) is not None
31 except TypeError:
32 # TypeError: len() of unsized object
33 return False
34
35
36def is_env_enabled(env_var: str, default: str = "0") -> bool:
37 r"""Check if the environment variable is enabled."""
38 return os.getenv(env_var, default).lower() in ["true", "y", "1"]
39
40
41def check_version(requirement: str, mandatory: bool = False) -> None:
42 r"""Optionally check the package version."""
43 if is_env_enabled("DISABLE_VERSION_CHECK") and not mandatory:
44 logger.warning_rank0_once(
45 "Version checking has been disabled, may lead to unexpected behaviors."
46 )
47 return
48
49 if "gptmodel" in requirement or "autoawq" in requirement:
50 pip_command = f"pip install {requirement} --no-build-isolation"
51 else:
52 pip_command = f"pip install {requirement}"
53
54 if mandatory:
55 hint = f"To fix: run `{pip_command}`."
56 else:
57 hint = f"To fix: run `{pip_command}` or set `DISABLE_VERSION_CHECK=1` to skip this check."
58
59 require_version(requirement, hint)
60
61
62def count_parameters(model: "torch.nn.Module") -> tuple[int, int]:
63 r"""Return the number of trainable parameters and number of all parameters in the model."""
64 trainable_params, all_param = 0, 0
65 for param in model.parameters():
66 num_params = param.numel()
67
68 all_param += num_params
69 if param.requires_grad:
70 trainable_params += num_params
71
72 return trainable_params, all_param
73
74
75def _get_package_version(name: str) -> "Version":
76 try:
77 return version.parse(importlib.metadata.version(name))
78 except Exception:
79 return version.parse("0.0.0")
80
81
82@lru_cache
83def is_transformers_version_greater_than(content: str):
84 return _get_package_version("transformers") >= version.parse(content)
85
86
87def get_current_device() -> "torch.device":
88 r"""
89 Gets the current available device.
90 """
91 if is_torch_xpu_available():
92 device = "xpu:{}".format(os.environ.get("LOCAL_RANK", "0"))
93 elif is_torch_npu_available():
94 device = "npu:{}".format(os.environ.get("LOCAL_RANK", "0"))
95 elif is_torch_mps_available():
96 device = "mps:{}".format(os.environ.get("LOCAL_RANK", "0"))
97 elif is_torch_cuda_available():
98 device = "cuda:{}".format(os.environ.get("LOCAL_RANK", "0"))
99 else:
100 device = "cpu"
101
102 return torch.device(device)
103
104
105def get_device_count() -> int:
106 r"""Get the number of available devices."""
107 if is_torch_xpu_available():
108 return torch.xpu.device_count()
109 elif is_torch_npu_available():
110 return torch.npu.device_count()
111 elif is_torch_mps_available():
112 return torch.mps.device_count()
113 elif is_torch_cuda_available():
114 return torch.cuda.device_count()
115 else:
116 return 0
117
118
119def check_dependencies() -> None:
120 r"""
121 Checks the version of the required packages.
122 """
123 check_version("transformers>=4.41.2,<=4.46.1")
124 check_version("datasets>=2.16.0,<=3.6.0")
125 check_version("accelerate>=0.34.0,<=1.7.0")