File size: 4,218 Bytes
00ff9d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Storage dtypes of the public ``model.safetensors``: bfloat16 with FP32 islands.

Every tensor name in the file matches exactly one rule. The FP32 islands are
the tensors whose rounding would change results: norm affine weights (some
see a float32 residual stream), the velocity head, the text adapter's learned
tokens and tap statistics. The rest is bfloat16. The same
policy writes the file (``export_release.py``) and checks it on load; a
tensor stored in another dtype fails loading.
"""

from __future__ import annotations

import re
from enum import Enum

import torch

from .text_conditioning import TEXT_ADAPTER_KEY_MAP

DENOISER_PREFIX = "denoiser."
TEXT_ADAPTER_PREFIX = "text_adapter."


class StoredDType(Enum):
    """The dtype one public tensor is stored in."""

    BFLOAT16 = "bfloat16"
    FLOAT32 = "float32"

    @property
    def torch_dtype(self) -> torch.dtype:
        """The matching torch dtype."""

        match self:
            case StoredDType.BFLOAT16:
                return torch.bfloat16
            case StoredDType.FLOAT32:
                return torch.float32
            case _ as unreachable:
                raise RuntimeError(f"Unsupported stored dtype: {unreachable}")


_LAYER = r"denoiser\.(?:text_refiner|prefix|middle|suffix)_layers\.\d+\."
_NORMS = r"(?:attn_norm1|attn_norm2|mlp_norm1|mlp_norm2|attn\.q_norm|attn\.k_norm)"

_STORAGE_RULES: tuple[tuple[re.Pattern[str], StoredDType], ...] = (
    (re.compile(_LAYER + _NORMS + r"\.weight"), StoredDType.FLOAT32),
    (
        re.compile(
            _LAYER
            + r"(?:attn\.(?:qkv|proj_out)\.weight|mlp\.(?:up|down)\.(?:weight|bias))"
        ),
        StoredDType.BFLOAT16,
    ),
    (
        re.compile(r"denoiser\.(?:prefix|middle|suffix)_adaln\.\d+\.(?:weight|bias)"),
        StoredDType.BFLOAT16,
    ),
    (
        re.compile(
            r"denoiser\.(?:patch_embed|time_embed\.proj_in|time_embed\.proj_out"
            r"|tail_join\.adascale|tail_join\.proj|final_modulation)"
            r"\.(?:weight|bias)"
        ),
        StoredDType.BFLOAT16,
    ),
    (
        re.compile(r"denoiser\.tail_join\.(?:mask_token|dropped_skip_proj\.weight)"),
        StoredDType.BFLOAT16,
    ),
    (
        re.compile(r"denoiser\.(?:final_norm\.weight|velocity_head\.(?:weight|bias))"),
        StoredDType.FLOAT32,
    ),
)


def denoiser_storage_dtype(name: str) -> StoredDType:
    """Storage dtype of one public ``denoiser.*`` tensor.

    Raises:
        RuntimeError: If ``name`` matches no rule or several.
    """

    matches = {
        storage for pattern, storage in _STORAGE_RULES if pattern.fullmatch(name)
    }
    if len(matches) != 1:
        raise RuntimeError(
            f"Public tensor {name!r} matches storage rules "
            f"{sorted(storage.value for storage in matches)}; it needs exactly one"
        )
    return matches.pop()


# Storage of each training text adapter tensor; the public key of each is
# ``text_adapter.`` + ``TEXT_ADAPTER_KEY_MAP[training key]`` (text_conditioning).
_TEXT_ADAPTER_STORAGE: dict[str, StoredDType] = {
    "conditioning._encoder._proj_lo.weight": StoredDType.BFLOAT16,
    "conditioning._encoder._proj_mid.weight": StoredDType.BFLOAT16,
    "conditioning._encoder._proj_hi.weight": StoredDType.BFLOAT16,
    "conditioning._encoder._tap_statistics.mean": StoredDType.FLOAT32,
    "conditioning._encoder._tap_statistics.std": StoredDType.FLOAT32,
    "conditioning.learned_padding_tokens": StoredDType.FLOAT32,
    "conditioning.uncond_token": StoredDType.FLOAT32,
}


def text_adapter_storage_dtypes() -> dict[str, StoredDType]:
    """Storage dtype of every public text adapter tensor, keyed by its full
    public name (``text_adapter.<key>``).

    Raises:
        RuntimeError: If the adapter's key map and the storage rules differ.
    """

    if set(TEXT_ADAPTER_KEY_MAP) != set(_TEXT_ADAPTER_STORAGE):
        raise RuntimeError(
            "Text adapter keys and storage rules differ: "
            f"{sorted(set(TEXT_ADAPTER_KEY_MAP) ^ set(_TEXT_ADAPTER_STORAGE))}"
        )
    return {
        TEXT_ADAPTER_PREFIX + public: _TEXT_ADAPTER_STORAGE[internal]
        for internal, public in TEXT_ADAPTER_KEY_MAP.items()
    }