model_utils.py 713 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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:
26
        return f"{numel / B:.2f} B"
27
    elif numel >= M:
28
        return f"{numel / M:.2f} M"
29
    elif numel >= K:
30
        return f"{numel / K:.2f} K"
31
    else:
32
        return f"{numel}"