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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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# coding=utf-8
"""Standalone Hugging Face Transformers modeling file for UDream-1.0-Bi-Encode."""
import os
from typing import List, Optional, Sequence, Tuple, Union

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel
from transformers.modeling_outputs import BaseModelOutput

try:
    from .configuration_udream_bi import UDreamBiEncoderConfig
except ImportError:
    from configuration_udream_bi import UDreamBiEncoderConfig


class RMSNorm(nn.Module):
    def __init__(self, d: int, eps: float = 1e-5):
        super().__init__()
        self.w = nn.Parameter(torch.ones(d))
        self.eps = eps

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        dt = x.dtype
        xf = x.float()
        xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
        return (xf * self.w.float()).to(dt)


def build_rope(head_dim: int, seq: int, theta: float, device: torch.device, dtype: torch.dtype):
    inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
    t = torch.arange(seq, device=device).float()
    f = torch.outer(t, inv)
    return torch.cos(f).to(dtype), torch.sin(f).to(dtype)


def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    x1, x2 = x[..., 0::2], x[..., 1::2]
    o1 = x1 * cos - x2 * sin
    o2 = x1 * sin + x2 * cos
    return torch.stack((o1, o2), dim=-1).flatten(-2)


def _can_use_grouped_mm(x: torch.Tensor) -> bool:
    if os.environ.get("UDREAM_GROUPED_MM", "1") != "1":
        return False
    if not (x.is_cuda and hasattr(torch, "_grouped_mm") and x.dtype == torch.bfloat16):
        return False
    major, _ = torch.cuda.get_device_capability(x.device)
    return major >= 9


class BidirectionalAttention(nn.Module):
    def __init__(self, cfg: UDreamBiEncoderConfig, layer: int):
        super().__init__()
        self.cfg = cfg
        self.layer = layer
        self.is_global = cfg.is_global(layer)
        self.nh = cfg.n_heads
        self.nkv = cfg.n_kv_heads
        self.hd = cfg.head_dim
        d = cfg.d_model
        self.q = nn.Linear(d, self.nh * self.hd, bias=False)
        self.k = nn.Linear(d, self.nkv * self.hd, bias=False)
        self.v = nn.Linear(d, self.nkv * self.hd, bias=False)
        self.o = nn.Linear(self.nh * self.hd, d, bias=False)
        self.qn = RMSNorm(self.hd, cfg.rms_eps)
        self.kn = RMSNorm(self.hd, cfg.rms_eps)

    def forward(
        self,
        x: torch.Tensor,
        rope: Tuple[torch.Tensor, torch.Tensor],
        attention_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        B, T, _ = x.shape
        q = self.qn(self.q(x).view(B, T, self.nh, self.hd).transpose(1, 2))
        k = self.kn(self.k(x).view(B, T, self.nkv, self.hd).transpose(1, 2))
        v = self.v(x).view(B, T, self.nkv, self.hd).transpose(1, 2)
        if not self.is_global:
            cos, sin = rope
            q = apply_rope(q, cos, sin)
            k = apply_rope(k, cos, sin)

        rep = self.nh // self.nkv
        k_rep = k.repeat_interleave(rep, dim=1)
        v_rep = v.repeat_interleave(rep, dim=1)
        w = self.cfg.window

        valid_kv = attention_mask[:, :T].bool() if attention_mask is not None else None

        if self.is_global or T <= w:
            if valid_kv is None:
                o = F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=False)
            else:
                amask = valid_kv[:, None, None, :]
                empty = ~valid_kv.any(dim=-1)
                if empty.any():
                    amask = amask.clone()
                    amask[empty, :, :, 0] = True
                o = F.scaled_dot_product_attention(q, k_rep, v_rep, attn_mask=amask, is_causal=False)
        else:
            # Bidirectional sliding window |q - kv| < w for long sequences (T > 512)
            outs = []
            for cs in range(0, T, 512):
                ce = min(cs + 512, T)
                kv_lo = max(0, cs - (w - 1))
                kv_hi = min(T, ce + (w - 1))
                q_pos = torch.arange(cs, ce, device=q.device)[:, None]
                kv_pos = torch.arange(kv_lo, kv_hi, device=q.device)[None, :]
                amask = ((q_pos - kv_pos).abs() < w)[None, None, :, :]
                if valid_kv is not None:
                    amask = amask & valid_kv[:, kv_lo:kv_hi][:, None, None, :]
                    diag = (q_pos == kv_pos)[None, None, :, :]
                    amask = amask | diag
                outs.append(
                    F.scaled_dot_product_attention(
                        q[:, :, cs:ce, :], k_rep[:, :, kv_lo:kv_hi, :], v_rep[:, :, kv_lo:kv_hi, :],
                        attn_mask=amask, is_causal=False,
                    )
                )
            o = torch.cat(outs, dim=2)

        return self.o(o.transpose(1, 2).reshape(B, T, -1))


class SwiGLU(nn.Module):
    def __init__(self, d: int, dff: int):
        super().__init__()
        self.up = nn.Linear(d, dff, bias=False)
        self.gate = nn.Linear(d, dff, bias=False)
        self.down = nn.Linear(dff, d, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.down(F.silu(self.gate(x)) * self.up(x))


class MoE(nn.Module):
    def __init__(self, cfg: UDreamBiEncoderConfig):
        super().__init__()
        self.cfg = cfg
        d, E, dff = cfg.d_model, cfg.n_experts, cfg.expert_d_ff
        self.E = E
        self.k = getattr(cfg, "moe_top_k", getattr(cfg, "top_k", 6))
        self.router = nn.Linear(d, E, bias=False)
        self.w_up = nn.Parameter(torch.empty(E, d, dff))
        self.w_gate = nn.Parameter(torch.empty(E, d, dff))
        self.w_down = nn.Parameter(torch.empty(E, dff, d))
        self.shared = SwiGLU(d, cfg.shared_d_ff)
        self.h_router = nn.Linear(cfg.cond_dim, E, bias=False)

    def forward(self, x: torch.Tensor, cond: Optional[torch.Tensor]) -> torch.Tensor:
        B, T, d = x.shape
        xf = x.reshape(-1, d)
        logits = self.router(xf).float()
        if cond is not None:
            bias = self.h_router(cond.to(self.h_router.weight.dtype)).float()
            if bias.shape[1] == 1 and T > 1:
                bias = bias.expand(B, T, self.E)
            logits = logits + bias.reshape(-1, self.E)
        probs = logits.softmax(-1)
        topv, topi = probs.topk(self.k, dim=-1)
        topv = topv / topv.sum(-1, keepdim=True)

        N = xf.shape[0]
        flat_e = topi.reshape(-1)
        flat_w = topv.reshape(-1).to(xf.dtype)
        flat_t = torch.arange(N, device=xf.device).repeat_interleave(self.k)
        order = torch.argsort(flat_e)
        se, st, sw = flat_e[order], flat_t[order], flat_w[order]
        bounds = torch.searchsorted(se, torch.arange(self.E + 1, device=xf.device))

        out = torch.zeros_like(xf)
        if _can_use_grouped_mm(xf):
            xs = xf[st]
            offs = bounds[1:].to(torch.int32)
            hg = torch._grouped_mm(xs, self.w_gate, offs=offs)
            hu = torch._grouped_mm(xs, self.w_up, offs=offs)
            y = torch._grouped_mm(F.silu(hg) * hu, self.w_down, offs=offs)
            out.index_add_(0, st, y * sw.unsqueeze(-1))
        else:
            bl = bounds.tolist()
            for e in range(self.E):
                lo, hi = bl[e], bl[e + 1]
                if hi <= lo:
                    continue
                tk = st[lo:hi]
                h = xf[tk]
                y = (F.silu(h @ self.w_gate[e]) * (h @ self.w_up[e])) @ self.w_down[e]
                out.index_add_(0, tk, y * sw[lo:hi].unsqueeze(-1))

        return out.view(B, T, d) + self.shared(x)


class HormoneEncoder(nn.Module):
    def __init__(self, cfg: UDreamBiEncoderConfig):
        super().__init__()
        self.null = nn.Parameter(torch.zeros(cfg.n_hormones))
        self.net = nn.Sequential(
            nn.Linear(cfg.n_hormones, cfg.cond_dim),
            nn.SiLU(),
            nn.Linear(cfg.cond_dim, cfg.cond_dim),
        )

    def forward(self, h: Optional[torch.Tensor], B: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
        if h is None:
            h = self.null.to(device=device, dtype=dtype).expand(B, -1)
        else:
            h = h.to(device=device, dtype=dtype)
        return self.net(h)[:, None, :]


class FiLM(nn.Module):
    def __init__(self, cfg: UDreamBiEncoderConfig):
        super().__init__()
        self.proj = nn.Linear(cfg.cond_dim, 2 * cfg.d_model, bias=False)

    def forward(self, x: torch.Tensor, cond: Optional[torch.Tensor]) -> torch.Tensor:
        if cond is None:
            return x
        g, b = self.proj(cond.to(self.proj.weight.dtype)).chunk(2, dim=-1)
        return (x * (1 + g) + b).to(x.dtype)


class Block(nn.Module):
    def __init__(self, cfg: UDreamBiEncoderConfig, layer: int):
        super().__init__()
        self.is_moe = cfg.is_moe(layer)
        self.n1 = RMSNorm(cfg.d_model, cfg.rms_eps)
        self.attn = BidirectionalAttention(cfg, layer)
        self.n2 = RMSNorm(cfg.d_model, cfg.rms_eps)
        self.ffn = MoE(cfg) if self.is_moe else SwiGLU(cfg.d_model, cfg.dense_d_ff)
        self.film1 = FiLM(cfg)
        self.film2 = FiLM(cfg)

    def forward(
        self,
        x: torch.Tensor,
        cond: Optional[torch.Tensor],
        rope: Tuple[torch.Tensor, torch.Tensor],
        attention_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        x = x + self.attn(self.film1(self.n1(x), cond), rope, attention_mask=attention_mask)
        h = self.film2(self.n2(x), cond)
        y = self.ffn(h, cond) if self.is_moe else self.ffn(h)
        return x + y


class UDreamBiEncoderModel(PreTrainedModel):
    """Bidirectional Sparse MoE Text Encoder (4.14B total / 1.44B active, d_model=2048).

    Designed for text-to-image diffusion conditioning (e.g. Photon v2 / DiT) and
    bilingual Ukrainian <-> English semantic embeddings.
    """

    config_class = UDreamBiEncoderConfig
    base_model_prefix = "udream_bi_encoder"
    supports_gradient_checkpointing = False
    _no_split_modules = ["Block"]

    def __init__(self, config: UDreamBiEncoderConfig):
        super().__init__(config)
        self.cfg = config
        self.emb = nn.Embedding(config.vocab_size, config.d_model)
        self.hormones = HormoneEncoder(config)
        self.blocks = nn.ModuleList(Block(config, i) for i in range(config.n_layers))
        self.norm = RMSNorm(config.d_model, config.rms_eps)
        self._rope_cache = {}
        self.post_init()

    def get_input_embeddings(self):
        return self.emb

    def set_input_embeddings(self, value):
        self.emb = value

    def _get_rope(self, max_pos: int, device: torch.device, dtype: torch.dtype):
        cap = max(512, max_pos)
        key = (device, dtype)
        cached = self._rope_cache.get(key)
        if cached is None or cached[0].shape[0] < cap:
            self._rope_cache[key] = build_rope(self.cfg.head_dim, cap, self.cfg.rope_theta, device, dtype)
        return self._rope_cache[key]

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        hormones: Optional[torch.Tensor] = None,
        use_hormones: bool = True,
        **kwargs,
    ) -> Union[Tuple, BaseModelOutput]:
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        return_dict = True if return_dict is None else return_dict

        if inputs_embeds is not None:
            x = inputs_embeds
            B, T, _ = x.shape
        else:
            B, T = input_ids.shape
            x = self.emb(input_ids)

        if position_ids is None:
            cos_all, sin_all = self._get_rope(T, x.device, x.dtype)
            cos = cos_all[:T][None, None, :, :]
            sin = sin_all[:T][None, None, :, :]
        else:
            pos_safe = position_ids.clamp(min=0)
            max_pos = int(pos_safe.max().item()) + 1
            cos_all, sin_all = self._get_rope(max_pos, x.device, x.dtype)
            cos = cos_all[pos_safe][:, None, :, :]
            sin = sin_all[pos_safe][:, None, :, :]

        cond = self.hormones(hormones, B, x.device, x.dtype) if use_hormones else None

        all_hidden = (x,) if output_hidden_states else None
        for i, blk in enumerate(self.blocks):
            x = blk(x, cond, (cos, sin), attention_mask=attention_mask)
            if output_hidden_states and i < len(self.blocks) - 1:
                all_hidden = all_hidden + (x,)

        x = self.norm(x)
        if output_hidden_states:
            all_hidden = all_hidden + (x,)

        if not return_dict:
            return tuple(v for v in (x, all_hidden) if v is not None)
        return BaseModelOutput(last_hidden_state=x, hidden_states=all_hidden)

    @torch.inference_mode()
    def encode(
        self,
        prompts: Union[str, Sequence[str]],
        tokenizer,
        max_length: int = 256,
        layers: Sequence[int] = (-4, -3, -2),
        normalize_taps: bool = True,
        prepend_doc: bool = True,
        pool: Optional[str] = None,
    ):
        """Convenience encoder matching UDream-1.0-Bi-Encode training/T2I convention.

        Prepends `<doc>` (id=4) at position 0, runs bidirectional attention with exact
        padding mask, averages final-normed `layers` (default `(-4, -3, -2)`), and strips
        the `<doc>` prefix so 100% of prompt tokens are preserved.

        Args:
            prompts: String or list of strings.
            tokenizer: Matching `UDream/UDream-1.0-Bi-Encode` tokenizer.
            max_length: Max prompt tokens (excluding `<doc>`).
            layers: Block indices to average (negative indices follow Python convention,
                e.g. `(-4, -3, -2)` -> blocks 22, 23, 24; `(-1,)` -> final block 25).
            normalize_taps: Apply `self.norm` to each tapped layer before averaging.
            prepend_doc: Prepend `<doc>` token as trained, then strip it on output.
            pool: `None` -> `(token_states [B, L, 2048], mask [B, L])`;
                  `"mean"` -> L2-normalized pooled embeddings `[B, 2048]`.
        """
        single = isinstance(prompts, str)
        plist: List[str] = [prompts] if single else list(prompts)
        is_empty = [not p for p in plist]
        doc_id = self.cfg.doc_token_id
        pad_id = self.cfg.pad_token_id if self.cfg.pad_token_id is not None else 0
        pre = [doc_id] if (prepend_doc and doc_id is not None) else []
        n_pre = len(pre)

        seqs = []
        for p in plist:
            if not p:
                seqs.append(list(pre))
            else:
                tids = tokenizer.encode(p, add_special_tokens=False)[:max_length]
                seqs.append(list(pre) + tids)
        T = max(n_pre + 1, max((len(s) for s in seqs), default=n_pre + 1))
        B = len(plist)
        device = next(self.parameters()).device
        ids = torch.full((B, T), pad_id, dtype=torch.long, device=device)
        mask = torch.zeros(B, T, dtype=torch.bool, device=device)
        for i, s in enumerate(seqs):
            if s:
                ids[i, :len(s)] = torch.tensor(s, dtype=torch.long, device=device)
                mask[i, :len(s)] = True

        x = self.emb(ids)
        cos_all, sin_all = self._get_rope(T, x.device, x.dtype)
        rope = (cos_all[:T][None, None, :, :], sin_all[:T][None, None, :, :])
        cond = self.hormones(None, B, x.device, x.dtype)

        n_layers = len(self.blocks)
        tap_indices = sorted({i % n_layers for i in layers})
        max_li = max(tap_indices)
        taps = []
        for li in range(max_li + 1):
            x = self.blocks[li](x, cond, rope, attention_mask=mask)
            if li in tap_indices:
                taps.append((self.norm(x) if normalize_taps else x).float())
        h = torch.stack(taps).mean(0)

        if n_pre > 0:
            h, mask = h[:, n_pre:], mask[:, n_pre:]
        if h.shape[1] == 0:
            h = h.new_zeros(B, 1, self.cfg.d_model)
            mask = torch.zeros(B, 1, dtype=torch.bool, device=device)
        for i, empty in enumerate(is_empty):
            if empty:
                h[i].zero_()
                mask[i] = False

        if pool == "mean":
            mf = mask.float().unsqueeze(-1)
            pooled = (h * mf).sum(dim=1) / mf.sum(dim=1).clamp(min=1.0)
            pooled = F.normalize(pooled, dim=-1)
            return pooled[0] if single else pooled

        if single:
            return h[0], mask[0]
        return h, mask