Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: load Laya without randomly initialising its vocabulary embedding (#12210)
Daniel Han7e732ba5a2ca
diff --git a/studio/backend/core/systemone/laya_runtime.py b/studio/backend/core/systemone/laya_runtime.pyindex f9136357f81..c33031cca91 100644--- a/studio/backend/core/systemone/laya_runtime.py+++ b/studio/backend/core/systemone/laya_runtime.py@@ -282,7 +282,7 @@ class _MLXAgent:def _load_checkpoint(checkpoint: Checkpoint):root = _checkpoint_dir(checkpoint)- laya = _laya()+ _laya()# Evict only once the new checkpoint is on disk, so a long or failed download leaves the resident model serving._evict()@@ -291,16 +291,107 @@ def _load_checkpoint(checkpoint: Checkpoint):if device == "mlx":return _MLXAgent(folder), deviceif device not in ("cuda", "cpu"):- return laya.load(str(root), subfolder = checkpoint.subfolder, device = device), device+ return _load_laya(str(root), subfolder = checkpoint.subfolder, device = device), deviceimport torch# Built on CPU and cast before the move, so the device never holds laya's fp32 copy.- agent = laya.load(str(root), subfolder = checkpoint.subfolder, device = "cpu")fp16_checkpoint = checkpoint.name in CHECKPOINTS or _stored_fp16(folder)+ weights, _ = _precision(torch.device(device), fp16_checkpoint)+ agent = _load_laya(+ str(root), subfolder = checkpoint.subfolder, device = "cpu", embedding_dtype = weights+ )_place(agent, torch.device(device), fp16_checkpoint)return agent, str(agent.device.type)+_build_lock = threading.Lock()+++def _load_laya(+ path: str,+ *,+ embedding_dtype = None,+ **kwargs,+):+ """``laya.load`` without randomly initialising the encoder's vocabulary embedding.++ laya builds a randomly initialised fp32 encoder and then loads the checkpoint over it. For mmBERT's+ 256000 x 768 embedding that init alone took ~3.2 GB of scratch RAM and ~8 s, all of it overwritten+ by laya's strict load. The embedding is created with ``skip_init`` instead, in the dtype it will be+ served in; the rest of the model, including buffers the checkpoint does not carry, is built as before.+ """+ laya = _laya()+ hook = getattr(laya, "agent", None)+ if not hasattr(hook, "build_model"):+ return laya.load(path, **kwargs)+ with _build_lock:+ original = hook.build_model++ def build_model(cfg, encoder_dir = None):+ return _build_model(cfg, encoder_dir, original, embedding_dtype)++ hook.build_model = build_model+ try:+ return laya.load(path, **kwargs)+ finally:+ hook.build_model = original+++def _build_model(+ cfg,+ encoder_dir,+ original,+ embedding_dtype = None,+):+ """laya.common.build_model, with the vocabulary embedding allocated but not initialised."""+ import os++ import torch+ from transformers import AutoConfig, AutoModel++ if not encoder_dir or not os.path.exists(encoder_dir):+ return original(cfg, encoder_dir = encoder_dir)+ config = AutoConfig.from_pretrained(encoder_dir)+ vocab_size, pad_token_id = config.vocab_size, getattr(config, "pad_token_id", None)+ # ModernBERT reads pad_token_id only for this embedding; others keep it (RoBERTa's position ids).+ if config.model_type != "modernbert" or vocab_size <= 1:+ return original(cfg, encoder_dir = encoder_dir)+ # A one-row placeholder, with row 0 standing in for the padding id so the check below can+ # tell the embedding was sized and padded from the config.+ placeholder_pad = None if pad_token_id is None else 0+ config.vocab_size, config.pad_token_id = 1, placeholder_pad+ try:+ encoder = AutoModel.from_config(config, attn_implementation = "sdpa")+ finally:+ config.vocab_size, config.pad_token_id = vocab_size, pad_token_id+ placeholder = encoder.get_input_embeddings()+ if (+ type(placeholder) is not torch.nn.Embedding+ or placeholder.num_embeddings != 1+ or placeholder.padding_idx != placeholder_pad+ or encoder.config.vocab_size != vocab_size+ ):+ # Not laid out like ModernBERT: build it laya's way.+ del encoder, placeholder+ return original(cfg, encoder_dir = encoder_dir)+ encoder.set_input_embeddings(+ torch.nn.utils.skip_init(+ torch.nn.Embedding,+ vocab_size,+ placeholder.embedding_dim,+ padding_idx = pad_token_id,+ max_norm = placeholder.max_norm,+ norm_type = placeholder.norm_type,+ scale_grad_by_freq = placeholder.scale_grad_by_freq,+ sparse = placeholder.sparse,+ dtype = embedding_dtype or placeholder.weight.dtype,+ )+ )+ return _laya().common.DecisionModel(+ encoder, cfg.get("head_layers", 2), len(cfg.get("act_costs", {})) + 1+ )++def _stored_fp16(folder: Path) -> bool:"""Whether the checkpoint's weights are saved as float16, as all three published Laya checkpoints are."""import json@@ -619,14 +710,17 @@ def _forward(agent, items: list[dict[str, Any]]):if "memory" not in reason and "allocate" not in reason:raise# Past the handler, so the traceback no longer keeps the MLX arrays alive while the CPU copy loads.- laya = _laya()-logger.warning("Laya ran out of GPU memory; moving it to CPU")agent.model = None_release_memory()try:- cpu = laya.load(str(agent.folder), device = "cpu")- _place(cpu, torch.device("cpu"), _stored_fp16(Path(agent.folder)))+ cpu_device, fp16_checkpoint = torch.device("cpu"), _stored_fp16(Path(agent.folder))+ cpu = _load_laya(+ str(agent.folder),+ device = "cpu",+ embedding_dtype = _precision(cpu_device, fp16_checkpoint)[0],+ )+ _place(cpu, cpu_device, fp16_checkpoint)except Exception:# Callers hold _run_lock, so drop the half-moved agent here; the next request loads it again._agent = _loaded = _device_name = Nonediff --git a/studio/backend/tests/test_systemone.py b/studio/backend/tests/test_systemone.pyindex 3136afe66e3..64304e967c1 100644--- a/studio/backend/tests/test_systemone.py+++ b/studio/backend/tests/test_systemone.py@@ -1192,3 +1192,210 @@ def test_fp16_overflow_reruns_in_fp32(monkeypatch, gpu_agent):logits, _ = laya_runtime._forward(agent, _items())assert calls == [torch.float16, torch.float32] and agent.dtype == torch.float32assert logits.tolist() == [[1.0, 0.5]]+++def _tiny_laya_encoder(tmp_path):+ pytest.importorskip("torch")+ from transformers import ModernBertConfig++ config = ModernBertConfig(+ vocab_size = 300,+ hidden_size = 64,+ intermediate_size = 96,+ num_hidden_layers = 3,+ num_attention_heads = 4,+ pad_token_id = 0,+ bos_token_id = 2,+ eos_token_id = 1,+ cls_token_id = 1,+ sep_token_id = 1,+ mask_token_id = 4,+ global_attn_every_n_layers = 3,+ local_attention = 16,+ )+ encoder_dir = tmp_path / "encoder"+ config.save_pretrained(encoder_dir)+ return str(encoder_dir), {"encoder": "tiny", "head_layers": 1, "act_costs": {"escalate": 0.5}}+++def test_skip_init_build_matches_laya_after_loading(tmp_path):+ torch = pytest.importorskip("torch")+ laya = laya_runtime._laya()+ encoder_dir, cfg = _tiny_laya_encoder(tmp_path)+ reference = laya.common.build_model(cfg, encoder_dir = encoder_dir).eval()+ fast = laya_runtime._build_model(cfg, encoder_dir, laya.common.build_model).eval()+ embedding = fast.encoder.get_input_embeddings()+ assert embedding.num_embeddings == 300 and fast.encoder.config.vocab_size == 300+ assert embedding.padding_idx == reference.encoder.get_input_embeddings().padding_idx+ # laya loads strictly, so every parameter and persistent buffer comes from the checkpoint.+ fast.load_state_dict(reference.state_dict(), strict = True)+ ours = dict(fast.named_parameters()) | dict(fast.named_buffers())+ theirs = dict(reference.named_parameters()) | dict(reference.named_buffers())+ assert ours.keys() == theirs.keys()+ # Includes the rotary inv_freq buffers, which the checkpoint does not carry.+ assert any("inv_freq" in name for name in theirs)+ assert all(torch.equal(ours[name], theirs[name]) for name in theirs)+ assert repr(fast) == repr(reference)+ assert fast.encoder.config.to_dict() == reference.encoder.config.to_dict()+ ids = torch.randint(5, 300, (2, 20))+ args = (+ ids,+ torch.ones_like(ids),+ torch.tensor([[3, 7]] * 2),+ torch.ones(2, 2, dtype = torch.bool),+ torch.zeros(2, dtype = torch.long),+ )+ with torch.inference_mode():+ assert torch.equal(fast(*args)[0], reference(*args)[0])+++def test_skip_init_embedding_is_built_in_the_serving_dtype(tmp_path):+ torch = pytest.importorskip("torch")+ laya = laya_runtime._laya()+ encoder_dir, cfg = _tiny_laya_encoder(tmp_path)+ fast = laya_runtime._build_model(cfg, encoder_dir, laya.common.build_model, torch.float16)+ assert fast.encoder.get_input_embeddings().weight.dtype == torch.float16+ assert fast.encoder.embeddings.norm.weight.dtype == torch.float32+++def test_build_without_an_encoder_dir_is_laya_own(tmp_path):+ pytest.importorskip("torch")+ sentinel = object()+ calls = []++ def original(cfg, encoder_dir = None):+ calls.append(encoder_dir)+ return sentinel++ assert laya_runtime._build_model({}, None, original) is sentinel+ assert laya_runtime._build_model({}, str(tmp_path / "missing"), original) is sentinel+ assert calls == [None, str(tmp_path / "missing")]+++def test_fallback_build_releases_the_speculative_encoder(tmp_path, monkeypatch):+ torch = pytest.importorskip("torch")+ import gc++ from transformers import ModernBertModel++ encoder_dir, cfg = _tiny_laya_encoder(tmp_path)+ # An input embedding that is not a plain nn.Embedding sends the build back to laya's own builder.+ monkeypatch.setattr(ModernBertModel, "get_input_embeddings", lambda self: torch.nn.Identity())+ gc.collect()+ before = sum(isinstance(o, ModernBertModel) for o in gc.get_objects())+ during = []++ def original(cfg, encoder_dir = None):+ during.append(sum(isinstance(o, ModernBertModel) for o in gc.get_objects()))+ return "laya"++ assert laya_runtime._build_model(cfg, encoder_dir, original) == "laya"+ assert during == [before]+++def test_build_hook_is_restored_even_when_loading_fails(monkeypatch):+ pytest.importorskip("torch") # laya imports torch+ laya = laya_runtime._laya()+ original = laya.agent.build_model+ seen = []++ def boom(path, **kwargs):+ seen.append(laya.agent.build_model is not original)+ raise FileNotFoundError(path)++ monkeypatch.setattr(laya, "load", boom)+ with pytest.raises(FileNotFoundError):+ laya_runtime._load_laya("missing", device = "cpu")+ assert seen == [True] and laya.agent.build_model is original+++def test_high_special_token_ids_still_skip_the_embedding_init(tmp_path):+ torch = pytest.importorskip("torch")+ from transformers import ModernBertConfig++ laya = laya_runtime._laya()+ encoder_dir, cfg = _tiny_laya_encoder(tmp_path)+ # ModernBERT-large puts its special tokens at the end of the vocabulary (pad 50283 of 50368).+ config = ModernBertConfig.from_pretrained(encoder_dir)+ config.pad_token_id, config.bos_token_id, config.eos_token_id = 297, 295, 296+ config.cls_token_id, config.sep_token_id = 295, 296+ config.save_pretrained(encoder_dir)+ built = []+ real_skip_init = torch.nn.utils.skip_init++ def skip_init(*args, **kwargs):+ built.append(args[1])+ return real_skip_init(*args, **kwargs)++ from transformers import AutoModel++ real_from_config = AutoModel.from_config+ placeholder_vocab = []++ def from_config(config, **kwargs):+ placeholder_vocab.append(config.vocab_size)+ return real_from_config(config, **kwargs)++ torch.nn.utils.skip_init, AutoModel.from_config = skip_init, from_config+ try:+ fast = laya_runtime._build_model(cfg, encoder_dir, laya.common.build_model).eval()+ finally:+ torch.nn.utils.skip_init, AutoModel.from_config = real_skip_init, real_from_config+ # One row, not one past the highest special id: otherwise the embedding is still randomly initialised.+ assert placeholder_vocab == [1]+ reference = laya.common.build_model(cfg, encoder_dir = encoder_dir).eval()+ assert built == [300]+ assert (+ fast.encoder.get_input_embeddings().padding_idx+ == 297+ == reference.encoder.get_input_embeddings().padding_idx+ )+ fast.load_state_dict(reference.state_dict(), strict = True)+ assert repr(fast) == repr(reference)+ assert fast.encoder.config.to_dict() == reference.encoder.config.to_dict()+ ids = torch.randint(5, 300, (2, 20))+ args = (+ ids,+ torch.ones_like(ids),+ torch.tensor([[3, 7]] * 2),+ torch.ones(2, 2, dtype = torch.bool),+ torch.zeros(2, dtype = torch.long),+ )+ with torch.inference_mode():+ assert torch.equal(fast(*args)[0], reference(*args)[0])+++def test_encoders_that_keep_the_padding_id_match_laya(tmp_path):+ torch = pytest.importorskip("torch")+ from transformers import RobertaConfig++ laya = laya_runtime._laya()+ # RoBERTa keeps pad_token_id for its position ids, so a build with a stand-in padding id answers differently.+ config = RobertaConfig(+ vocab_size = 300,+ hidden_size = 64,+ intermediate_size = 96,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ max_position_embeddings = 40,+ pad_token_id = 1,+ bos_token_id = 0,+ eos_token_id = 2,+ )+ encoder_dir = tmp_path / "encoder"+ config.save_pretrained(encoder_dir)+ cfg = {"encoder": "tiny", "head_layers": 1, "act_costs": {"escalate": 0.5}}+ reference = laya.common.build_model(cfg, encoder_dir = str(encoder_dir)).eval()+ fast = laya_runtime._build_model(cfg, str(encoder_dir), laya.common.build_model).eval()+ fast.load_state_dict(reference.state_dict(), strict = True)+ ids = torch.randint(5, 300, (2, 20))+ ids[:, 15:] = 1+ args = (+ ids,+ (ids != 1).long(),+ torch.tensor([[3, 7]] * 2),+ torch.ones(2, 2, dtype = torch.bool),+ torch.zeros(2, dtype = torch.long),+ )+ with torch.inference_mode():+ assert torch.equal(fast(*args)[0], reference(*args)[0])