Text Generation
Transformers
Safetensors
udream
Mixture of Experts
mixture-of-experts
ukrainian
nope
sliding-window-attention
from-scratch
custom_code
Instructions to use UDream/UDream-1.0-Base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use UDream/UDream-1.0-Base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="UDream/UDream-1.0-Base", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("UDream/UDream-1.0-Base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use UDream/UDream-1.0-Base with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "UDream/UDream-1.0-Base" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "UDream/UDream-1.0-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/UDream/UDream-1.0-Base
- SGLang
How to use UDream/UDream-1.0-Base with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "UDream/UDream-1.0-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "UDream/UDream-1.0-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "UDream/UDream-1.0-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "UDream/UDream-1.0-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use UDream/UDream-1.0-Base with Docker Model Runner:
docker model run hf.co/UDream/UDream-1.0-Base
File size: 16,377 Bytes
dc47fb0 | 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 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 | # coding=utf-8
"""Standalone Hugging Face Transformers modeling file for UDream 1.0."""
import os
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import GenerationMixin, PreTrainedModel
from transformers.cache_utils import Cache, DynamicCache
from transformers.modeling_outputs import CausalLMOutputWithPast
from .configuration_udream import UDreamConfig
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:
# x: (B, H, T, D); cos/sin: (B, 1, T, D//2) or (1, 1, T, D//2)
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)
class Attention(nn.Module):
def __init__(self, cfg: UDreamConfig, 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,
past_key_values: Optional[Cache] = 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)
if past_key_values is not None:
k_full, v_full = past_key_values.update(k, v, self.layer)
else:
k_full, v_full = k, v
S = k_full.shape[2]
prev_len = S - T
rep = self.nh // self.nkv
k_rep = k_full.repeat_interleave(rep, dim=1)
v_rep = v_full.repeat_interleave(rep, dim=1)
w = self.cfg.window
valid_kv = None
if attention_mask is not None:
# attention_mask shape: (B, S_mask), 1=keep, 0=pad
valid_kv = attention_mask[:, :S].bool()
if T == 1 and prev_len > 0:
kv_lo = 0 if self.is_global else max(0, S - w)
k_a = k_rep[:, :, kv_lo:S, :]
v_a = v_rep[:, :, kv_lo:S, :]
if valid_kv is not None:
m = valid_kv[:, kv_lo:S][:, None, None, :]
m = m & torch.ones((B, 1, 1, S - kv_lo), dtype=torch.bool, device=q.device)
# Guard against completely masked rows
empty = ~m.any(dim=-1, keepdim=True)
if empty.any():
m = m.clone()
m[empty.expand_as(m)] = True
o = F.scaled_dot_product_attention(q, k_a, v_a, attn_mask=m)
else:
o = F.scaled_dot_product_attention(q, k_a, v_a, is_causal=False)
elif self.is_global and prev_len == 0 and valid_kv is None:
o = F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=(T > 1))
elif self.is_global:
q_pos = torch.arange(prev_len, S, device=q.device)[:, None]
kv_pos = torch.arange(S, device=q.device)[None, :]
amask = (q_pos >= kv_pos)[None, None, :, :]
if valid_kv is not None:
amask = amask & valid_kv[:, None, None, :]
# Keep diagonal unmasked so padded queries never produce NaN
diag = (q_pos == kv_pos)[None, None, :, :]
amask = amask | diag
o = F.scaled_dot_product_attention(q, k_rep, v_rep, attn_mask=amask)
else:
# Sliding-window attention chunked in 512-token subchunks for exact SWA semantics
outs = []
for cs in range(0, T, 512):
ce = min(cs + 512, T)
q_lo, q_hi = prev_len + cs, prev_len + ce
kv_lo = max(0, q_lo - (w - 1))
kv_hi = q_hi
q_pos = torch.arange(q_lo, q_hi, device=q.device)[:, None]
kv_pos = torch.arange(kv_lo, kv_hi, device=q.device)[None, :]
amask = ((q_pos >= kv_pos) & ((q_pos - kv_pos) < 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
)
)
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))
USE_GROUPED_MM = os.environ.get("UDREAM_GROUPED_MM", "1") == "1" and hasattr(torch, "_grouped_mm")
class MoE(nn.Module):
def __init__(self, cfg: UDreamConfig):
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.view(-1, d)
logits = self.router(xf).float()
if cond is not None:
logits = (
logits.view(B, T, self.E) + self.h_router(cond.to(self.h_router.weight.dtype)).float()
).view(-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 USE_GROUPED_MM and xf.is_cuda:
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: UDreamConfig):
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:
w_dt = self.net[0].weight.dtype
if h is None:
h = self.null.to(device=device, dtype=w_dt).expand(B, -1)
c = self.net(h.to(device=device, dtype=w_dt)).to(dtype)
return c[:, None, :] if c.ndim == 2 else c
class FiLM(nn.Module):
def __init__(self, cfg: UDreamConfig):
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: UDreamConfig, layer: int):
super().__init__()
self.cfg = cfg
self.layer = layer
self.is_moe = cfg.is_moe(layer)
self.n1 = RMSNorm(cfg.d_model, cfg.rms_eps)
self.attn = Attention(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)
self.drop = nn.Dropout(cfg.dropout) if cfg.dropout > 0 else nn.Identity()
def forward(
self,
x: torch.Tensor,
cond: Optional[torch.Tensor],
rope: Tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
) -> torch.Tensor:
x = x + self.drop(
self.attn(self.film1(self.n1(x), cond), rope, attention_mask=attention_mask, past_key_values=past_key_values)
)
h = self.film2(self.n2(x), cond)
y = self.ffn(h, cond) if self.is_moe else self.ffn(h)
return x + self.drop(y)
class UDreamForCausalLM(PreTrainedModel, GenerationMixin):
config_class = UDreamConfig
_tied_weights_keys = {"head.weight": "emb.weight"}
supports_gradient_checkpointing = False
def __init__(self, config: UDreamConfig):
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.head = nn.Linear(config.d_model, config.vocab_size, bias=False)
self.h_logit_a = nn.Linear(config.cond_dim, 64, bias=False)
self.h_logit_b = nn.Linear(64, config.vocab_size, bias=False)
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_output_embeddings(self):
return self.head
def set_output_embeddings(self, new_embeddings):
self.head = new_embeddings
def _get_rope(self, max_pos: int, device: torch.device, dtype: torch.dtype):
# Cache cos/sin tables up to at least 2048 tokens for speed
cap = max(2048, 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 prepare_inputs_for_generation(
self,
input_ids: torch.LongTensor,
past_key_values: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
):
model_inputs = super().prepare_inputs_for_generation(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
cache_position=cache_position,
**kwargs,
)
if "hormones" in kwargs:
model_inputs["hormones"] = kwargs["hormones"]
if "use_hormones" in kwargs:
model_inputs["use_hormones"] = kwargs["use_hormones"]
return model_inputs
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
hormones: Optional[torch.Tensor] = None,
use_hormones: bool = True,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs,
) -> CausalLMOutputWithPast:
if inputs_embeds is not None:
x = inputs_embeds
B, T, _ = x.shape
else:
B, T = input_ids.shape
x = self.emb(input_ids)
use_cache = self.config.use_cache if use_cache is None else use_cache
if use_cache and past_key_values is None:
past_key_values = DynamicCache()
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
if position_ids is None:
max_pos = past_len + T
cos_all, sin_all = self._get_rope(max_pos, x.device, x.dtype)
cos = cos_all[past_len:past_len + T][None, None, :, :]
sin = sin_all[past_len:past_len + 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
for blk in self.blocks:
x = blk(
x,
cond,
(cos, sin),
attention_mask=attention_mask,
past_key_values=past_key_values if use_cache else None,
)
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
if labels is None and logits_to_keep != 0:
x = x[:, slice_indices, :]
if cond is not None and cond.shape[1] > 1:
cond = cond[:, slice_indices, :]
x = self.norm(x)
logits = self.head(x)
if cond is not None:
logits = logits + self.h_logit_b(self.h_logit_a(cond.to(self.h_logit_a.weight.dtype))).to(logits.dtype)
loss = None
if labels is not None:
shift_logits = logits[:, :-1, :].contiguous()
shift_labels = labels[:, 1:].contiguous()
loss = F.cross_entropy(
shift_logits.view(-1, self.cfg.vocab_size).float(),
shift_labels.view(-1),
ignore_index=-100,
)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=past_key_values if use_cache else None,
)
|