File size: 10,480 Bytes
ceac1e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""sigma_core.py — SigMa positional-encoding core, EXTRACTED VERBATIM from
github.com/bxuanz/SigMa flux/transformer_flux.py (ICML 2026 paper 47JZSOkw5C).

Only the diffusers-independent RoPE/SigMa math is copied here so it runs without
the repo's heavy diffusers/transformers imports (which clash with the local
huggingface-hub version). No logic is modified. Line provenance in transformer_flux.py:
  get_adaptive_scale        L89-111
  find_correction_factor    L534-535
  find_correction_range     L538-544
  linear_ramp_mask          L547-553
  find_newbase_ntk          L556-560
  get_1d_rotary_pos_embed   L568-685
  FluxPosEmbed              L687-776
"""
import math
import torch
import torch.nn as nn
import numpy as np
from typing import List, Union

def get_adaptive_scale(t: float, scale_factor: float) -> float:
    """
    Logit-space SigMa scheduler:
    mu_d(t) = sigmoid(gamma_d * (logit(t) - logit(t_c,d))).
    """
    t_center = 1.0 / scale_factor
    gamma_d = math.sqrt(scale_factor)

    # logit(t) is defined on (0, 1); Flux can pass t=1 at the first step.
    eps = 1e-6
    t = min(max(t, eps), 1.0 - eps)
    t_center = min(max(t_center, eps), 1.0 - eps)

    def logit(value: float) -> float:
        return math.log(value / (1.0 - value))

    # 注意:Flux 中 t=1 是噪声,t=0 是图。
    # 当 t > t_center (早期),x > 0 -> alpha -> 1 (使用 NTK/YaRN)
    # 当 t < t_center (晚期),x < 0 -> alpha -> 0 (回归 Base 以获得锐利纹理)
    x = gamma_d * (logit(t) - logit(t_center))
    alpha = 1 / (1 + math.exp(-x))

    return alpha

def find_correction_factor(num_rotations, dim, base, max_position_embeddings):
    return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) #Inverse dim formula to find number of rotations

def find_correction_range(low_ratio, high_ratio, dim, base, ori_max_pe_len):
    """
    Find the correction range for NTK-by-parts interpolation.
    """
    low = np.floor(find_correction_factor(low_ratio, dim, base, ori_max_pe_len))
    high = np.ceil(find_correction_factor(high_ratio, dim, base, ori_max_pe_len))
    return max(low, 0), min(high, dim-1) #Clamp values just in case

def linear_ramp_mask(min, max, dim):
    if min == max:
        max += 0.001 #Prevent singularity

    linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
    ramp_func = torch.clamp(linear_func, 0, 1)
    return ramp_func

def find_newbase_ntk(dim, base, scale):
    """
    Calculate the new base for NTK-aware scaling.
    """
    return base * (scale ** (dim / (dim - 2)))

def get_1d_rotary_pos_embed(
    dim: int,
    pos: Union[np.ndarray, int],
    theta: float = 10000.0,
    use_real=False,
    linear_factor=1.0,
    ntk_factor=1.0,
    repeat_interleave_real=True,
    freqs_dtype=torch.float32,
    yarn=False,
    max_pe_len=None,
    ori_max_pe_len=64, # [重要] 听你的,保持 64 不动!这是画质的基石。
    sigma=False,
    current_timestep=1.0,
    gamma_factor=1.0,
):
    assert dim % 2 == 0

    if isinstance(pos, int):
        pos = torch.arange(pos)
    if isinstance(pos, np.ndarray):
        pos = torch.from_numpy(pos)

    device = pos.device

    # 这里的 scale 用于计算 RoPE 频率,必须基于 ori_max_pe_len=64
    if yarn and max_pe_len is not None and max_pe_len > ori_max_pe_len:
        if not isinstance(max_pe_len, torch.Tensor):
            max_pe_len = torch.tensor(max_pe_len, dtype=freqs_dtype, device=device)

        # [Track 1: 几何缩放] 
        # 保持 64 基准,scale 约为 64.0 (4096/64)
        # 这一步保证了图像质量不下降
        scale = torch.clamp_min(max_pe_len / ori_max_pe_len, 1.0)
        scale_val = scale.item() 

        # YaRN 默认参数
        beta_0 = 1.25
        beta_1 = 0.75
        gamma_0 = 16
        gamma_1 = 2

        freqs_base = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim))

        # 这里的 freqs_linear 使用 Base-64 的 scale,保证坐标系正确
        freqs_linear = 1.0 / torch.einsum(
            '..., f -> ... f',
            scale,
            (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim))
        )

        new_base = find_newbase_ntk(dim, theta, scale)
        if new_base.dim() > 0:
            new_base = new_base.view(-1, 1)
        freqs_ntk = 1.0 / torch.pow(
            new_base,
            (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim)
        )
        if freqs_ntk.dim() > 1:
            freqs_ntk = freqs_ntk.squeeze()

        # -----------------------------------------------------------
        # [SigMa core logic]
        # -----------------------------------------------------------
        if sigma:
            adaptive_alpha = get_adaptive_scale(current_timestep, scale_val)
            beta_0 = beta_0 * adaptive_alpha
            beta_1 = beta_1 * adaptive_alpha
        
        low, high = find_correction_range(beta_0, beta_1, dim, theta, ori_max_pe_len)
        low = max(0, low)
        high = min(dim // 2, high)

        freqs_mask = (1 - linear_ramp_mask(low, high, dim // 2).to(device).to(freqs_dtype))
        freqs = freqs_linear * (1 - freqs_mask) + freqs_ntk * freqs_mask

        if sigma:
            gamma_0 = gamma_0 * adaptive_alpha
            gamma_1 = gamma_1 * adaptive_alpha

        low, high = find_correction_range(gamma_0, gamma_1, dim, theta, ori_max_pe_len)
        low = max(0, low)
        high = min(dim // 2, high)

        freqs_mask = (1 - linear_ramp_mask(low, high, dim // 2).to(device).to(freqs_dtype))
        freqs = freqs * (1 - freqs_mask) + freqs_base * freqs_mask

    else:
        theta_ntk = theta * ntk_factor
        freqs = 1.0 / (theta_ntk ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim)) / linear_factor

    freqs = torch.outer(pos, freqs)

    is_npu = freqs.device.type == "npu"
    if is_npu:
        freqs = freqs.float()
    if use_real and repeat_interleave_real:
        freqs_cos = freqs.cos().repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2).float()
        freqs_sin = freqs.sin().repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2).float()

        # MScale 逻辑
        if yarn and max_pe_len is not None and max_pe_len > ori_max_pe_len:
            scale_factor_tensor = scale if isinstance(scale, torch.Tensor) else torch.tensor(scale)

            # MScale 这里的公式 0.1 * ln(scale)
            target_mscale = 0.1 * torch.log(scale_factor_tensor) + 1.0

            if sigma:
                adaptive_alpha = get_adaptive_scale(current_timestep, scale_val)
                mscale = (target_mscale - 1.0) * adaptive_alpha + 1.0
            else:
                mscale = target_mscale

            mscale = mscale.to(freqs_cos.device)
            freqs_cos = freqs_cos * mscale
            freqs_sin = freqs_sin * mscale

        return freqs_cos, freqs_sin

class FluxPosEmbed(nn.Module):
    def __init__(
            self,
            theta: int,
            axes_dim: List[int],
            method: str = 'yarn',
            sigma: bool = True,
            gamma_factor: float = 1,
    ):
        super().__init__()
        self.theta = theta
        self.axes_dim = axes_dim
        self.base_resolution = 1024
        self.patch_size = 16
        self.base_patches = self.base_resolution // self.patch_size
        self.method = method
        self.sigma = sigma if method != 'base' else False
        self.current_timestep = 1.0
        self.gamma_factor = gamma_factor

    def set_timestep(self, timestep: float):
        """Set current timestep for SigMa."""
        self.current_timestep = timestep

    def forward(self, ids: torch.Tensor) -> torch.Tensor:
        n_axes = ids.shape[-1]
        cos_out = []
        sin_out = []
        pos = ids.float()
        is_mps = ids.device.type == "mps"
        is_npu = ids.device.type == "npu"
        freqs_dtype = torch.float32 if (is_mps or is_npu) else torch.float64

        for i in range(n_axes):
            common_kwargs = {
                'dim': self.axes_dim[i],
                'pos': pos[:, i],
                'theta': self.theta,
                'repeat_interleave_real': True,
                'use_real': True,
                'freqs_dtype': freqs_dtype,
            }

            if i > 0:
                max_pos = pos[:, i].max().item()
                current_patches = max_pos + 1

                if self.method == 'yarn' and current_patches > self.base_patches:
                    max_pe_len = torch.tensor(current_patches, dtype=freqs_dtype, device=pos.device)
                    cos, sin = get_1d_rotary_pos_embed(
                        **common_kwargs,
                        yarn=True,
                        max_pe_len=max_pe_len,
                        ori_max_pe_len=self.base_patches,
                        sigma=self.sigma,
                        current_timestep=self.current_timestep,
                        gamma_factor=self.gamma_factor,
                    )

                elif self.method == 'ntk' and current_patches > self.base_patches:
                    # 计算基础 NTK 因子
                    scale_s = current_patches / self.base_patches
                    base_ntk = scale_s ** (self.axes_dim[i] / (self.axes_dim[i] - 2))
                    
                    # [SigMa core update: dynamic NTK]
                    if self.sigma:
                        # 1. 计算自适应强度 alpha
                        adaptive_alpha = get_adaptive_scale(self.current_timestep, scale_s)
                        
                        # 2. 应用强度
                        # [修改] 移除 2.0,回归 power 1.0 (adaptive_alpha)
                        ntk_factor = base_ntk ** (adaptive_alpha)
                    else:
                        ntk_factor = base_ntk
                    
                    ntk_factor = max(1.0, ntk_factor)

                    cos, sin = get_1d_rotary_pos_embed(**common_kwargs, ntk_factor=ntk_factor)

                else:
                    cos, sin = get_1d_rotary_pos_embed(**common_kwargs)
            else:
                cos, sin = get_1d_rotary_pos_embed(**common_kwargs)

            cos_out.append(cos)
            sin_out.append(sin)

        freqs_cos = torch.cat(cos_out, dim=-1).to(ids.device)
        freqs_sin = torch.cat(sin_out, dim=-1).to(ids.device)
        return freqs_cos, freqs_sin