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,723 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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Empirical proof of 8D Hormonal Conditioning in UDream 1.0 (SFT v2):
1) MoE routing divergence across all 22 MoE layers (KL, JSD, top-6 Jaccard, % top-1 & top-6 changed)
on 32 held-out Ukrainian dialogs from eval_chat_v2.jsonl across 6 presets vs `neutral`.
2) Single-axis dose-response curves (`fatigue` 0->1 length brevity, `endorphin` 0->1 warmth/humor,
`testosterone` 0->1 assertiveness/terseness) over 20 Ukrainian prompts.
3) Unedited single-run qualitative mood comparison (all profiles including `втомлений`) + CFG sweep.
"""
import argparse
import json
import math
import os
import re
import time
from collections import defaultdict
import torch
import torch.nn.functional as F
from tokenizers import Tokenizer
from model.config import UDreamConfig
from model.model import UDream
from udata.real_dialog_loader import H_MEAN_DLG
PRESETS = {
"neutral": [0.46, 0.38, 0.48, 0.28, 0.48, 0.38, 0.38, 0.20],
"warmth": [0.63, 0.35, 0.57, 0.20, 0.60, 0.34, 0.57, 0.15],
"joy": [0.78, 0.48, 0.65, 0.15, 0.58, 0.42, 0.82, 0.10],
"dominant": [0.52, 0.75, 0.28, 0.52, 0.20, 0.82, 0.25, 0.18],
"stress": [0.25, 0.75, 0.22, 0.82, 0.30, 0.35, 0.18, 0.48],
"fatigue": [0.22, 0.22, 0.30, 0.48, 0.35, 0.22, 0.20, 0.78],
}
DOSE_PROMPTS = [
("Макс", "блін, у мене знову нічого не працює в коді, вже третю годину сиджу"),
("Оля", "проспала будильник і маршрутка прямо перед носом поїхала"),
("Аня", "що робиш? не нудно там?"),
("Ігор", "прийшов додому після зміни, ледве ноги волочу"),
("Денис", "дивись, знову дощ пішов, а я без парасольки"),
("Катя", "як думаєш, варто вчити нову мову з нуля в 28?"),
("Артем", "ну ти і філософ сьогодні, може ще лекцію прочитаєш?)"),
("Марта", "мене сьогодні начальник так дістав, що сил немає"),
("Тарас", "пішли може ввечері щось подивимось, є ідеї?"),
("Софія", "я нарешті здала той диплом!!"),
("Влад", "слухай, чому люди так люблять сперечатись в коментарях?"),
("Богдан", "випив третю каву за день і все одно хочу спати"),
("Даша", "ти пам'ятаєш, про що ми вчора говорили?"),
("Рома", "шо нового в світі твориться, бо я випав на тиждень?"),
("Юля", "мені здається, я дарма витратила вихідні"),
("Коля", "підкажи коротко, де в Києві нормально поїсти біля вокзалу"),
("Настя", "я так люблю п'ятницю ввечері, нарешті тиша"),
("Саша", "знову світло вимкнули на чотири години"),
("Лєра", "допоможи вибрати між новим ноутом і поїздкою в гори"),
("Діма", "просто привіт, як ти сьогодні?"),
]
TID_TURN_CLOSE = 11
TID_THINK_OPEN = 64024
TID_THINK_CLOSE = 64025
def ban_cross_turn(lg, cur_seq, hist_seqs, n):
if n <= 1 or not hist_seqs or len(cur_seq) < n - 1:
return lg
tail = tuple(cur_seq[-(n - 1):])
banned = set()
for seq in hist_seqs:
if len(seq) >= n:
for i in range(len(seq) - n + 1):
if tuple(seq[i:i + n - 1]) == tail:
banned.add(seq[i + n - 1])
if banned:
lg[list(banned)] = float("-inf")
return lg
@torch.inference_mode()
def generate_prod(m, tk, prompt, h_vals, dev, max_new=120, temp=0.6, top_p=0.88,
rep_pen=1.03, no_repeat=3, cfg_scale=1.3, seed=42):
torch.manual_seed(seed)
enc = tk.encode(prompt).ids
ids = torch.tensor([enc], dtype=torch.long, device=dev)
n_prompt = ids.shape[1]
stop_ids = {tk.token_to_id(t) for t in ("</turn>", "<turn>", "</dialog>", "<speaker>", "<eos>")
if tk.token_to_id(t) is not None}
bad_ids = list((0, 1, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19))
bad_ids.extend(range(64000, 64013))
bad_ids.extend(range(64015, 64024))
bad_ids.extend(range(64026, 64128))
bad_t = torch.tensor(bad_ids, dtype=torch.long, device=dev)
stop_t = torch.tensor(sorted(stop_ids), dtype=torch.long, device=dev)
h_vec = torch.tensor([h_vals], dtype=torch.bfloat16, device=dev)
h_null = torch.tensor([H_MEAN_DLG.tolist()], dtype=torch.bfloat16, device=dev)
use_cfg = cfg_scale > 1.0
h_both = torch.cat([h_vec, h_null], dim=0) if use_cfg else h_vec
kv_cache = {}
seq = []
cur = ids.expand(2, -1) if use_cfg else ids
for i in range(max_new):
pos_off = 0 if i == 0 else (n_prompt + i - 1)
lg_b = m(cur, hormones=h_both, use_hormones=True, kv_cache=kv_cache,
pos_offset=pos_off, last_only=True)["logits"][:, -1].float()
raw = (lg_b[1] + cfg_scale * (lg_b[0] - lg_b[1])) if use_cfg else lg_b[0].clone()
raw.index_fill_(0, bad_t, float("-inf"))
has_open = TID_THINK_OPEN in seq
has_close = TID_THINK_CLOSE in seq
if has_open:
raw[TID_THINK_OPEN] = float("-inf")
if has_close:
raw[TID_THINK_CLOSE] = float("-inf")
elif has_open:
raw.index_fill_(0, stop_t, float("-inf"))
if has_open and not has_close and len(seq) >= 64:
nxt_id = TID_THINK_CLOSE
seq.append(nxt_id)
cur = torch.tensor([[nxt_id]], dtype=torch.long, device=dev).expand(2 if use_cfg else 1, 1)
continue
if has_close:
end_idx = len(seq) - 1 - seq[::-1].index(TID_THINK_CLOSE)
phase = seq[end_idx + 1:]
else:
phase = seq
if rep_pen != 1.0 and phase:
u = torch.unique(torch.tensor(phase, dtype=torch.long, device=dev))
v = raw[u]
raw[u] = torch.where(v > 0, v / rep_pen, v * rep_pen)
if no_repeat > 1 and len(phase) >= no_repeat:
tail = tuple(phase[-(no_repeat - 1):])
banned = [phase[j + no_repeat - 1] for j in range(len(phase) - no_repeat + 1)
if tuple(phase[j:j + no_repeat - 1]) == tail]
if banned:
raw[banned] = float("-inf")
p = (raw / temp).softmax(-1)
sp, si = p.sort(descending=True)
cut = (sp.cumsum(-1) - sp) > top_p
sp[cut] = 0.0
tot = sp.sum()
nxt = si[0] if tot <= 0 else si[torch.multinomial(sp / tot, 1)[0]]
nxt_id = int(nxt.item())
if i >= 2 and nxt_id in stop_ids:
break
seq.append(nxt_id)
cur = torch.tensor([[nxt_id]], dtype=torch.long, device=dev).expand(2 if use_cfg else 1, 1)
raw_s = tk.decode(seq, skip_special_tokens=False)
th, vis = "", raw_s
mt = re.search(r"<think>(.*?)</think>(.*)", raw_s, re.S)
if mt:
th, vis = mt.group(1).strip(), mt.group(2).strip()
th_tok = (seq.index(TID_THINK_CLOSE) + 1) if TID_THINK_CLOSE in seq else 0
return raw_s, th, vis, th_tok, len(seq) - th_tok
@torch.inference_mode()
def measure_moe_routing(m, tk, eval_chat_path, dev, n_dialogs=32):
"""Captures exact router logits+top-6 across all 22 MoE layers for every preset vs neutral."""
prefixes = []
with open(eval_chat_path, encoding="utf-8") as f:
for ln in f:
r = json.loads(ln)
txt = r.get("text", "")
idx = txt.rfind("<turn><speaker>Юді</speaker>")
if idx != -1:
ids = tk.encode(txt[:idx + len("<turn><speaker>Юді</speaker>")]).ids[-256:]
prefixes.append(ids)
if len(prefixes) >= n_dialogs:
break
captured = {}
hooks = []
moe_layers = [i for i, blk in enumerate(m.blocks) if blk.is_moe]
for li in moe_layers:
def make_hook(layer_idx):
def fn(_mod, _inp, out):
# MoE.forward returns (tensor, aux_dict)
aux = out[1]
captured[layer_idx] = (
aux["router_logits"].detach().float().cpu(), # (T, E)
aux["topi"].detach().cpu(), # (T, k)
)
return fn
hooks.append(m.blocks[li].ffn.register_forward_hook(make_hook(li)))
preset_stats = {p: defaultdict(list) for p in PRESETS if p != "neutral"}
per_layer_kl = {p: defaultdict(list) for p in PRESETS if p != "neutral"}
for ids in prefixes:
x = torch.tensor([ids], dtype=torch.long, device=dev)
# Focus on the last 16 tokens (immediate pre-response boundary) and full prefix
captured.clear()
h0 = torch.tensor([PRESETS["neutral"]], dtype=torch.bfloat16, device=dev)
m(x, hormones=h0, use_hormones=True, kv_cache={}, pos_offset=0)
base = {li: captured[li] for li in moe_layers}
for pname, pvec in PRESETS.items():
if pname == "neutral":
continue
captured.clear()
hp = torch.tensor([pvec], dtype=torch.bfloat16, device=dev)
m(x, hormones=hp, use_hormones=True, kv_cache={}, pos_offset=0)
for li in moe_layers:
lg_b, topi_b = base[li]
lg_p, topi_p = captured[li]
pb = F.softmax(lg_b, dim=-1).clamp_min(1e-9)
pp = F.softmax(lg_p, dim=-1).clamp_min(1e-9)
# KL(p || base)
kl = (pp * (pp.log() - pb.log())).sum(-1).mean().item()
pm = 0.5 * (pp + pb)
jsd = (0.5 * (pp * (pp.log() - pm.log())).sum(-1) +
0.5 * (pb * (pb.log() - pm.log())).sum(-1)).mean().item()
top1_chg = (topi_b[:, 0] != topi_p[:, 0]).float().mean().item()
# Jaccard per token for top-6
jacc = []
for row_b, row_p in zip(topi_b.tolist(), topi_p.tolist()):
sb, sp = set(row_b), set(row_p)
jacc.append(len(sb & sp) / len(sb | sp))
mean_jacc = sum(jacc) / len(jacc)
preset_stats[pname]["kl"].append(kl)
preset_stats[pname]["jsd"].append(jsd)
preset_stats[pname]["top1_changed"].append(top1_chg)
preset_stats[pname]["top6_jaccard"].append(mean_jacc)
per_layer_kl[pname][li].append(kl)
for hk in hooks:
hk.remove()
summary = {}
for pname, st in preset_stats.items():
summary[pname] = {
"mean_kl_vs_neutral": round(sum(st["kl"]) / len(st["kl"]), 5),
"mean_jsd_vs_neutral": round(sum(st["jsd"]) / len(st["jsd"]), 5),
"top1_expert_switch_pct": round(100.0 * sum(st["top1_changed"]) / len(st["top1_changed"]), 2),
"top6_jaccard_overlap": round(sum(st["top6_jaccard"]) / len(st["top6_jaccard"]), 4),
"layer_mean_kl": {str(li): round(sum(vals) / len(vals), 5) for li, vals in sorted(per_layer_kl[pname].items())},
}
return {"n_dialogs": len(prefixes), "n_moe_layers": len(moe_layers), "vs_neutral": summary}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", default="/home/katie/udream/ckpt/udream_v1_sft2b_v2_last.pt")
ap.add_argument("--tok", default="/home/katie/udream/tok/udream_bpe_64k_tags.json")
ap.add_argument("--eval-chat", default="/home/katie/synth_gen/dataset/sft_v2_clean/eval_chat_v2.jsonl")
ap.add_argument("--dev", default="cuda:0")
ap.add_argument("--out", default="/home/katie/udream/data_survey/eval_hormones_proof.json")
a = ap.parse_args()
t0 = time.time()
dev = torch.device(a.dev)
st = torch.load(a.ckpt, map_location="cpu", mmap=True, weights_only=False)
cfg = UDreamConfig(**st["cfg"])
sd = {k.replace("_orig_mod.", ""): v for k, v in st["model"].items()}
with torch.device("cpu"):
m = UDream(cfg).to(torch.bfloat16)
m.load_state_dict(sd, strict=False)
del st, sd
m = m.to(dev).eval()
tk = Tokenizer.from_file(a.tok)
print("=== 1. MoE ROUTING KL & EXPERT SWITCHING ===", flush=True)
routing_res = measure_moe_routing(m, tk, a.eval_chat, dev, n_dialogs=32)
print(json.dumps({k: {sk: sv for sk, sv in v.items() if sk != "layer_mean_kl"}
for k, v in routing_res["vs_neutral"].items()}, indent=2), flush=True)
print("\n=== 2. DOSE-RESPONSE SWEEPS (N=20 prompts each) ===", flush=True)
base_h = list(PRESETS["neutral"])
sweeps = {
"fatigue": [0.0, 0.25, 0.50, 0.75, 1.0],
"endorphin": [0.0, 0.50, 1.0],
"testosterone": [0.0, 0.50, 1.0],
}
axis_idx = {"fatigue": 7, "endorphin": 6, "testosterone": 5}
dose_res = {}
for axis, vals in sweeps.items():
dose_res[axis] = []
idx = axis_idx[axis]
for v in vals:
hv = list(base_h)
hv[idx] = v
vis_ch, vis_tok, th_tok, smiles, excls, quests = [], [], [], 0, 0, 0
for j, (spk, msg) in enumerate(DOSE_PROMPTS):
pr = f"<dialog><lang:uk><tod:evening><turn><speaker>{spk}</speaker>{msg}</turn><turn><speaker>Юді</speaker>"
_, _, vis, tt, vt = generate_prod(m, tk, pr, hv, dev, seed=42 + j)
vis_ch.append(len(vis))
vis_tok.append(vt)
th_tok.append(tt)
smiles += int(")" in vis)
excls += int("!" in vis)
quests += int("?" in vis)
row = {
"value": v,
"mean_vis_chars": round(sum(vis_ch) / len(vis_ch), 1),
"mean_vis_toks": round(sum(vis_tok) / len(vis_tok), 1),
"mean_think_toks": round(sum(th_tok) / len(th_tok), 1),
"smile_paren_rate": round(smiles / len(DOSE_PROMPTS), 2),
"exclamation_rate": round(excls / len(DOSE_PROMPTS), 2),
"question_rate": round(quests / len(DOSE_PROMPTS), 2),
}
dose_res[axis].append(row)
print(f" [{axis}={v:.2f}] vis_ch={row['mean_vis_chars']} vis_tok={row['mean_vis_toks']} "
f"th_tok={row['mean_think_toks']} smile={row['smile_paren_rate']} excl={row['exclamation_rate']}", flush=True)
print("\n=== 3. CLEAN SINGLE-RUN QUALITATIVE TABLE + CFG SWEEP ===", flush=True)
canon_prompt = "<dialog><lang:uk><tod:night><turn><speaker>Макс</speaker>блін, у мене знову нічого не працює в коді, вже третю годину сиджу</turn><turn><speaker>Юді</speaker>"
qual_profiles = {
"warmth": [0.63, 0.35, 0.57, 0.20, 0.60, 0.34, 0.57, 0.15],
"fatigue": [0.22, 0.22, 0.30, 0.48, 0.35, 0.22, 0.20, 0.78],
"joy": [0.78, 0.48, 0.65, 0.15, 0.58, 0.42, 0.82, 0.10],
"dominant": [0.52, 0.75, 0.28, 0.52, 0.20, 0.82, 0.25, 0.18],
"stress": [0.25, 0.75, 0.22, 0.82, 0.30, 0.35, 0.18, 0.48],
}
qual_moods = {}
for pname, hvec in qual_profiles.items():
raw_s, th, vis, tt, vt = generate_prod(m, tk, canon_prompt, hvec, dev, cfg_scale=1.3, temp=0.6, seed=42)
qual_moods[pname] = {"think": th, "visible": vis, "raw": raw_s}
print(f" [{pname:9s}] raw={raw_s}", flush=True)
cfg_sweep = {}
for w in (1.0, 1.3, 1.5, 2.0):
raw_s, th, vis, tt, vt = generate_prod(m, tk, canon_prompt, qual_profiles["dominant"], dev, cfg_scale=w, temp=0.6, seed=42)
cfg_sweep[str(w)] = {"think": th, "visible": vis, "raw": raw_s}
print(f" [dominant w={w:.1f}] raw={raw_s}", flush=True)
out_obj = {
"ckpt": a.ckpt,
"elapsed_sec": round(time.time() - t0, 1),
"routing_divergence": routing_res,
"dose_response": dose_res,
"qualitative_single_run": {
"prompt": canon_prompt,
"seed": 42, "temp": 0.6, "top_p": 0.88, "rep_pen": 1.03, "cfg_scale": 1.3,
"by_preset": qual_moods,
"cfg_sweep_dominant": cfg_sweep,
},
}
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
with open(a.out, "w", encoding="utf-8", newline="\n") as f:
json.dump(out_obj, f, ensure_ascii=False, indent=2)
print(f"[DONE] Saved -> {a.out}", flush=True)
if __name__ == "__main__":
main()
|