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
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
"""Loss is recorded, never asserted: with num_iterations=1 and beta=0.0 it is zero by construction."""
from __future__ import annotations
import argparse
import json
import os
import platform
import sys
import time
import traceback
from pathlib import Path
_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
from training_evidence import ( # noqa: E402
adapter_fingerprint,
adapter_update,
update_verdict,
)
from versions import ( # noqa: E402
GOAL_PACKAGES,
flatten_versions,
resolved_versions,
)
SEED = 3407
DEFAULT_MODEL = "unsloth/Qwen3-4B-Base"
SYSTEM_PROMPT = "You are given a question. Answer it as briefly as you can."
SEEN_COMPLETIONS: list[list[str]] = []
def _log(msg: str) -> None:
print(f"[grpo-t4] {msg}", flush = True)
def _texts(completions) -> list[str]:
"""TRL hands completions back as plain strings or as chat turns."""
out = []
for completion in completions:
if isinstance(completion, str):
out.append(completion)
elif isinstance(completion, list) and completion:
out.append(str(completion[0].get("content", "")))
else:
out.append("")
return out
# len/(len+SCALE) never saturates and is 0.5 at SCALE characters.
_LENGTH_SCALE = 200.0
def reward_length(completions, **kwargs) -> list[float]:
"""A length cap saturated every completion at 1.0 and zeroed reward_std; this curve never saturates."""
texts = _texts(completions)
SEEN_COMPLETIONS.append(texts)
return [len(t) / (len(t) + _LENGTH_SCALE) for t in texts]
def reward_digit(completions, **kwargs) -> list[float]:
"""A second reward of different shape, so one broken reward function can't pass for broken
generation."""
return [1.0 if any(c.isdigit() for c in t) else 0.0 for t in _texts(completions)]
def memory() -> dict:
import torch
if not torch.cuda.is_available():
return {}
props = torch.cuda.get_device_properties(0)
return {
"peak_reserved_gb": round(torch.cuda.max_memory_reserved() / 1024**3, 2),
"peak_allocated_gb": round(torch.cuda.max_memory_allocated() / 1024**3, 2),
"total_gb": round(props.total_memory / 1024**3, 2),
}
def vllm_facts() -> dict:
"""Recorded before the engine is built, so a crash in construction still reports what was attempted."""
facts: dict = {"env_override": os.environ.get("VLLM_ATTENTION_BACKEND")}
try:
import vllm
facts["version"] = getattr(vllm, "__version__", "unknown")
except BaseException as exc: # noqa: BLE001
facts["version"] = None
facts["import_error"] = f"{type(exc).__name__}: {str(exc)[:300]}"
return facts
try:
from vllm.platforms import current_platform
facts["platform"] = str(current_platform.device_name)
facts["capability"] = str(current_platform.get_device_capability())
except Exception as exc: # noqa: BLE001
facts["platform_error"] = f"{type(exc).__name__}: {str(exc)[:200]}"
# The backend enum moved between releases; xformers is expected missing at this version.
for path in (
"vllm.attention.backends.registry",
"vllm.attention.selector",
"vllm.platforms.interface",
):
try:
module = __import__(path, fromlist = ["*"])
except Exception: # noqa: BLE001
continue
backends = getattr(module, "_Backend", None) or getattr(module, "Backend", None)
if backends is not None:
names = sorted(getattr(b, "name", str(b)) for b in backends)
facts["backend_enum_source"] = path
facts["backends_available"] = names
facts["xformers_backend_present"] = any("XFORMERS" in n.upper() for n in names)
facts["triton_attn_backend_present"] = any("TRITON_ATTN" in n.upper() for n in names)
facts["requested_backend"] = os.environ.get("VLLM_ATTENTION_BACKEND", "")
break
return facts
def build_dataset(rows: list[dict]):
from datasets import Dataset
return Dataset.from_dict(
{
"prompt": [
[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": row["question"]},
]
for row in rows
],
"answer": [row["answer"] for row in rows],
}
)
def train(args, report: dict | None = None) -> dict:
"""Facts are written to report as soon as known, so a crash cannot erase that the engine was built."""
import torch
from unsloth import FastLanguageModel
result: dict = {}
if report is None:
report = {}
def record(key, value):
result[key] = value
report[key] = value
t0 = time.time()
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = args.model,
max_seq_length = args.max_seq_length,
load_in_4bit = args.load_in_4bit,
fast_inference = True,
max_lora_rank = args.lora_rank,
gpu_memory_utilization = args.gpu_memory_utilization,
)
record("load_seconds", round(time.time() - t0, 1))
record("engine_built", True)
# The base model ships no chat template and TRL raises without one; set a minimal ChatML one.
if not getattr(tokenizer, "chat_template", None):
tokenizer.chat_template = (
"{% for message in messages %}"
"{{ '<|im_start|>' + message['role'] + '\n' + message['content'] + "
"'<|im_end|>\n' }}"
"{% endfor %}"
"{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
)
result["chat_template"] = "set by the payload (base model ships none)"
else:
result["chat_template"] = "shipped with the tokenizer"
_log("chat template: " + result["chat_template"])
result["memory_after_load"] = memory()
_log(f"loaded in {result['load_seconds']}s, memory {result['memory_after_load']}")
model = FastLanguageModel.get_peft_model(
model,
r = args.lora_rank,
target_modules = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
],
lora_alpha = args.lora_rank * 2,
use_gradient_checkpointing = "unsloth",
random_state = SEED,
)
rows = [
json.loads(line)
for line in Path(args.dataset).read_text(encoding = "utf-8").splitlines()
if line.strip()
]
dataset = build_dataset(rows)
from trl import GRPOConfig, GRPOTrainer
config = GRPOConfig(
output_dir = str(Path(args.outdir) / "trainer"),
temperature = 1.0,
learning_rate = 5e-6,
weight_decay = 0.001,
warmup_steps = 0,
lr_scheduler_type = "constant",
optim = "adamw_8bit",
logging_steps = 1,
per_device_train_batch_size = args.num_generations,
gradient_accumulation_steps = 1,
num_generations = args.num_generations,
max_prompt_length = args.max_prompt_length,
max_completion_length = args.max_seq_length - args.max_prompt_length,
max_steps = args.max_steps,
seed = SEED,
fp16 = True,
bf16 = False,
report_to = "none",
save_strategy = "no",
)
trainer = GRPOTrainer(
model = model,
processing_class = tokenizer,
reward_funcs = [reward_length, reward_digit],
args = config,
train_dataset = dataset,
)
# Fingerprint before training: under fp16 every step can be skipped while metrics still log.
adapter_before = adapter_fingerprint(model)
_log(f"adapter before training: {json.dumps(adapter_before)}")
t0 = time.time()
trainer.train()
result["train_seconds"] = round(time.time() - t0, 1)
result["adapter_update"] = adapter_update(adapter_before, adapter_fingerprint(model))
_log(f"adapter update: {json.dumps(result['adapter_update'])}")
result["log_history"] = [
{
k: v
for k, v in entry.items()
if k
in (
"step",
"loss",
"reward",
"reward_std",
"kl",
"completions/mean_length",
"frac_reward_zero_std",
)
or k.startswith("rewards/")
}
for entry in trainer.state.log_history
]
result["metrics"] = [
{"step": entry.get("step"), "loss": entry.get("loss"), "grad_norm": entry.get("grad_norm")}
for entry in trainer.state.log_history
if "loss" in entry
]
result["completions"] = SEEN_COMPLETIONS[: args.max_steps * 2]
result["memory_peak"] = memory()
_log(f"trained in {result['train_seconds']}s; log {json.dumps(result['log_history'])[:1500]}")
# fast_generate is a separate path from the trainer's rollouts, and the trained LoRA reaches
# it only via save_lora + load_lora; generating with None would not test adapter transfer.
lora_state: dict = {"requested": True, "applied": False}
lora_request = None
try:
lora_dir = str(Path(args.outdir) / "grpo_lora")
model.save_lora(lora_dir)
lora_request = model.load_lora(lora_dir)
lora_state.update(applied = lora_request is not None, path = lora_dir)
if lora_request is None:
lora_state["error"] = "load_lora returned None"
except BaseException as exc: # noqa: BLE001
lora_state["error"] = f"{type(exc).__name__}: {str(exc)[:400]}"
record("fast_generate_lora", lora_state)
try:
from vllm import SamplingParams
params = SamplingParams(temperature = 1.0, top_k = 50, max_tokens = 32, seed = SEED)
out = model.fast_generate(
[rows[0]["question"]], sampling_params = params, lora_request = lora_request
)
result["fast_generate"] = out[0].outputs[0].text
except BaseException as exc: # noqa: BLE001
result["fast_generate"] = None
result["fast_generate_error"] = f"{type(exc).__name__}: {str(exc)[:400]}"
del trainer, model
import gc
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return result
def failures_for(result: dict, args) -> list[str]:
"""The GRPO assertions. See this file's docstring for why not the loss."""
failures: list[str] = []
history = result.get("log_history") or []
# train() appends a summary entry with no loss, which is not a step.
steps = [e for e in history if "loss" in e]
rewards = [e["reward"] for e in history if e.get("reward") is not None]
if not rewards:
failures.append(
"no reward was logged on any step, so the reward functions never "
"ran and generation produced nothing to score"
)
elif any(r != r or r in (float("inf"), float("-inf")) for r in rewards):
failures.append(f"non-finite reward: {rewards}")
else:
missing = [e.get("step") for e in steps if e.get("reward") is None]
if missing:
failures.append(
f"the reward functions did not run on every step: no reward was "
f"logged for step(s) {missing} of {len(steps)}. A reward on some "
f"steps is not the invariant this leg asserts."
)
stds = [e["reward_std"] for e in history if e.get("reward_std") is not None]
if not stds:
failures.append("reward_std was never logged, so group diversity could not be established")
elif not any(s > 0 for s in stds):
failures.append(
f"reward_std was zero on every step ({stds}): every completion in "
f"each group scored identically, which means the group was not "
f"diverse. The GRPO advantage is exactly zero in that state, so "
f"the run trained on nothing while reporting a healthy loss."
)
seen = result.get("completions") or []
flat = [text for group in seen for text in group]
if not flat:
failures.append("no completion was ever produced")
elif not any(t.strip() for t in flat):
failures.append(
f"every one of the {len(flat)} completions was empty, so the "
f"identical rewards above are not evidence of anything"
)
metrics = result.get("metrics") or []
if len(metrics) != args.max_steps:
failures.append(f"expected {args.max_steps} logged steps, got {len(metrics)}")
# Under fp16 steps can be skipped while metrics still log, and an empty grad_norm list must not
# pass. See training_evidence.py.
update = update_verdict(metrics, result.get("adapter_update"))
if update["verdict"] == "not_applied":
failures.append(
f"no optimizer update was applied: {update['detail']}. The fp16 scaler "
f"skips the step it overflowed on, so this run generated, scored and "
f"updated nothing."
)
elif update["verdict"] == "non_finite":
failures.append(
f"the adapter holds non-finite weights after training: {update['detail']}. "
f"An optimizer step landed and produced NaN or infinity, which is a "
f"broken run rather than an untrained one, and generation still returns "
f"text either way."
)
elif update["verdict"] != "applied":
# Any unknown verdict fails rather than passing silently.
failures.append(
f"whether the optimizer applied anything could not be established: "
f"{update['detail']}. Every other number this leg reports is produced "
f"by generation and scoring, which the base model does on its own."
)
lora = result.get("fast_generate_lora")
if lora is not None and lora.get("requested") and not lora.get("applied"):
failures.append(
f"the trained adapter could not be handed to the vLLM engine, so the "
f"final generation ran on the base weights and proves nothing about "
f"training: {lora.get('error')}"
)
if result.get("fast_generate") is None:
failures.append(
"fast_generate (the vLLM inference path the notebook uses after "
f"training) failed: {result.get('fast_generate_error')}"
)
return failures
def make_libcuda_linkable() -> dict:
"""Kaggle has libcuda.so.1 but no libcuda.so, so -lcuda fails; LIBRARY_PATH avoids a symlink."""
facts: dict = {"needed": False, "applied": False}
try:
import ctypes.util
import subprocess
# Only directories flashinfer passes with -L; the compat dir is not on the link line.
link_dirs = ["/usr/local/cuda/lib64", "/usr/local/cuda/lib64/stubs"]
for d in link_dirs:
if os.path.exists(os.path.join(d, "libcuda.so")):
facts["already_linkable"] = d
return facts
facts["needed"] = True
facts["searched"] = link_dirs
real = None
try:
out = subprocess.run(
["/sbin/ldconfig", "-p"], capture_output = True, text = True, timeout = 60
).stdout
for line in out.splitlines():
if "libcuda.so.1" in line and "=>" in line:
real = line.split("=>")[-1].strip()
break
except Exception:
real = None
if real is None or not os.path.exists(real):
found = ctypes.util.find_library("cuda")
real = found if found and os.path.exists(found) else None
if real is None:
# The compat tree is useless as a -L target but fine as a symlink target.
for candidate in (
"/usr/local/cuda/compat/libcuda.so",
"/usr/local/cuda/compat/libcuda.so.1",
):
if os.path.exists(candidate):
real = candidate
break
if real is None:
facts["error"] = "no libcuda.so.1 on this machine"
return facts
shim = os.path.join(os.environ.get("TMPDIR") or "/tmp", "unsloth_libcuda_shim")
os.makedirs(shim, exist_ok = True)
link = os.path.join(shim, "libcuda.so")
if not os.path.exists(link):
os.symlink(real, link)
existing = os.environ.get("LIBRARY_PATH", "")
os.environ["LIBRARY_PATH"] = f"{shim}:{existing}" if existing else shim
facts.update(applied = True, real = real, shim = shim)
except Exception as exc: # noqa: BLE001
facts["error"] = f"{type(exc).__name__}: {exc}"
return facts
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--model", default = DEFAULT_MODEL)
ap.add_argument("--dataset", default = str(_HERE / "canary_dataset.jsonl"))
ap.add_argument("--outdir", required = True)
ap.add_argument("--label", default = "grpo")
ap.add_argument("--max-steps", type = int, default = 3)
ap.add_argument("--max-seq-length", type = int, default = 2048)
ap.add_argument("--max-prompt-length", type = int, default = 256)
ap.add_argument("--num-generations", type = int, default = 4)
ap.add_argument("--lora-rank", type = int, default = 32)
ap.add_argument("--gpu-memory-utilization", type = float, default = 0.9)
# The notebook uses False: 16-bit weights plus engine plus trainer on a 16GB card.
ap.add_argument("--load-in-4bit", dest = "load_in_4bit", action = "store_true", default = False)
ap.add_argument("--no-load-in-4bit", dest = "load_in_4bit", action = "store_false")
ap.add_argument("--probe", action = "store_true", help = "record everything, assert nothing")
# Illegal memory accesses surface at the next synchronising CUDA call, not the faulting kernel.
ap.add_argument("--cuda-launch-blocking", action = "store_true")
args = ap.parse_args()
if args.cuda_launch_blocking:
# Must precede the first `import torch`, before any CUDA context.
os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
os.environ["TORCH_USE_CUDA_DSA"] = "1"
# Before vLLM imports: flashinfer JIT linking fails on this image otherwise.
libcuda = make_libcuda_linkable()
_log(f"libcuda link shim: {libcuda}")
outdir = Path(args.outdir)
outdir.mkdir(parents = True, exist_ok = True)
report: dict = {
"label": args.label,
"model": args.model,
"leg": "grpo",
"probe": args.probe,
"config": {
k: getattr(args, k)
for k in (
"max_steps",
"max_seq_length",
"max_prompt_length",
"num_generations",
"lora_rank",
"gpu_memory_utilization",
"load_in_4bit",
"cuda_launch_blocking",
)
},
"failures": [],
}
report["versions"] = resolved_versions(
GOAL_PACKAGES, import_check = ("torch", "transformers", "trl", "vllm")
)
report["versions_flat"] = flatten_versions(report["versions"])
_log("versions " + json.dumps(report["versions_flat"]))
report["libcuda_shim"] = libcuda
report["vllm"] = vllm_facts()
_log("vllm " + json.dumps(report["vllm"]))
try:
import torch
props = torch.cuda.get_device_properties(0)
report["environment"] = {
"python": platform.python_version(),
"torch": torch.__version__,
"cuda": torch.version.cuda,
"gpu_name": props.name,
"gpu_capability": f"sm_{props.major}{props.minor}",
"gpu_total_gb": round(props.total_memory / 1024**3, 1),
"gpu_count_visible": torch.cuda.device_count(),
"bf16_supported": bool(torch.cuda.is_bf16_supported()),
"vllm_standby": os.environ.get("UNSLOTH_VLLM_STANDBY"),
}
except Exception as exc: # noqa: BLE001
report["environment"] = {"error": f"{type(exc).__name__}: {exc}"}
failures: list[str] = []
try:
result = train(args, report)
report.update(result)
failures = failures_for(report, args)
except BaseException as exc: # noqa: BLE001
if isinstance(exc, KeyboardInterrupt):
raise
# Head and tail: a long ninja log can push the Python frames out of the tail.
_tb = traceback.format_exc()
report["traceback"] = (
_tb if len(_tb) <= 12000 else _tb[:6000] + "\n...[middle elided]...\n" + _tb[-6000:]
)
report["engine_built"] = report.get("engine_built", False)
failures = [f"{type(exc).__name__}: {str(exc)[:600]}"]
_log("EXCEPTION\n" + report["traceback"])
report["memory_peak"] = memory()
report["observed_failures"] = failures
if args.probe:
report["failures"] = []
report["passed"] = True
else:
report["failures"] = failures
report["passed"] = not failures
(outdir / "t4_smoke_report.json").write_text(
json.dumps(report, indent = 2, default = str), encoding = "utf-8"
)
print("T4_SMOKE_REPORT " + json.dumps(report, default = str), flush = True)
for entry in failures:
_log(f"OBSERVED FAILURE: {entry}")
_log("T4_SMOKE_RESULT " + ("PASS" if report["passed"] else "FAIL"))
return 0 if report["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())