2023-08-28 09:59:11 +00:00
|
|
|
from contextlib import contextmanager
|
|
|
|
|
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def low_precision_init(target_dtype: torch.dtype = torch.float16):
|
|
|
|
dtype = torch.get_default_dtype()
|
|
|
|
try:
|
|
|
|
torch.set_default_dtype(target_dtype)
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
torch.set_default_dtype(dtype)
|
|
|
|
|
|
|
|
|
|
|
|
def get_model_numel(model: nn.Module) -> int:
|
|
|
|
return sum(p.numel() for p in model.parameters())
|
|
|
|
|
|
|
|
|
|
|
|
def format_numel_str(numel: int) -> str:
|
|
|
|
B = 1024**3
|
|
|
|
M = 1024**2
|
|
|
|
K = 1024
|
|
|
|
if numel >= B:
|
2023-09-19 06:20:26 +00:00
|
|
|
return f"{numel / B:.2f} B"
|
2023-08-28 09:59:11 +00:00
|
|
|
elif numel >= M:
|
2023-09-19 06:20:26 +00:00
|
|
|
return f"{numel / M:.2f} M"
|
2023-08-28 09:59:11 +00:00
|
|
|
elif numel >= K:
|
2023-09-19 06:20:26 +00:00
|
|
|
return f"{numel / K:.2f} K"
|
2023-08-28 09:59:11 +00:00
|
|
|
else:
|
2023-09-19 06:20:26 +00:00
|
|
|
return f"{numel}"
|