Download scripts/sigma_core.py from kpshinnik/repro-sigma-bundle: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/datasets/kpshinnik/repro-sigma-bundle/resolve/main/scripts/sigma_core.py
- Command line
-
hf download hf://datasets/kpshinnik/repro-sigma-bundle/scripts/sigma_core.py
-
curl -L -o sigma_core.py https://huggingface.co/datasets/kpshinnik/repro-sigma-bundle/resolve/main/scripts/sigma_core.py
10.5 kB
| """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 | |