"""Model loading, LoRA, and per-token log-probs that never build the full [T, vocab] logits. The vocabulary has 151,936 entries, so the logits of one 32k-token answer in float32 would take ~19 GB. Training computes log-probs from the hidden states in chunks, each wrapped in activation checkpointing. Scoring (no gradients) runs the model over the sequence in chunks with a KV cache, so it works for any architecture, including custom ones like Limite. """ from __future__ import annotations import json import shutil from pathlib import Path from typing import Any import torch import torch.nn.functional as F from torch.utils.checkpoint import checkpoint DTYPES = {"fp16": torch.float16, "fp32": torch.float32, "bf16": torch.bfloat16} TOKENIZER_FILES = ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "added_tokens.json", "vocab.json", "merges.txt", "chat_template.jinja", "generation_config.json") def pick_dtype(name: str, device: str) -> torch.dtype: if not device.startswith("cuda"): return torch.float32 return DTYPES[name] def load_tokenizer(path: str | Path, trust_remote_code: bool = False): from transformers import AutoTokenizer return AutoTokenizer.from_pretrained(str(path), trust_remote_code=trust_remote_code) _ORIGINAL_USE_GQA = None def set_sdpa_gqa(enabled: bool) -> None: """Choose whether Transformers' SDPA attention may pass enable_gqa=True to PyTorch (process-wide). PyTorch runs GQA only in its flash and math kernels (torch 2.11's scaled_dot_product_attention docstring). A T4 has no flash kernel, so GQA falls to the math kernel, which stores the full [heads, T, T] attention matrix: smoke run 2 trained 4,096 tokens in 6.65 GB and ran out of memory at 8,192. With GQA off, Transformers repeats the key/value heads itself and PyTorch can pick its memory-efficient kernel instead. Both models give the same numbers. """ from transformers.integrations import sdpa_attention as sa global _ORIGINAL_USE_GQA if not hasattr(sa, "use_gqa_in_sdpa"): raise RuntimeError("transformers moved use_gqa_in_sdpa; update modeling.set_sdpa_gqa") if _ORIGINAL_USE_GQA is None: _ORIGINAL_USE_GQA = sa.use_gqa_in_sdpa sa.use_gqa_in_sdpa = _ORIGINAL_USE_GQA if enabled else _never_gqa def _never_gqa(attention_mask, key) -> bool: return False def load_model(path: str | Path, dtype: torch.dtype, device: str, trust_remote_code: bool = False): from transformers import AutoModelForCausalLM set_sdpa_gqa(False) model = AutoModelForCausalLM.from_pretrained(str(path), dtype=dtype, trust_remote_code=trust_remote_code, attn_implementation="sdpa") return model.to(device) def eval_model(model): """model.eval(), then, for a float32 model, half-precision inference constants upcast to float32. Limite's eval() caches some weights in bfloat16 whatever the model's dtype (LimiteMudd.train in its modeling_limite.py), so a float32 forward pass failed with "expected mat1 and mat2 to have the same dtype" (smoke runs 1 and 2). Half-precision models are left exactly as they were. """ model.eval() if next(model.parameters()).dtype == torch.float32: for module in model.modules(): for name, buf in list(module._buffers.items()): if buf is not None and buf.dtype in (torch.float16, torch.bfloat16): module._buffers[name] = buf.float() return model def lora_config(cfg: dict[str, Any]): from peft import LoraConfig return LoraConfig(r=int(cfg.get("rank", 64)), lora_alpha=int(cfg.get("alpha", 32)), lora_dropout=float(cfg.get("dropout", 0.0)), target_modules=cfg.get("targets", "all-linear"), bias="none", task_type="CAUSAL_LM") def attach_lora(model, cfg: dict[str, Any], adapter_dir: Path | None, trainable: bool = True): from peft import PeftModel, get_peft_model if adapter_dir is not None and (Path(adapter_dir) / "adapter_config.json").exists(): return PeftModel.from_pretrained(model, str(adapter_dir), is_trainable=trainable) return get_peft_model(model, lora_config(cfg)) def _unwrap(model): return model.get_base_model() if hasattr(model, "get_base_model") else model def _lp_chunk(h: torch.Tensor, targets: torch.Tensor, weight: torch.Tensor): logits = (h @ weight.t()).float() logp = logits.log_softmax(-1) lp = logp.gather(-1, targets[:, None]).squeeze(-1) with torch.no_grad(): ent = -(logp.exp() * logp).sum(-1) return lp, ent def train_logprobs(model, ids: torch.Tensor, start: int, chunk: int = 1024) -> tuple[torch.Tensor, torch.Tensor]: """Log-prob and entropy of tokens ids[start:], each given everything before it. ids is 1-D. Valid for causal LMs whose head is a plain linear layer on the final hidden state (Qwen2, which both VibeThinker models are). """ inner = _unwrap(model) hidden = inner.model(input_ids=ids[None], use_cache=False).last_hidden_state[0] h = hidden[start - 1:-1] targets = ids[start:] weight = inner.lm_head.weight lps, ents = [], [] for s in range(0, h.shape[0], chunk): if torch.is_grad_enabled(): lp, ent = checkpoint(_lp_chunk, h[s:s + chunk], targets[s:s + chunk], weight, use_reentrant=False) else: lp, ent = _lp_chunk(h[s:s + chunk], targets[s:s + chunk], weight) lps.append(lp) ents.append(ent) return torch.cat(lps), torch.cat(ents) @torch.no_grad() def score_logprobs(model, ids: torch.Tensor, start: int, chunk: int = 2048, floor: float = -30.0) -> torch.Tensor: """Log-probs of ids[start:] by running the model over the sequence in chunks with a KV cache. Token ids outside this model's vocabulary score `floor`. """ from transformers import DynamicCache vocab = model.get_output_embeddings().weight.shape[0] safe = ids.clamp(max=vocab - 1) cache = DynamicCache() out = torch.empty(ids.shape[0] - start, dtype=torch.float32, device=ids.device) pos = 0 prev_logits = None # Custom models such as Limite keep some activations in float32 and feed them to fp16 weights; # autocast makes those matmuls run in fp16 as the model's own bf16 path would. half = ids.device.type == "cuda" and next(model.parameters()).dtype == torch.float16 while pos < ids.shape[0]: end = min(pos + chunk, ids.shape[0]) with torch.autocast("cuda", dtype=torch.float16, enabled=half): logits = model(input_ids=safe[None, pos:end], past_key_values=cache, use_cache=True).logits[0].float() if prev_logits is not None: logits = torch.cat([prev_logits, logits]) first = pos - 1 else: first = pos # logits[i] (absolute position first + i) predicts token first + i + 1. lo, hi = max(first, start - 1), end - 1 if hi > lo: sel = logits[lo - first:hi - first].log_softmax(-1) tgt = safe[lo + 1:hi + 1] out[lo + 1 - start:hi + 1 - start] = sel.gather(-1, tgt[:, None]).squeeze(-1) prev_logits = logits[-1:] pos = end oob = ids[start:] >= vocab out[oob] = floor return out def save_adapter(model, out_dir: Path, extra: dict[str, Any] | None = None) -> None: out_dir = Path(out_dir) tmp = out_dir.with_name(out_dir.name + ".tmp") shutil.rmtree(tmp, ignore_errors=True) model.save_pretrained(str(tmp)) if extra: (tmp / "base.json").write_text(json.dumps(extra, indent=2)) shutil.rmtree(out_dir, ignore_errors=True) tmp.rename(out_dir) def save_merged(model, tokenizer_src: Path, out_dir: Path, dtype: torch.dtype = torch.float16) -> None: """Fold the LoRA weights into the base and save a plain checkpoint vLLM can load.""" out_dir = Path(out_dir) tmp = out_dir.with_name(out_dir.name + ".tmp") shutil.rmtree(tmp, ignore_errors=True) merged = model.merge_and_unload() if hasattr(model, "merge_and_unload") else model merged.to(dtype).save_pretrained(str(tmp)) # Merging LoRA leaves the architecture unchanged. transformers 5 writes rope_theta only inside # rope_parameters, which vLLM 0.10 does not read, so keep the base model's own config.json. shutil.copyfile(Path(tokenizer_src) / "config.json", tmp / "config.json") copy_tokenizer(tokenizer_src, tmp) shutil.rmtree(out_dir, ignore_errors=True) tmp.rename(out_dir) def copy_tokenizer(src: Path, dst: Path) -> None: for name in TOKENIZER_FILES: p = Path(src) / name if p.exists() and not (Path(dst) / name).exists(): shutil.copyfile(p, Path(dst) / name) def full_logprobs_reference(model, ids: torch.Tensor, start: int) -> torch.Tensor: """The plain O(T x vocab) computation, used only by tests to check the chunked paths.""" logits = model(input_ids=ids[None]).logits[0].float() return F.log_softmax(logits[start - 1:-1], -1).gather(-1, ids[start:, None]).squeeze(-1)