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
Download eval/eval_niah_clean.py from UDream/UDream-1.0-Base: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/UDream/UDream-1.0-Base/resolve/main/eval/eval_niah_clean.py
- Command line
-
hf download hf://UDream/UDream-1.0-Base/eval/eval_niah_clean.py
-
curl -L -o eval_niah_clean.py https://huggingface.co/UDream/UDream-1.0-Base/resolve/main/eval/eval_niah_clean.py
10.3 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """Clean Conversational NIAH (`dialog` mode) without substring / unclosed-<think> false positives. | |
| Fixes all bugs from eval_niah.py: | |
| 1. Uses 4 unambiguous needles (no 2-digit numbers like "14" that collide with times/indices). | |
| 2. Parses `<think>...</think>` via regex and checks `answer in visible_reply` ONLY. | |
| 3. Enforces production `max_think=64` (force-closing `</think>`) + `rep_pen=1.03`, `no_repeat=3`. | |
| 4. Logs separately: `visible_hit`, `think_hit`, `think_closed`, across N=4 needles x 4 depths x 4 lengths = 64 trials. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import time | |
| import torch | |
| from tokenizers import Tokenizer | |
| from model.config import UDreamConfig | |
| from model.model import UDream | |
| from eval_niah import load_haystack_turns, build_prompt | |
| from udata.real_dialog_loader import H_MEAN_DLG | |
| TID_THINK_OPEN = 64024 | |
| TID_THINK_CLOSE = 64025 | |
| CLEAN_NEEDLES = [ | |
| { | |
| "dialog_fact": "<turn><speaker>Оля</speaker>до речі, запиши про всяк випадок: код від камери схову на вокзалі 7492, і ключ лишила в баристи на ім'я Тимур</turn><turn><speaker>Юді</speaker><think>Оля назвала код камери схову 7492 та ім'я баристи Тимур.</think>ок, запам'ятав: 7492 і Тимур)</turn>", | |
| "dialog_q": "<turn><speaker>Оля</speaker>слухай, я вже біля вокзалу і вилетіло з голови, який там був код від камери схову?</turn><turn><speaker>Юді</speaker>", | |
| "answer": "7492", | |
| }, | |
| { | |
| "dialog_fact": "<turn><speaker>Макс</speaker>о, чуть не забув сказати: мій новий поїзд прибуває о 19:47 на колію 831, вагон дев'ятий</turn><turn><speaker>Юді</speaker><think>Макс сказав про поїзд: 19:47, колія 831.</think>прийняв, колія 831 о 19:47</turn>", | |
| "dialog_q": "<turn><speaker>Макс</speaker>нагадай швидко, на яку саме колію (номер з трьох цифр) прибуває мій поїзд?</turn><turn><speaker>Юді</speaker>", | |
| "answer": "831", | |
| }, | |
| { | |
| "dialog_fact": "<turn><speaker>Денис</speaker>слухай, пароль від нашого спільного архіву цього тижня — «Смарагд47», нікому не скидай</turn><turn><speaker>Юді</speaker><think>Денис дав пароль від архіву Смарагд47.</think>домовились, Смарагд47 тримаю в голові</turn>", | |
| "dialog_q": "<turn><speaker>Денис</speaker>вилетіло з голови, яке там було слово-пароль до архіву?</turn><turn><speaker>Юді</speaker>", | |
| "answer": "Смарагд47", | |
| }, | |
| { | |
| "dialog_fact": "<turn><speaker>Аня</speaker>мій новий номер комірки в поштоматі 5208, забери будь ласка посилку ввечері</turn><turn><speaker>Юді</speaker><think>Аня попросила запам'ятати комірку 5208.</think>окей, 5208, записав</turn>", | |
| "dialog_q": "<turn><speaker>Аня</speaker>ти пам'ятаєш, який номер комірки в поштоматі я казала?</turn><turn><speaker>Юді</speaker>", | |
| "answer": "5208", | |
| }, | |
| ] | |
| def chunked_prefill_and_gen_clean(m, tk, prompt_ids, h_vec, dev, max_new=96, max_think=64, | |
| rep_pen=1.03, no_repeat=3, chunk=512): | |
| kv_cache = {} | |
| T = len(prompt_ids) | |
| last_logits = None | |
| for s in range(0, T, chunk): | |
| part = torch.tensor([prompt_ids[s:s + chunk]], dtype=torch.long, device=dev) | |
| out = m(part, hormones=h_vec, use_hormones=True, kv_cache=kv_cache, pos_offset=s, last_only=(s + chunk >= T)) | |
| if s + chunk >= T: | |
| last_logits = out["logits"][0, -1].float() | |
| 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) | |
| gen = [] | |
| pos = T | |
| lg = last_logits | |
| for i in range(max_new): | |
| has_open = TID_THINK_OPEN in gen | |
| has_close = TID_THINK_CLOSE in gen | |
| if has_open and not has_close and len(gen) >= max_think: | |
| nxt = TID_THINK_CLOSE | |
| gen.append(nxt) | |
| nxt_t = torch.tensor([[nxt]], dtype=torch.long, device=dev) | |
| lg = m(nxt_t, hormones=h_vec, use_hormones=True, kv_cache=kv_cache, pos_offset=pos, last_only=True)["logits"][0, -1].float() | |
| pos += 1 | |
| continue | |
| lg = lg.clone() | |
| lg.index_fill_(0, bad_t, float("-inf")) | |
| if has_open: | |
| lg[TID_THINK_OPEN] = float("-inf") | |
| if has_close: | |
| lg[TID_THINK_CLOSE] = float("-inf") | |
| elif has_open: | |
| for sid in stop_ids: | |
| lg[sid] = float("-inf") | |
| if has_close: | |
| end_idx = len(gen) - 1 - gen[::-1].index(TID_THINK_CLOSE) | |
| phase = gen[end_idx + 1:] | |
| else: | |
| phase = gen | |
| if rep_pen != 1.0 and phase: | |
| u = torch.unique(torch.tensor(phase, dtype=torch.long, device=dev)) | |
| v = lg[u] | |
| lg[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: | |
| lg[banned] = float("-inf") | |
| nxt = int(lg.argmax().item()) | |
| if i >= 2 and nxt in stop_ids: | |
| break | |
| gen.append(nxt) | |
| nxt_t = torch.tensor([[nxt]], dtype=torch.long, device=dev) | |
| lg = m(nxt_t, hormones=h_vec, use_hormones=True, kv_cache=kv_cache, pos_offset=pos, last_only=True)["logits"][0, -1].float() | |
| pos += 1 | |
| raw = tk.decode(gen, skip_special_tokens=False) | |
| mth = re.search(r"<think>(.*?)</think>(.*)", raw, re.S) | |
| if mth: | |
| return raw, mth.group(1).strip(), mth.group(2).strip(), True | |
| if "<think>" in raw: | |
| return raw, raw.split("<think>", 1)[1].strip(), "", False | |
| return raw, "", raw.strip(), True | |
| 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("--long-file", default="/home/katie/synth_gen/dataset/sft_v1_final/long.jsonl") | |
| ap.add_argument("--dev", default="cuda:0") | |
| ap.add_argument("--lengths", default="4096,8192,16384,28672") | |
| ap.add_argument("--depths", default="0.10,0.35,0.65,0.90") | |
| ap.add_argument("--out", default="/home/katie/udream/data_survey/niah_sft2b_v2_dialog_clean.json") | |
| a = ap.parse_args() | |
| lengths = [int(x) for x in a.lengths.split(",")] | |
| depths = [float(x) for x in a.depths.split(",")] | |
| t0 = time.time() | |
| 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(a.dev).eval() | |
| tk = Tokenizer.from_file(a.tok) | |
| hay_turns = load_haystack_turns(a.long_file, tk) | |
| h_vec = torch.tensor([H_MEAN_DLG.tolist()], dtype=torch.bfloat16, device=a.dev) | |
| results = [] | |
| tot_vis, tot_th, tot_trials = 0, 0, 0 | |
| for L in lengths: | |
| row = [] | |
| for d in depths: | |
| vhits, thits, closed_cnt = 0, 0, 0 | |
| samples = [] | |
| for nd in CLEAN_NEEDLES: | |
| p_ids = build_prompt(tk, hay_turns, nd, L, d, "dialog") | |
| raw, th, vis, closed = chunked_prefill_and_gen_clean(m, tk, p_ids, h_vec, a.dev) | |
| ans_l = nd["answer"].lower() | |
| vis_ok = ans_l in vis.lower() | |
| th_ok = ans_l in th.lower() | |
| vhits += int(vis_ok) | |
| thits += int(th_ok) | |
| closed_cnt += int(closed) | |
| tot_vis += int(vis_ok) | |
| tot_th += int(th_ok) | |
| tot_trials += 1 | |
| samples.append({ | |
| "ans": nd["answer"], | |
| "visible_ok": vis_ok, | |
| "think_ok": th_ok, | |
| "think_closed": closed, | |
| "think": th[:120], | |
| "visible": vis[:160], | |
| }) | |
| acc = vhits / len(CLEAN_NEEDLES) | |
| row.append(f"{int(acc*100):3d}%") | |
| results.append({ | |
| "length": L, | |
| "depth": d, | |
| "visible_acc": acc, | |
| "think_acc": thits / len(CLEAN_NEEDLES), | |
| "think_closed_rate": closed_cnt / len(CLEAN_NEEDLES), | |
| "samples": samples, | |
| }) | |
| print(f" L={L:5d} | depths {depths} -> visible recall: {' '.join(row)}", flush=True) | |
| summary = { | |
| "ckpt": a.ckpt, | |
| "mode": "dialog_clean_visible_only", | |
| "n_needles_per_cell": len(CLEAN_NEEDLES), | |
| "total_trials": tot_trials, | |
| "overall_visible_hits": tot_vis, | |
| "overall_visible_acc": round(tot_vis / max(tot_trials, 1), 4), | |
| "overall_think_hits": tot_th, | |
| "elapsed_sec": round(time.time() - t0, 1), | |
| "results": results, | |
| } | |
| 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(summary, f, ensure_ascii=False, indent=2) | |
| print(f"[DONE] visible={tot_vis}/{tot_trials} ({summary['overall_visible_acc']*100:.1f}%) think={tot_th}/{tot_trials} -> {a.out}") | |
| if __name__ == "__main__": | |
| main() | |