diff --git a/.gitattributes b/.gitattributes index 40292d7..3b45501 100644 --- a/.gitattributes +++ b/.gitattributes @@ -16,6 +16,3 @@ corpora/posix-api/ export-ignore # headers. Provenance first, then it can ship. corpora/musl-headers/ export-ignore -# Build and download logs from one pod run. Evidence worth keeping, not source -# anyone needs to clone. -pod-artifacts-qwen3coder/ export-ignore diff --git a/.gitignore b/.gitignore index c7af953..ff8f66f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,11 +2,7 @@ # Poids de modèles — plusieurs dizaines de Go, jamais dans git. # ───────────────────────────────────────────────────────────────────────── /models/ -# Served GGUFs. The first name is the directory this deployment still has -# on disk (47 GB): renaming the RULE without moving the DIRECTORY is how -# 47 GB becomes visible to `git add -A`. The second is where the server -# layout puts them. -/edgem-gguf/ +# Served GGUFs, where the server layout puts them. /models/gguf/ # ───────────────────────────────────────────────────────────────────────── diff --git a/client/TRAINING_DATA.md b/client/TRAINING_DATA.md index fc1464a..80e11d5 100644 --- a/client/TRAINING_DATA.md +++ b/client/TRAINING_DATA.md @@ -11,12 +11,12 @@ real store. Run `python -m training freeze --source audit/training-data semantic OpenAI messages, source checksums, policies, governance, a held-out evaluation plan, Axolotl configuration, and a human runbook. -The default source is the Transformers checkpoint -`Qwen/Qwen3-Coder-Next`, not the deployed GGUF inference artifact. The optional -`qwen3_coder_next_base` profile uses `Qwen/Qwen3-Coder-Next-Base`. GGUF paths -are rejected. The initial profile is conservative 4-bit QLoRA and targets only -attention projections; targeting MoE experts is explicit because it changes -memory requirements. +The source is the Transformers checkpoint `Qwen/Qwen3.8-27B` (profile +`qwen38_27b_sft`), at the revision the operator pins in +`training-execution.json` (the weights were fetched at +`8c0b3d30f3ae96f5c7f774de704bf0ada83e422a`), not the deployed GGUF; +GGUF paths are rejected. The profile is conservative 4-bit QLoRA and targets +only attention projections. Every SFT message is annotated with a per-turn `train` flag. Context—including prior failed assistant actions—is false; only FT1's selected last assistant @@ -124,11 +124,8 @@ and missing source revision remain hard gates. The expected environment is a dedicated operator-managed Python/Axolotl environment, separate from the inference service on port 8010. Current Axolotl guidance requires Python >=3.11, PyTorch >=2.11, and an NVIDIA Ampere+ -or AMD GPU. Its Qwen3-Next guide describes conservative QLoRA at about 47 GiB -without expert targeting and about 71 GiB with expert targeting; these are -coarse planning values, not an EDGEM admission formula. Axolotl's documented -uv installation and Qwen3-Next extra dependencies are not installed -automatically. +or AMD GPU. Axolotl's documented uv installation and optional dependencies +are not installed automatically. If SSH authentication is unavailable, configure the normal OpenSSH alias so `ssh ` succeeds non-interactively from the SPEAR account. Use an @@ -147,18 +144,13 @@ UUID and cache paths before executing Axolotl. The pinned environment currently contains Axolotl 0.18.0, PyTorch 2.12.1+cu130, Transformers 5.14.1, PEFT 0.19.1, bitsandbytes 0.49.1, flash-linear-attention 0.4.1, and Cut Cross Entropy 25.1.1. The source model is -`Qwen/Qwen3-Coder-Next` at immutable revision -`a7fbcb5c0e12d62a448eaa0e260346bf5dcc0feb`; only tokenizer/config/chat-template -assets were fetched, never model weights. - -The assigned RTX PRO 6000 Blackwell has 97,887 MiB total VRAM, so hardware -capacity is `READY` for the coarse approximately 47 GiB no-expert QLoRA -profile. Current availability is `BUSY` because the known llama-server uses -82,628 MiB and 14,599 MiB is free. FT4C never stops or signals inference. -These are separate from data readiness, which remains `COLLECTING` with zero -real episodes. The bounded synthetic Axolotl preprocess succeeded and showed -50 ignored labels plus 5 trainable labels, preserving one-target masking; -`axolotl train` was never executed. +`Qwen/Qwen3.8-27B` at revision `8c0b3d30f3ae96f5c7f774de704bf0ada83e422a`. + +The assigned RTX PRO 6000 Blackwell has 97,887 MiB total VRAM. A training +job never stops or signals inference on its own: the controlled handoff below +does, for a job that owns the GPU lease. The bounded synthetic Axolotl +preprocess showed 50 ignored labels plus 5 trainable labels, preserving +one-target masking; `axolotl train` was never executed. ## Controlled inference handoff (FT4D) diff --git a/client/cli/finetune_commands.py b/client/cli/finetune_commands.py index e37fe0f..707065c 100644 --- a/client/cli/finetune_commands.py +++ b/client/cli/finetune_commands.py @@ -244,7 +244,7 @@ def _format_doctor(local: LocalDoctorReport, "source_model_revision", "environment_fingerprint", "axolotl_available", "axolotl_version", "package", "disk_available_kib", - "training_root", "qwen3_next_compatibility"): + "training_root"): if key in checks: value = checks[key] diff --git a/client/cli/model_io.py b/client/cli/model_io.py index f0a8c85..ae37d10 100644 --- a/client/cli/model_io.py +++ b/client/cli/model_io.py @@ -310,11 +310,9 @@ def chat_once(client, messages, use_tools=True, spinner=None): # --served-model-name, so make it configurable (SPEAR_MODEL_NAME). model=os.environ.get("SPEAR_MODEL_NAME", "qwen3"), messages=messages, - # Sampling temperature (SPEAR_TEMP). 0.25 gives more conservative, - # consistent edits on Qwen3-Coder-Next (less prone to over-eager - # refactors like dropping includes). NOTE: on the older dense/A3B model - # a low temp starved the sampler into repetition loops; if that recurs, - # raise SPEAR_TEMP back toward 0.7. + # Sampling temperature (SPEAR_TEMP). A low value gives conservative, + # consistent edits; if it starves the sampler into repetition loops, + # raise SPEAR_TEMP toward 0.7. temperature=float(os.environ.get("SPEAR_TEMP", "0.25")), top_p=0.8, # Big enough that a full file rewrite (write_file with the whole new diff --git a/client/doc/source/training_host_setup.rst b/client/doc/source/training_host_setup.rst index 26fb397..e852fce 100644 --- a/client/doc/source/training_host_setup.rst +++ b/client/doc/source/training_host_setup.rst @@ -1,8 +1,7 @@ SPEAR training host setup ============================ -This is an operator runbook for a future ```` Qwen3-Coder-Next -experiment. FT4B diagnostics found that the current SPEAR execution account +This is an operator runbook for a ```` Qwen3.8-27B fine-tune. FT4B diagnostics found that the current SPEAR execution account cannot authenticate through the bare ```` target, while the explicit operator destination/identity works. No setup command below has been executed by SPEAR. Do not use these instructions to modify the inference service or its @@ -32,21 +31,13 @@ environment's Axolotl binary. Installed versions are Axolotl 0.18.0, PyTorch 2.12.1+cu130, Transformers 5.14.1, PEFT 0.19.1, bitsandbytes 0.49.1, flash-linear-attention 0.4.1, and -Cut Cross Entropy 25.1.1. Tokenizer/config/chat-template-only assets for -``Qwen/Qwen3-Coder-Next`` were downloaded at revision -``a7fbcb5c0e12d62a448eaa0e260346bf5dcc0feb``; no model weights were fetched. - -Capacity and availability are separate: the assigned GPU has 97,887 MiB total -(suitable for the approximately 47 GiB no-expert QLoRA reference profile), but -14,599 MiB free while the existing llama-server uses 82,628 MiB. Current -availability is therefore ``BUSY``; FT4C does not stop or signal that workload. -Future operator-controlled training may stop the known inference service and -re-check free VRAM before launch. - -The training filesystem currently has roughly 100,937,000 KiB free. The -configured coarse model-storage reserve is 160 GiB, so doctor reports -``MODEL_STORAGE_CAPACITY=INSUFFICIENT`` and the full Qwen snapshot remains -deferred. No weights are downloaded while data is collecting. +Cut Cross Entropy 25.1.1. The source is ``Qwen/Qwen3.8-27B`` at revision +``8c0b3d30f3ae96f5c7f774de704bf0ada83e422a``. + +Capacity and availability are separate: the assigned GPU has 97,887 MiB +total, and the training run needs the inference service stopped or the +remaining memory checked first. Operator-controlled training may stop the +known inference service and re-check free VRAM before launch. Inference management discovery ------------------------------ @@ -103,10 +94,9 @@ pattern is conceptually:: uv pip install --no-build-isolation 'axolotl[deepspeed]' Choose the CUDA/PyTorch matrix appropriate for the actual GPU and approved -host image. Keep the environment isolated from inference. For Qwen3-Next, -install only the extra performance dependencies that the operator elects to -use after reviewing the current Axolotl model guide (for example Cut Cross -Entropy and the documented FLA version); do not enable optional kernels by +host image. Keep the environment isolated from inference. Install only the +extra performance dependencies that the operator elects to use after +reviewing the current Axolotl documentation; do not enable optional kernels by default. Trusted execution contract @@ -137,17 +127,14 @@ hardware capacity from TOTAL VRAM, current GPU availability from free VRAM and known workload activity, and dataset readiness. A BUSY current GPU is not a hardware-capacity failure. -Qwen3-Next planning notes -------------------------- - -The source must be the Transformers/Hugging Face -``Qwen/Qwen3-Coder-Next`` checkpoint at an immutable commit revision. GGUF is -an inference artifact and is rejected as a training source. The first profile -is conservative QLoRA: 4-bit loading, attention-only LoRA targets, no expert -targeting, gradient checkpointing, small micro-batch, and no packing. Axolotl's -Qwen3-Next guide gives approximately 47 GiB for no-expert-targeting QLoRA and -approximately 71 GiB when targeting experts; these are coarse planning values, -not an admission guarantee. Existing GPU processes must not be killed to make +Source model +------------ + +The source must be the Transformers/Hugging Face ``Qwen/Qwen3.8-27B`` +checkpoint at an immutable commit revision. GGUF is an inference artifact and +is rejected as a training source. The profile is conservative QLoRA: 4-bit +loading, attention-only LoRA targets, gradient checkpointing, small +micro-batch, and no packing. Existing GPU processes must not be killed to make room. Configure a minimum free-VRAM policy if the operator needs one. Non-training validation @@ -172,5 +159,4 @@ References ---------- * https://docs.axolotl.ai/docs/installation.html -* https://docs.axolotl.ai/docs/models/qwen3-next.html * https://docs.axolotl.ai/docs/cli.html diff --git a/client/eval/abstention/build_pairs.py b/client/eval/abstention/build_pairs.py index 23c80c2..82f3298 100644 --- a/client/eval/abstention/build_pairs.py +++ b/client/eval/abstention/build_pairs.py @@ -278,8 +278,8 @@ def load_tokenizer(): """The pinned tokenizer, offline. The rendering has to be the real one.""" from transformers import AutoTokenizer return AutoTokenizer.from_pretrained( - "Qwen/Qwen3-Coder-Next", - revision="a7fbcb5c0e12d62a448eaa0e260346bf5dcc0feb") + "Qwen/Qwen3.8-27B", + revision="8c0b3d30f3ae96f5c7f774de704bf0ada83e422a") def main(out_dir, tokenizer=None): diff --git a/client/models/remote_readiness.py b/client/models/remote_readiness.py index 3d0b1c4..0784161 100644 --- a/client/models/remote_readiness.py +++ b/client/models/remote_readiness.py @@ -260,7 +260,7 @@ def inspect(self) -> RemoteReadinessReport: printf 'model_snapshot_status=READY\n' else printf 'model_snapshot_status=NOT_PRESENT\n'; fi ram=$(awk '/MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null || true); printf 'ram_kib=%s\n' "${ram:-unknown}" -for module in torch transformers peft bitsandbytes qwen3_next; do +for module in torch transformers peft bitsandbytes; do "$py" - "$module" <<'PY' 2>/dev/null || true import importlib, sys name = sys.argv[1] @@ -377,7 +377,6 @@ def inspect(self) -> RemoteReadinessReport: else RemoteReadinessState.READY) checks["environment_readiness"] = state.value - checks["qwen3_next_compatibility"] = state.value return RemoteReadinessReport(state.value, tuple(dict.fromkeys(reasons)), checks, self.configuration.host, _now()) @@ -546,7 +545,7 @@ def local_doctor(store: TrainingStore | str | os.PathLike[str], checks["launcher"] = "ssh" checks["host"] = config.host checks["ssh_identity"] = "CONFIGURED" if config.ssh_identity_file else "SYSTEM_DEFAULT" - checks["model_source"] = "Qwen/Qwen3-Coder-Next" + checks["model_source"] = "Qwen/Qwen3.8-27B" checks["model_revision"] = ("PINNED" if (model_revision or config.source_model_revision) else "MISSING") diff --git a/client/tests/test_hardened_v3.py b/client/tests/test_hardened_v3.py index 7eb9844..3a920a0 100644 --- a/client/tests/test_hardened_v3.py +++ b/client/tests/test_hardened_v3.py @@ -27,7 +27,7 @@ POLICY = CommandPolicy() -# The command Coder-Next ran at step 78 of sye-uboot-patch/3, its paths +# The command the model ran at step 78 of sye-uboot-patch/3, its paths # shortened: refused as a heredoc and as a script, it ran as `python3 -c`. OBSERVED = ( diff --git a/client/tests/test_normative_precedence.py b/client/tests/test_normative_precedence.py index 514c0f3..e495bcb 100644 --- a/client/tests/test_normative_precedence.py +++ b/client/tests/test_normative_precedence.py @@ -339,7 +339,7 @@ def test_the_rule_names_the_artefacts_that_are_not_evidence(self): class ProseKeepsItsCitation(unittest.TestCase): """What the real backend wrote, and what sentence-local grounding did to it. - Qwen3-Coder-Next, bound to the standard, quoted the rule in full, concluded + The served model, bound to the standard, quoted the rule in full, concluded from it, and closed with a restatement carrying no citation of its own. The first version of this guard replaced that true, retrieved, correctly cited claim with a note saying nothing backed it -- a worse sentence than diff --git a/client/tests/test_public_boundary.py b/client/tests/test_public_boundary.py index aa224b9..43c77b9 100644 --- a/client/tests/test_public_boundary.py +++ b/client/tests/test_public_boundary.py @@ -258,10 +258,6 @@ class NoStaleProductPrefixEscapes(unittest.TestCase): JUSTIFIED = { # --- persistent identifiers, named where they are defined --- - ".gitignore": - "guards a 47 GB directory this deployment still has on disk; " - "renaming the rule without moving the directory exposes it", - # --- historical evidence: transcripts and measured incidents --- "client/TRAINING_DATA.md": "narrates a run against a path that was actually tried", @@ -269,8 +265,6 @@ class NoStaleProductPrefixEscapes(unittest.TestCase): "the same narrative: the path Axolotl was not usable at", "doc/source/model_serving.rst": "a recorded backend probe and its literal reply", - "pod-artifacts-qwen3coder/gguf-download.log": - "a download log from one run; evidence, not source", # --- checks that must name what they forbid --- "client/tests/test_public_boundary.py": diff --git a/client/tests/test_remote_readiness.py b/client/tests/test_remote_readiness.py index 1e9592d..d642434 100644 --- a/client/tests/test_remote_readiness.py +++ b/client/tests/test_remote_readiness.py @@ -67,7 +67,7 @@ def test_remote_success_parses_environment_and_ready_state(self): "training_root=usable\ndisk_available_kib=80000\n" "ram_kib=1000000\npackage=torch:2.12.0\n" "package=transformers:5.8.0\npackage=peft:0.18.0\n" - "package=bitsandbytes:available\npackage=qwen3_next:available\n") + "package=bitsandbytes:available\n") runner = ProbeRunner([ok("host config"), ok(), ok(output)]) report = SSHRemoteProbe(self.config(), runner).inspect() self.assertEqual(report.state, RemoteReadinessState.READY.value) diff --git a/client/tests/test_training_bundle.py b/client/tests/test_training_bundle.py index a08446e..804f50c 100644 --- a/client/tests/test_training_bundle.py +++ b/client/tests/test_training_bundle.py @@ -40,70 +40,38 @@ def positive_store(self, root): ])) def test_source_profiles_and_gguf_rejection(self): - default = SourceModelProfile.named("qwen3_coder_next_sft") - self.assertEqual(default.base_model, "Qwen/Qwen3-Coder-Next") + default = SourceModelProfile.named("qwen38_27b_sft") + self.assertEqual(default.base_model, "Qwen/Qwen3.8-27B") self.assertEqual(default.source_kind, "instruct_post_trained") - base = SourceModelProfile.named("qwen3_coder_next_base") - self.assertEqual(base.base_model, "Qwen/Qwen3-Coder-Next-Base") - base.validate() + self.assertIsNone(default.revision) + default.validate() with self.assertRaises(TrainingBundleError): replace(default, base_model="deployed/model.gguf").validate() - def test_axolotl_configs_are_semantic_qlora_and_conservative_moe(self): + def test_axolotl_configs_are_semantic_qlora(self): generator = AxolotlConfigGenerator(SourceModelProfile(), AxolotlProfile()) sft, kto, dpo = generator.sft(), generator.kto(), generator.dpo() self.assertIn("adapter: qlora", sft) self.assertIn("load_in_4bit: true", sft) - # load_in_4bit alone does not quantize this model's routed experts: - # under transformers 5.x they are fused 3-D nn.Parameter tensors and - # bitsandbytes only replaces nn.Linear. Asking for 4-bit without this - # flag is how a run ended up holding 148 GiB of bf16 experts. - self.assertIn("quantize_moe_experts: true", sft) + self.assertIn("base_model: \"Qwen/Qwen3.8-27B\"", sft) self.assertIn("message_field_training: train", sft) self.assertIn("chat_template: tokenizer_default", sft) - # Conservative means no expert TARGETING -- a different thing from - # expert quantization, which the line above requires. The targeting - # section must be absent, and routed experts must never appear as - # lora_target_modules: they are parameters, not modules. - self.assertNotIn("lora_target_parameters", sft) - self.assertNotIn("gate_up_proj", sft) self.assertIn("rl: kto", kto) self.assertIn("rl: dpo", dpo) self.assertNotIn("<|im_start|>", sft + kto + dpo) - def test_feasibility_depends_on_how_the_experts_are_loaded(self): - """96 GiB is insufficient or ample depending on one flag. - - The old table said ">= 96 GiB may fit" whatever the config, and the - config it shipped left the routed experts in bf16 -- where the weights - alone measured 152 010 MiB on a B200. A verdict that ignores the load - mode sends an operator to rent the wrong card either way. - """ + def test_feasibility_follows_the_card(self): card = TrainingHardwareReport( True, ("RTX PRO 6000",), 1, 96.0, ("12.0",), 256.0, 900.0, "linux", "test", VRAMFeasibility.UNKNOWN.value, (), ) - bf16 = card.classify(quantize_moe_experts=False) - self.assertEqual(bf16.vram_feasibility, - VRAMFeasibility.LIKELY_DOES_NOT_FIT.value) - self.assertTrue(any("bf16" in w for w in bf16.warnings)) - - quantized = card.classify(quantize_moe_experts=True) - self.assertEqual(quantized.vram_feasibility, VRAMFeasibility.MAY_FIT.value) - # Never LIKELY_FITS on that path: the figure behind it is Axolotl's - # documentation, not a measurement made here. - self.assertTrue(any("preflight" in w for w in quantized.warnings)) - - targeting = card.classify(quantize_moe_experts=True, expert_targeting=True) - self.assertEqual(targeting.vram_feasibility, VRAMFeasibility.MAY_FIT.value) - small = replace(card, total_vram_gib=48.0).classify( - quantize_moe_experts=True, expert_targeting=True) - self.assertEqual(small.vram_feasibility, - VRAMFeasibility.LIKELY_DOES_NOT_FIT.value) - - # Told nothing, it stays coarse and says so. - silent = card.classify() - self.assertTrue(any("not declared" in w for w in silent.warnings)) + + for vram, verdict in ((96.0, VRAMFeasibility.LIKELY_FITS), + (48.0, VRAMFeasibility.MAY_FIT), + (24.0, VRAMFeasibility.LIKELY_DOES_NOT_FIT), + (None, VRAMFeasibility.UNKNOWN)): + self.assertEqual(replace(card, total_vram_gib=vram).classify().vram_feasibility, + verdict.value) def test_freeze_is_deterministic_immutable_and_masked(self): with tempfile.TemporaryDirectory() as directory: diff --git a/client/tests/test_training_jobs.py b/client/tests/test_training_jobs.py index a0f3ef5..105f3da 100644 --- a/client/tests/test_training_jobs.py +++ b/client/tests/test_training_jobs.py @@ -11,7 +11,7 @@ def job(job_id="ftjob_" + "a" * 24): return TrainingJob( job_id, "SFT", "training_bundle", "/bundle", "b" * 64, "c" * 64, - "Qwen/Qwen3-Coder-Next", "deadbeef", {"train": "d" * 64}, + "Qwen/Qwen3.8-27B", "deadbeef", {"train": "d" * 64}, "fake", "fake", f"fake://jobs/{job_id}", ) diff --git a/client/training/__main__.py b/client/training/__main__.py index e9d8054..b4b50ad 100644 --- a/client/training/__main__.py +++ b/client/training/__main__.py @@ -43,8 +43,8 @@ def _parser() -> argparse.ArgumentParser: if name == "freeze": item.add_argument("--output", required=True) - item.add_argument("--profile", default="qwen3_coder_next_sft", - choices=("qwen3_coder_next_sft", "qwen3_coder_next_base")) + item.add_argument("--profile", default="qwen38_27b_sft", + choices=("qwen38_27b_sft",)) item.add_argument("--base-model") item.add_argument("--tokenizer-path") item.add_argument("--hardware-report", action="store_true") diff --git a/client/training/training_bundle.py b/client/training/training_bundle.py index 112a6e9..13b6bb5 100644 --- a/client/training/training_bundle.py +++ b/client/training/training_bundle.py @@ -29,7 +29,7 @@ BUNDLE_SCHEMA_VERSION = 1 -AXOLOTL_PROFILE_VERSION = 1 +AXOLOTL_PROFILE_VERSION = 2 MASKING_POLICY_VERSION = 1 @@ -51,18 +51,19 @@ class VRAMFeasibility(StrEnum): @dataclass(frozen=True) class SourceModelProfile: - profile: str = "qwen3_coder_next_sft" - base_model: str = "Qwen/Qwen3-Coder-Next" + profile: str = "qwen38_27b_sft" + base_model: str = "Qwen/Qwen3.8-27B" source_kind: str = SourceModelKind.INSTRUCT.value revision: str | None = None @classmethod def named(cls, name: str) -> "SourceModelProfile": - if name == "qwen3_coder_next_sft": - return cls() + # The model production serves: one model, versioned, and nothing else + # to train. The revision is the operator's to pin (training-execution + # .json); a start without one is refused. - if name == "qwen3_coder_next_base": - return cls(name, "Qwen/Qwen3-Coder-Next-Base", SourceModelKind.BASE.value) + if name == "qwen38_27b_sft": + return cls() raise ValueError(f"unknown source model profile: {name}") @@ -89,43 +90,10 @@ class AxolotlProfile: gradient_checkpointing: str = "true" lora_r: int = 16 lora_alpha: int = 32 - moe_targeting: str = "conservative_no_expert_targeting" - expert_target_modules: tuple[str, ...] = () - - # `load_in_4bit` alone does NOT quantize this model's routed experts under - # transformers 5.x, where Qwen3NextExperts fuses them into 3-D - # nn.Parameter tensors that bitsandbytes -- which replaces nn.Linear -- - # cannot reach. Axolotl added quantize_moe_experts for exactly that: it - # intercepts the load, quantizes to NF4 and frees the bf16 copies. - # Emitting a QLoRA config without it asks for 4-bit and gets 148 GiB of - # bf16 experts anyway, which is how a run ended up on a 179 GiB card. - # Both halves are measured, not read: LAYOUT_ONLY=1 in - # qwen3-finetune/cloud/load_preflight.py builds the model on the meta - # device and reports per_expert_modules (512,) on transformers 4.57.6 - # against fused_parameter (512, 1024, 2048) on 5.9.0, over the same - # 77.3B expert parameters -- 145 GiB left in bf16 versus 39 GiB in NF4. - - quantize_moe_experts: bool = True - def __post_init__(self) -> None: if self.sequence_len <= 0 or self.micro_batch_size <= 0: raise ValueError("invalid Axolotl size setting") - if self.moe_targeting not in {"conservative_no_expert_targeting", - "expert_targeting"}: - raise ValueError("unknown MoE targeting profile") - - # The profile and the module list have to agree in both directions: - # expert targeting materially changes the VRAM the run will need, so it - # is never inferred from one of the two being set. - - if self.moe_targeting == "expert_targeting" and not self.expert_target_modules: - raise ValueError("expert targeting requires explicit module names") - - if (self.moe_targeting == "conservative_no_expert_targeting" and - self.expert_target_modules): - raise ValueError("conservative profile cannot target expert modules") - @dataclass(frozen=True) class TrainingHardwareReport: @@ -206,62 +174,25 @@ def from_dict(cls, value: Mapping[str, object]) -> "TrainingHardwareReport": tuple(value.get("warnings", ())), ) - def classify(self, *, quantize_moe_experts: bool | None = None, - expert_targeting: bool = False) -> "TrainingHardwareReport": - """Feasibility, which depends on HOW the experts are loaded. - - A bare threshold table cannot answer this. For an 80B MoE, 96 GiB is - insufficient or ample depending on one flag: with the routed experts - left in bf16 the weights alone measured 152 010 MiB on a B200, and - with them quantized Axolotl documents ~47 GiB (no expert targeting) - and ~71 GiB (with). Told nothing, this stays coarse and pessimistic. - - Nothing here returns LIKELY_FITS on the quantized path: those numbers - are Axolotl's, not ours, and the harness has already been bitten once - by a documented figure that did not survive contact with the actual - stack. MAY_FIT means "provision it and run the load preflight", not - "go". - """ - extra: tuple[str, ...] = () + def classify(self) -> "TrainingHardwareReport": + """Coarse feasibility of a 4-bit QLoRA run of the dense 27B source. + The one measured point is a 96 GiB card, on which the FT-4 and FT-5 + runs completed; below it this cannot say more than MAY_FIT, which + means "run the load preflight", not "go". + """ if self.total_vram_gib is None: value = VRAMFeasibility.UNKNOWN - elif quantize_moe_experts is False: - # Experts stay bf16: the measured 148 GiB of weights, plus - # activations, optimizer and logits. - - value = (VRAMFeasibility.LIKELY_FITS if self.total_vram_gib >= 160 - else VRAMFeasibility.LIKELY_DOES_NOT_FIT) - extra = ("quantize_moe_experts is false: the routed experts load in " - "bf16 and the weights alone need ~148 GiB.",) - elif quantize_moe_experts is True: - # Never LIKELY_FITS here: the figures are Axolotl's own, and the - # docstring above says why a documented number is not a measurement. - - floor = 80.0 if expert_targeting else 56.0 - value = (VRAMFeasibility.MAY_FIT if self.total_vram_gib >= floor - else VRAMFeasibility.LIKELY_DOES_NOT_FIT) - extra = (f"Quantized-expert path: Axolotl documents ~{71 if expert_targeting else 47} " - f"GiB for this model. Unverified here -- confirm with a load " - f"preflight before committing a training run.",) - elif self.total_vram_gib >= 160: - value = VRAMFeasibility.LIKELY_FITS elif self.total_vram_gib >= 96: + value = VRAMFeasibility.LIKELY_FITS + elif self.total_vram_gib >= 48: value = VRAMFeasibility.MAY_FIT - elif self.total_vram_gib < 48: - value = VRAMFeasibility.LIKELY_DOES_NOT_FIT else: - value = VRAMFeasibility.UNKNOWN - - if quantize_moe_experts is None: - extra = ("MoE load mode not declared: this verdict assumes nothing " - "and is therefore coarse.",) + value = VRAMFeasibility.LIKELY_DOES_NOT_FIT warning = ("Peak memory depends on sequence length, batch size, LoRA targets, " "optimizer, checkpointing, packing, and library versions.") - self = replace(self, warnings=tuple(self.warnings) + extra) - return TrainingHardwareReport( self.cuda_available, self.gpu_models, self.gpu_count, self.total_vram_gib, self.compute_capabilities, @@ -344,16 +275,10 @@ def _common(self, dataset: str, output: str) -> list[str]: *( [f"revision: {_yaml_scalar(self.model.revision)}"] if self.model.revision else []), "tokenizer_type: AutoTokenizer", "trust_remote_code: false", "load_in_4bit: true", - f"quantize_moe_experts: {_yaml_scalar(p.quantize_moe_experts)}", "adapter: qlora", "lora_r: " + str(p.lora_r), "lora_alpha: " + str(p.lora_alpha), "lora_dropout: 0.0", "lora_target_linear: false", "lora_target_modules:", " - q_proj", " - k_proj", " - v_proj", " - o_proj", - # Routed experts are PARAMETERS, not modules: they are fused 3-D - # tensors, so naming them under lora_target_modules matches - # nothing. Axolotl takes them under lora_target_parameters. - *( ["lora_target_parameters:"] if p.expert_target_modules else []), - *(f" - {item}" for item in p.expert_target_modules), f"sequence_len: {p.sequence_len}", f"micro_batch_size: {p.micro_batch_size}", f"gradient_accumulation_steps: {p.gradient_accumulation_steps}", @@ -665,10 +590,6 @@ def freeze(self, output_root: str | os.PathLike[str], *, dry_run: bool = False if self.configuration.hardware_report else {"vram_feasibility": VRAMFeasibility.UNKNOWN.value, "reason": "training_host_not_specified"}), - "moe_targeting": {"profile": self.configuration.axolotl.moe_targeting, - "experts_targeted": self.configuration.axolotl.moe_targeting == - "expert_targeting", - "warning": "Expert targeting materially changes VRAM requirements."}, "future_output_lineage_schema": { "source_base_model": "required", "base_revision_hash": "required", "training_bundle_id": "required", "dataset_checksums": "required", @@ -847,13 +768,10 @@ def _runbook(configs, token_validation, smoke_test_only=False): "1. Validate `checksums.sha256` and run `python -m training validate-bundle ...`.", "2. Inspect governance, readiness, and held-out evaluation plan.", "3. Verify masking with Axolotl preprocessing debug output.", - "4. Measure, do not assume, that the card holds this config: the " - "readiness verdict is a table, the preflight is a measurement.", "", + "4. Preprocess on the training host, then train.", "", "```sh", *(["axolotl preprocess configs/axolotl-sft.yml --debug"] if has_sft else ["# No active training config: continue collecting/reviewing data."]), - *(["CONFIG_YAML=configs/axolotl-sft.yml bash " - "qwen3-finetune/cloud/load_preflight.sh"] if has_sft else []), *(["axolotl train configs/axolotl-sft.yml"] if has_sft and not smoke_test_only else []), "```", "", diff --git a/doc/source/img/spear.drawio b/doc/source/img/spear.drawio index 4c2eced..36766fc 100644 --- a/doc/source/img/spear.drawio +++ b/doc/source/img/spear.drawio @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/doc/source/model/inference_host.rst b/doc/source/model/inference_host.rst index eed4ef7..6a1fa21 100644 --- a/doc/source/model/inference_host.rst +++ b/doc/source/model/inference_host.rst @@ -26,7 +26,7 @@ What you are building ~/spear/ checkout (tens of MB) spear-chat --reds ~/spear-runtime/ │ SSH tunnel llama.cpp/ pinned build │ 127.0.0.1:8082 - models/gguf/ the weights, 79 GiB ▼ + models/gguf/ the weights, 27 GiB ▼ embed/ embedding worker venv ◄──── ssh … run-worker.sh config/ server.conf, gpu.conf log/ @@ -63,8 +63,8 @@ over SSH. Nothing on the host is exposed but ``sshd``. ``python3-dev``, ``curl``, ``wget`` - * - Disk, under the account's home - - ~100 GB: model 85 GB (79 GiB), embedder venv 5 GB, embedder cache - 4.3 GB, llama.cpp build 1 GB + - ~40 GB: model 28.6 GB, embedder venv 5 GB, embedder cache 4.3 GB, + llama.cpp build 1 GB - * - RAM - not critical once the weights are on the GPU @@ -73,13 +73,10 @@ over SSH. Nothing on the host is exposed but ``sshd``. - one account that owns the checkout and the runtime - see below -**Sizing the GPU.** The profile serves Qwen3-Coder-Next Q8_0: 79 GiB of -weights. Its KV cache is small because only 12 of its 48 layers use full -attention, with 2 KV heads of 256: at ``q8_0`` that is about 13 KB per token, -6.8 GB for the 524 288-token window. Measured: 89.5 of 97.9 GB in use at -512K. On a smaller card, lower ``SPEAR_SERVER_CTX`` (step 4); on a card that -cannot hold the weights at all, ``SPEAR_SERVER_NCPUMOE`` keeps the -mixture-of-experts weights in system RAM, at a large cost in speed. +**Sizing the GPU.** The profile serves Qwen3.8-27B Q8_0: 26.6 GiB of +weights, and the KV cache of the 262 144-token window beside them. Measured: +36.9 of 97.9 GB in use. On a smaller card, lower ``SPEAR_SERVER_CTX`` +(step 4). **The account.** Everything below lives in one account's home and needs no root, except installing the system unit (step 6). On a machine shared with @@ -126,8 +123,8 @@ build everything the manifest describes: $ scripts/bootstrap-runtime.sh --root ~/spear-runtime --gpu GPU-xxxxxxxx-… The dry run says what it would do and writes nothing. The real run clones -and builds the pinned llama.cpp, downloads the four model shards (budget -about an hour per 60 GB), builds the embedder's virtualenv, and writes +and builds the pinned llama.cpp, downloads the model file at its pinned +revision, builds the embedder's virtualenv, and writes ``config/server.conf`` and ``config/gpu.conf``. It is idempotent: interrupt it, run it again, and it keeps what is already correct. @@ -152,20 +149,16 @@ with the exact command line the launcher would run. is the deployment's from then on; no later bootstrap overwrites it. Every key is described in ``server/config/server.conf.example``. The ones to review: -``SPEAR_SERVER_CTX=524288`` - The context window. The model is trained at 262 144 tokens, so the - profile serves twice that with YaRN, enabled by the next two keys. - Lower it if the card is smaller: at or below 262 144 no scaling is used. - -``SPEAR_SERVER_NATIVE_CTX=262144`` and ``SPEAR_SERVER_ARCH=qwen3next`` - The trained length and the model architecture. When ``SPEAR_SERVER_CTX`` - exceeds the first, ``serve.sh`` adds ``--rope-scaling yarn --rope-scale 2 - --yarn-orig-ctx 262144`` **and** overrides - ``qwen3next.context_length``. The override is not optional: - ``llama-server`` caps each slot at the trained length it reads from the - GGUF, so without it a 512K request serves 256K and says so only in its log. - YaRN is static — it applies to short prompts too — which is why it is - switched on only past the trained length. +``SPEAR_SERVER_CTX=262144`` + The context window: the length the model was trained at. Lower it if the + card is smaller. + +``SPEAR_SERVER_NATIVE_CTX=262144`` and ``SPEAR_SERVER_ARCH=qwen35`` + The trained length and the model architecture. Only a window past the + first uses them: ``serve.sh`` then adds YaRN RoPE scaling **and** overrides + ``qwen35.context_length``, because ``llama-server`` caps each slot at the + trained length it reads from the GGUF. YaRN is static — it applies to + short prompts too — which is why it is switched on only past that length. ``SPEAR_SERVER_PORT=8010``, ``SPEAR_SERVER_HOST=127.0.0.1`` Keep the host on loopback. Clients use the port in their tunnel (step 8). @@ -191,10 +184,9 @@ Loading takes a minute or two. From a second shell: $ until curl -sf http://127.0.0.1:8010/health >/dev/null; do sleep 2; done $ curl -s http://127.0.0.1:8010/props | python3 -c \ 'import sys,json;print(json.load(sys.stdin)["default_generation_settings"]["n_ctx"])' - 524288 + 262144 -If that prints 262144, the architecture override is missing (step 4). Stop -the server with Ctrl-C. +Stop the server with Ctrl-C. 6. Supervision ============== @@ -315,19 +307,13 @@ A leading ``~/`` is expanded on the host. Indexing (``/reindex``, host $ curl -s http://127.0.0.1:8010/props | grep -o '"n_ctx":[0-9]*' client $ spear-chat --reds # the banner shows the model and the window -What the reference deployment measures at 512K: +What the reference deployment measures: .. list-table:: :widths: 50 50 * - VRAM in use - - 89.5 of 97.9 GB - * - Generation - - 156 tokens/s (157 at 98K: YaRN costs nothing measurable) - * - Prompt processing - - ~2 100 tokens/s — a 512K prompt takes about four minutes - * - Retrieval past the trained length - - a fact placed 40 % into a 311 744-token prompt, recalled exactly + - 36.9 of 97.9 GB, at the 262 144-token window 10. Updating and rolling back ============================= diff --git a/doc/source/model/model_history.rst b/doc/source/model/model_history.rst index 2ae0795..2da135c 100644 --- a/doc/source/model/model_history.rst +++ b/doc/source/model/model_history.rst @@ -48,60 +48,15 @@ Which model is served The project started on Qwen3-Coder-30B-A3B with a homemade QLoRA adapter (v1 → v3, retrained on a rented pod). It migrated on 2026-06-08 to the stock **Qwen3.6-35B-A3B**: the newer base beat the fine-tuned Coder outright, so the -adapter was dropped. Since 2026-06-23 the served model is **Qwen3-Coder-Next -(80B-A3B)**, chosen for native tool calls and *targeted* edits where the dense -Coder-32B rewrote whole files. The inference host serves it at roughly -157 tokens/s in Q8_0. +adapter was dropped. Since 2026-11-11 the served model is the dense +**Qwen3.8-27B**, in Q8_0, at its native 262144-token context. -Q8 was chosen over Q4 for accuracy: measured, it costs about 7 % of throughput -to double the precision of the weights. :doc:`/model/model_serving` describes the +Q8 is chosen over Q4 for accuracy. :doc:`/model/model_serving` describes the serving profile and how to override the model or load an adapter for one run. No fine-tune is served today ============================ -The first full-size runs were done in bf16 on a rented B200, because the -weights then occupy 152 GB and no single card here holds them. - -**That was the expensive way, and it was avoidable.** 4-bit had been ruled out -by reading the *installed* ``transformers`` 5.x, where the routed experts are -fused into 3-D parameters that bitsandbytes — which replaces ``nn.Linear`` — -cannot reach. But the published checkpoint stores those experts separately, -and the pod was pinned to ``transformers`` 4.57.6, which loads them as ordinary -``nn.Linear``, where bitsandbytes reaches every one. A 4-bit run would very -likely have fitted a 48–80 GB card. The measured layouts, and the loader flag -that fixes this under ``transformers`` 5.x, are in :ref:`the-moe-lesson`. - -Those runs did validate the chain end to end — dataset, pod, adapter, GGUF, -``--lora``, audit — which is what they were for. - -Measured, 2026-08-24: the adapter does not pay -============================================== - -Two adapters were trained on a rented B200 and served on the same Q8_0 base. - -.. list-table:: - :header-rows: 1 - :widths: 40 30 30 - - * - Configuration - - Without retrieval - - With retrieval - * - base, no adapter - - 18.2 % - - 89.6 % - * - usage-shaped adapter - - 22.1 % - - 83.1 % - * - descriptive adapter - - 16.9 % - - — - -Without retrieval the usage-shaped corpus helps a little and the descriptive -one hurts. With retrieval — the way the :term:`harness` actually runs — the adapter -*costs* six complete answers out of 37. It does not complement retrieval, it -competes with it. - -So no adapter is served. The pipeline is kept for the thing that would justify +No adapter is served. The pipeline is kept for the thing that would justify one: **behaviour, not facts**. What a governed dataset looks like, and what it takes to run a job on the card that also serves the model, is :doc:`/model/training`. diff --git a/doc/source/model/model_serving.rst b/doc/source/model/model_serving.rst index c311503..c27b92e 100644 --- a/doc/source/model/model_serving.rst +++ b/doc/source/model/model_serving.rst @@ -13,15 +13,15 @@ the ports, the sampling it sends, the smoke test — is :ref:`backends`. Current profile =============== -The profile is ``server/runtime/manifest.json``: Qwen3-Coder-Next, Q8_0, in -four shards (85 GB, 79 GiB), on a 96 GB card. ``server/inference/serve.sh`` turns the -deployment's ``config/server.conf`` into this command line: +The profile is ``server/runtime/manifest.json``: Qwen3.8-27B, a dense model, +in Q8_0, one 28.6 GB file, on a 96 GB card. ``server/inference/serve.sh`` +turns the deployment's ``config/server.conf`` into this command line: .. code-block:: console llama-server - --model /models/gguf/Qwen3-Coder-Next-Q8_0-00001-of-00004.gguf - --ctx-size 524288 + --model /models/gguf/Qwen3.8-27B-Q8_0.gguf + --ctx-size 262144 --parallel 1 --n-gpu-layers 99 --flash-attn on @@ -29,8 +29,11 @@ deployment's ``config/server.conf`` into this command line: --host 127.0.0.1 --port 8010 --jinja --threads 16 - --rope-scaling yarn --rope-scale 2 --yarn-orig-ctx 262144 - --override-kv qwen3next.context_length=int:524288 + +The reference deployment points ``SPEAR_SERVER_LLAMA_BIN`` at a wrapper that +adds the model card's reasoning and sampling settings: ``--reasoning-format +auto --no-reasoning-preserve``, medium reasoning effort, ``--temp 1.0 +--top-p 0.95 --top-k 20 --min-p 0``. The flags that matter ===================== @@ -39,25 +42,22 @@ The flags that matter Required. It enables the model's chat template, and with it native tool calling. Without it the assistant loses structured tool calls entirely. -``--n-gpu-layers 99``, and no ``--n-cpu-moe`` - Everything on the card. On a smaller GPU, ``SPEAR_SERVER_NCPUMOE`` keeps - the mixture-of-experts weights in system RAM while attention and the KV - cache stay on the GPU — the hybrid offload that makes this model usable on - a laptop-class card, at a large cost in speed. +``--n-gpu-layers 99`` + Everything on the card. ``--cache-type-k q8_0 --cache-type-v q8_0`` Quantised KV cache. Buys context length at a small quality cost. -``--ctx-size 524288`` and the YaRN flags - Twice the 262 144 tokens the model was trained at. Past that length the - RoPE positions are rescaled with YaRN, and the GGUF's ``context_length`` is - overridden because ``llama-server`` otherwise caps each slot at it. Both - are added by ``serve.sh`` only when the window exceeds the trained length, - since YaRN is static and would otherwise touch every short prompt too. - Measured: a fact 40 % into a 311 744-token prompt was recalled exactly, and - generation speed did not change. The :term:`harness` still truncates long tool - outputs at ``max_output_chars`` (10 000 by default) so a single verbose - build log cannot evict the conversation. +``--ctx-size 262144`` + The length the model was trained at. A window past it is served with YaRN: + ``serve.sh`` adds the RoPE scaling and overrides the GGUF's + ``context_length`` when ``SPEAR_SERVER_CTX`` exceeds + ``SPEAR_SERVER_NATIVE_CTX``, because ``llama-server`` otherwise caps each + slot at the trained length. YaRN is static and would touch every short + prompt too, so it is switched on only past that length. The + :term:`harness` still truncates long tool outputs at ``max_output_chars`` + (10 000 by default) so a single verbose build log cannot evict the + conversation. ``--parallel 1`` One slot. This is a single-user assistant; concurrency would only fragment @@ -81,9 +81,6 @@ the *build* rather than of a deployment: ``--jinja`` required for the chat template and therefore for tool calling; -``--n-cpu-moe`` - for a mixture-of-experts model, unless a deployment says otherwise; - the YaRN flags derived from ``SPEAR_SERVER_CTX``, ``SPEAR_SERVER_NATIVE_CTX`` and ``SPEAR_SERVER_ARCH`` as above. diff --git a/doc/source/model/training.rst b/doc/source/model/training.rst index 421a645..e81f38d 100644 --- a/doc/source/model/training.rst +++ b/doc/source/model/training.rst @@ -159,7 +159,7 @@ leaves the previous manifest byte-identical. Every bundle carries: * - ``evaluation-plan.json`` - Held-out only, including a general-control regression. * - ``RUNBOOK.md`` - - The human procedure, preflight included. + - The human procedure. * - ``checksums.sha256`` - What ``validate-bundle`` re-checks. @@ -169,84 +169,13 @@ assistant message; every earlier assistant message is context with hard error — that is how a model learns to reproduce the mistake it later recovered from. -.. _the-moe-lesson: +Will it fit? +============ -The MoE lesson -============== - -The bundle emits QLoRA configs for an 80B mixture-of-experts model, and the -single most expensive thing this project learned is that **"4-bit" is not a -property of a config, it is a property of a load**. - -``load_in_4bit`` makes bitsandbytes replace ``nn.Linear`` modules. Whether the -routed experts *are* ``nn.Linear`` depends on the installed ``transformers``: - -.. list-table:: - :header-rows: 1 - :widths: 30 40 30 - - * - ``transformers`` - - Routed expert layout - - ``load_in_4bit`` reaches them - * - 4.57.6 - - ``per_expert_modules (512,)`` - - yes - * - 5.9.0 - - ``fused_parameter (512, 1024, 2048)`` - - **no** - * - 5.14.1 / 5.16.0.dev0 - - ``fused_parameter (512, 1024, 2048)`` - - **no** - -Both rows are measured, not read: ``LAYOUT_ONLY=1`` in -``qwen3-finetune/cloud/load_preflight.py`` materialises the model on the meta -device from ``config.json`` alone — no weights, no GPU, no disk — and reports -the layout and the exact parameter counts. Over the same 77.3 B expert -parameters that is **145 GiB left in bf16** against **39 GiB in NF4**. - -So the emitted config sets ``quantize_moe_experts: true``, which is Axolotl's -patch of the *loader*: it quantizes every ≥3-D CUDA parameter as it lands and -disables ``caching_allocator_warmup``, which would otherwise pre-reserve the -bf16 size and eat the saving. Two consequences the config generator encodes: - -* routed experts are targeted through ``lora_target_parameters``, never - ``lora_target_modules`` — they are parameters, not modules; -* ``lora_target_linear`` must stay false, which Axolotl itself enforces. - -Asking for 4-bit without the flag is how a run ended up holding 148 GiB of -bf16 weights on a rented 179 GiB card, for a job that fits a far smaller one. - -Will it fit? Measure it -======================== - -``TrainingHardwareReport.classify()`` takes the load mode, because without it -the question has no answer: for this model 96 GiB is insufficient or ample -depending on one flag. It returns ``LIKELY_FITS`` only on the bf16 path at -≥160 GiB. On the quantized path it returns at most ``MAY_FIT``, and -``MAY_FIT`` means *provision it and run the preflight*, not *go*. Those -thresholds are Axolotl's documentation, and this project has already been bitten -once by a documented figure that did not survive contact with the stack. - -The preflight is the measurement: - -.. code-block:: console - - $ CONFIG_YAML=configs/axolotl-sft.yml bash qwen3-finetune/cloud/load_preflight.sh - -It refuses on disk first, naming the exact number of GB to add; stops the -inference server, because 5 GiB free out of 97 answers nothing; loads the real -checkpoint with the real config; reports how many expert parameters were -actually quantized on load; runs one forward + backward at the real sequence -length; prints the peak and the headroom; and restarts the server from a -``trap``, including after the OOM it exists to provoke. It writes -``load-preflight.json`` and exits non-zero on anything but ``FITS``. - -It reads its numbers from the bundle's own ``axolotl-sft.yml`` when given one, -otherwise from ``AxolotlProfile`` in ``training_bundle.py``, parsed with -``ast`` rather than imported — the harness's runtime dependencies have no -business on a training host, and a preflight that cannot run where the training -runs is decoration. It names which source it used, so a verdict cannot be -mistaken for one covering a config it never saw. +``TrainingHardwareReport.classify()`` gives a coarse verdict for a 4-bit QLoRA +run of the dense 27B source: ``LIKELY_FITS`` from 96 GiB, the card the FT-4 and +FT-5 runs completed on; ``MAY_FIT`` from 48 GiB, which means *try a short run +first*, not *go*; below that, ``LIKELY_DOES_NOT_FIT``. The operator surface ==================== @@ -282,13 +211,8 @@ The training host is the inference host (:ref:`inference_host`), whose reserved RTX PRO 6000 Blackwell with 96 GiB. The objective is that this card is sufficient and no GPU is rented. -The binding constraint there is **disk, not VRAM**: the bf16 shards of the -current base model are about 159 GB, more than the free space such a host -typically has. 4-bit does -not reduce that — bitsandbytes quantizes at load, from shards that must land on -disk first. Growing that filesystem is the cheap fix, and it is why the -preflight's first check is a disk check that prints the deficit rather than a -suggestion to rent something. +The bf16 shards of the base model must land on disk before bitsandbytes +quantizes them at load: 4-bit does not reduce the disk a run needs. .. note:: @@ -302,7 +226,7 @@ Related material ================ ``qwen3-finetune/`` holds the experiment side: the LoRA trainers, the pod -scripts, the corpus tooling (``scripts/merge_corpora.py``; the builders that -read a deployment's own sources are deployment-specific and not shipped) and -the preflight. It is a working area, not a +scripts and the corpus tooling (``scripts/merge_corpora.py``; the builders that +read a deployment's own sources are deployment-specific and not shipped). It +is a working area, not a product surface — the governed path is the one described above. diff --git a/doc/source/start/container.rst b/doc/source/start/container.rst index 578b911..eb60700 100644 --- a/doc/source/start/container.rst +++ b/doc/source/start/container.rst @@ -58,23 +58,6 @@ Only ``scripts/`` goes on ``PATH``. ``scripts/docker/`` holds a ``build.sh``, and a shell that has also sourced another tree's ``env.sh`` with a ``build.sh`` of its own would then have two. -A workstation for the REDS project image ----------------------------------------- - -On a machine that only runs the image, one script does everything once: it -trusts the REDS registry's certificate, logs in, pulls the project image, -installs the ``spear`` launcher and writes ``~/.config/spear/local.conf``. - -.. code-block:: console - - $ . ./env.sh # puts scripts/ on PATH - $ spear-client-setup.sh # asks for the registry's pull password - -The pull password is not in the repository; ask for it, then type it when -asked or give it in ``SPEAR_REGISTRY_PASSWORD``. Run the script again to -update the image. ``spear-chat`` also needs your ``~/.ssh/id_ed25519.pub`` -on the inference host. - Base and project: get and update --------------------------------- diff --git a/qwen3-finetune/README.md b/qwen3-finetune/README.md index 3001c01..16e5280 100644 --- a/qwen3-finetune/README.md +++ b/qwen3-finetune/README.md @@ -11,9 +11,6 @@ scripts/merge_corpora.py merge JSONL sample sets, keeping their system scripts/merge_and_convert.sh merge the adapter and quantize to GGUF scripts/build_edit_discipline.py samples for whole-file edit behaviour scripts/{wget,resilient}_download.sh resumable weight downloads -cloud/load_preflight.{sh,py} does this card actually hold the model, loaded - the way training will load it? Measured, not - deduced. cloud/train_qlora_*.py per-base trainers cloud/runpod_train*.sh drive a rented pod setup.sh · activate.sh environment diff --git a/qwen3-finetune/cloud/README.md b/qwen3-finetune/cloud/README.md index 5de5058..1e53857 100644 --- a/qwen3-finetune/cloud/README.md +++ b/qwen3-finetune/cloud/README.md @@ -6,24 +6,8 @@ inference host already has. | Script | Where | |---|---| -| `load_preflight.sh` / `load_preflight.py` | the training host — **run this first** | | `runpod_train.sh` + `train_qlora_35b.py` | any 48 GB pod | | `runpod_train_coder32.sh` + `train_qlora_coder32.py` | dense-coder QLoRA | -| `train_lora_qwen3next.py` | a pod with ~160 GB for the weights alone | - -## Measure, do not deduce - -`load_preflight.sh` answers one question empirically: does this card hold the -model, loaded exactly the way training will load it? Stop inference, load with -the real quantization config, measure the peak, unload, restart inference. - -It exists because the answer was guessed twice and was wrong twice — once at -the cost of a rented B200 for a job that would have fitted a far smaller card. -A documentation figure said one thing and the installed library did another. - -The same rule the harness applies to sandboxes and budgets: if it says FITS, -the local card does the run and no pod is booked; if it says OOM, it says so -in the ten minutes a load takes rather than in the third hour of a paid one. ## What is not here diff --git a/qwen3-finetune/cloud/load_preflight.py b/qwen3-finetune/cloud/load_preflight.py deleted file mode 100644 index 5f19563..0000000 --- a/qwen3-finetune/cloud/load_preflight.py +++ /dev/null @@ -1,364 +0,0 @@ -"""Measure what one training step of THIS config actually costs on THIS card. - -Not a size estimate. It loads the real checkpoint with the real quantization -config, attaches the real LoRA adapter, and runs one forward + backward at the -real sequence length, then reports the peak. Weights-only numbers answer the -wrong question: at sequence_len 32768 the activations and the logits are a -large share of the peak, and they are exactly what a table cannot predict. - -The config is not restated here -- it is imported from training_bundle, the -same object that writes the Axolotl YAML. If the two ever disagree, the -measurement is worthless, so there is only one of them. - -Driven by cloud/load_preflight.sh, which owns the card and the inference -server. Env: BASE_MODEL, MOE_QUANT (1/0), LOAD_DTYPE (4bit/bf16). - -LAYOUT_ONLY=1 answers the cheap half -- which expert layout the installed -transformers builds, and therefore whether load_in_4bit reaches the experts -- -from config.json alone, no weights, no GPU, no disk. -""" -import ast -import json -import os -import re -import sys -import time -from pathlib import Path -from types import SimpleNamespace - -import torch - -_FIELDS = ("sequence_len", "micro_batch_size", "gradient_accumulation_steps", - "learning_rate", "lora_r", "lora_alpha", "gradient_checkpointing") -_BUNDLE = Path(__file__).resolve().parents[2] / "client" / "training/training_bundle.py" - - -def _from_yaml(path): - """The config as SHIPPED: the bundle's own axolotl-sft.yml. - - Preferred when present, because it is the file the training command will - actually read -- measuring anything else measures a different run. - """ - text = Path(path).read_text() - values = {} - for field in _FIELDS: - match = re.search(rf"^{field}:\s*(\S+)", text, re.M) - if match: - values[field] = ast.literal_eval(match.group(1)) if match.group(1)[0].isdigit() \ - else match.group(1) - base = re.search(r"^base_model:\s*(\S+)", text, re.M) - return SimpleNamespace(**values), base.group(1) if base else None, str(path) - - -# Last resort only -- see _from_source(). Kept in sync by hand with -# training_bundle.AxolotlProfile, which is exactly why it is the last resort. -_FALLBACK = dict(sequence_len=32768, micro_batch_size=1, - gradient_accumulation_steps=16, learning_rate=0.0001, - lora_r=16, lora_alpha=32, gradient_checkpointing="true") -_FALLBACK_BASE = "Qwen/Qwen3-Coder-Next" - - -def _from_source(): - """Otherwise the AxolotlProfile defaults, read from the dataclass SOURCE. - - Parsed with ast rather than imported: training_bundle drags in the whole - harness (openai, chromadb, ...), none of which belongs on a training host, - and a preflight that cannot run where the training runs is decoration. The - values still come from the one file that writes the YAML, so the two cannot - drift apart silently. - - A training host may carry only the qwen3-finetune tree, with no harness - beside it. That is not a reason to refuse to measure -- it is a reason to - say out loud which numbers are being measured, so nobody reads the verdict - as covering a config it never saw. - """ - if not _BUNDLE.is_file(): - return SimpleNamespace(**_FALLBACK), _FALLBACK_BASE, ( - f"built-in defaults ({_BUNDLE} absent) -- pass CONFIG_YAML=" - f"/configs/axolotl-sft.yml to measure the config you will train") - tree = ast.parse(_BUNDLE.read_text()) - values, base = {}, None - for node in ast.walk(tree): - if isinstance(node, ast.ClassDef) and node.name in ("AxolotlProfile", - "SourceModelProfile"): - for item in node.body: - if isinstance(item, ast.AnnAssign) and item.value is not None: - name = item.target.id - try: - literal = ast.literal_eval(item.value) - except ValueError: - continue - if name in _FIELDS: - values[name] = literal - elif name == "base_model": - base = literal - return SimpleNamespace(**values), base, f"{_BUNDLE.name}:AxolotlProfile" - - -if os.environ.get("CONFIG_YAML"): - PROFILE, _BASE, CONFIG_SOURCE = _from_yaml(os.environ["CONFIG_YAML"]) -else: - PROFILE, _BASE, CONFIG_SOURCE = _from_source() -BASE_MODEL = os.environ.get("BASE_MODEL") or _BASE -MOE_QUANT = os.environ.get("MOE_QUANT", "1") == "1" -LOAD_DTYPE = os.environ.get("LOAD_DTYPE", "4bit") -# The measurement is the point; a step that takes an hour is not one. Sequence -# length drives the activation peak, so it stays at the training value unless -# explicitly lowered -- and if it is lowered, the verdict says so. -SEQ_LEN = int(os.environ.get("SEQ_LEN", PROFILE.sequence_len)) - - -def gib(n_bytes): - return n_bytes / 1024 ** 3 - - -def smi_used(): - """Peak as the driver sees it: torch's allocator misses cuBLAS and NCCL.""" - try: - free, total = torch.cuda.mem_get_info() - return gib(total - free) - except Exception: - return float("nan") - - -def expert_layout(model): - """Per-expert nn.Linear, or one fused 3-D parameter? - - This is the whole reason quantize_moe_experts exists. bitsandbytes swaps - nn.Linear modules; it cannot see a 3-D nn.Parameter. Under transformers - 4.57 the experts are Linears and plain load_in_4bit reaches them; under 5.x - they are fused and it silently does not. - """ - for name, module in model.named_modules(): - if name.endswith("mlp.experts"): - for attr in ("gate_up_proj", "down_proj"): - value = getattr(module, attr, None) - if isinstance(value, torch.nn.Parameter): - return "fused_parameter", tuple(value.shape), str(value.dtype) - children = [c for c in module.children()] - if children: - return "per_expert_modules", (len(children),), str( - next(module.parameters()).dtype) - return "unknown", (), "" - - -def layout_only(): - """The pivotal question, answered for the price of one config.json. - - Whether load_in_4bit reaches the routed experts is a property of the - installed transformers, not of the weights: it depends on whether - Qwen3NextExperts builds per-expert nn.Linear or one fused 3-D - nn.Parameter. Materialising the model on the meta device settles it with - zero bytes downloaded and zero VRAM -- which is what makes it runnable - before the disk is grown. - - The parameter counts that follow are exact (from the shapes), so the - weight footprint is arithmetic, not an estimate. The training PEAK still - is not: that needs the real load and the real step. - """ - import transformers - from transformers import AutoConfig, AutoModelForCausalLM - - config = AutoConfig.from_pretrained(BASE_MODEL, trust_remote_code=True) - print(f"== layout probe ==\n {BASE_MODEL}, transformers {transformers.__version__}") - with torch.device("meta"): - model = AutoModelForCausalLM.from_config(config, trust_remote_code=True) - layout, shape, dtype = expert_layout(model) - expert_params = sum(p.numel() for name, p in model.named_parameters() - if ".mlp.experts." in name) - total_params = sum(p.numel() for p in model.parameters()) - other = total_params - expert_params - print(f" routed experts: {layout} {shape or ''}") - print(f" {expert_params / 1e9:.1f}B parameters in routed experts, " - f"{other / 1e9:.1f}B elsewhere ({total_params / 1e9:.1f}B total)") - reachable = layout == "per_expert_modules" - print(f" bitsandbytes replaces nn.Linear, so load_in_4bit reaches them " - f"on this stack: {reachable}") - bf16_all = gib(total_params * 2) - nf4_all = gib(total_params * 0.5 + total_params * 0.03) - mixed = gib(expert_params * 2 + other * 0.53) - print(f"== weight footprint (exact arithmetic, no activations) ==") - print(f" everything bf16: {bf16_all:.0f} GiB") - print(f" everything NF4: {nf4_all:.0f} GiB") - print(f" experts bf16, rest NF4: {mixed:.0f} GiB <- the failing config") - if reachable: - print("\nOn THIS transformers, a plain load_in_4bit is enough; " - "quantize_moe_experts is the belt to that pair of braces and " - "costs nothing.") - else: - print("\nOn THIS transformers, a plain load_in_4bit silently leaves " - "the experts in bf16. quantize_moe_experts is mandatory.") - return 0 - - -def _apply_axolotl_moe_patch(): - """Install axolotl's on-load MoE quantization, or say plainly that it is not - installed. - - Returns a callable that reports how many expert parameters were actually - quantized -- the one honest check that the flag did something, rather than - a layout guess made before the weights arrived. - """ - try: - from axolotl.monkeypatch.moe_quant import ( - get_moe_quantized_count, patch_moe_quantization_on_load, - patch_peft_target_parameters_matching, - ) - except ImportError as exc: - print(f" axolotl MoE quantization unavailable ({exc})") - print(" -> the experts will load however this transformers builds " - "them. On 4.x they are per-expert nn.Linear and bitsandbytes " - "reaches them unaided; on 5.x they are fused and it does not. " - "The layout check below decides, and refuses to call the result " - "a measurement of the declared config if it was the other one.") - return lambda: 0 - cfg = SimpleNamespace(load_in_8bit=False, load_in_4bit=True, - bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True) - patch_moe_quantization_on_load(cfg) - patch_peft_target_parameters_matching() - print(" axolotl MoE on-load quantization: patched") - return get_moe_quantized_count - - -def main(): - if os.environ.get("LAYOUT_ONLY") == "1": - return layout_only() - if not torch.cuda.is_available(): - print("No CUDA device visible -- nothing to measure.", file=sys.stderr) - return 2 - import transformers - from transformers import AutoModelForCausalLM - - name = torch.cuda.get_device_name(0) - total = gib(torch.cuda.get_device_properties(0).total_memory) - print(f"== target ==\n {name}, {total:.1f} GiB total, " - f"{gib(torch.cuda.mem_get_info()[0]):.1f} GiB free") - print(f" transformers {transformers.__version__}, torch {torch.__version__}") - print(f"== config (from {CONFIG_SOURCE}) ==") - print(f" {BASE_MODEL} dtype={LOAD_DTYPE} quantize_moe_experts={MOE_QUANT}") - print(f" seq_len={SEQ_LEN} micro_batch={PROFILE.micro_batch_size} " - f"lora_r={PROFILE.lora_r} checkpointing={PROFILE.gradient_checkpointing}") - if SEQ_LEN != PROFILE.sequence_len: - print(f" !! seq_len lowered from {PROFILE.sequence_len}: the peak below " - f"UNDERSTATES the training peak") - - quantized_count = lambda: 0 - kwargs = {"dtype": torch.bfloat16, "device_map": {"": 0}, - "attn_implementation": os.environ.get("ATTN_IMPL", "sdpa")} - if LOAD_DTYPE == "4bit": - from transformers import BitsAndBytesConfig - kwargs["quantization_config"] = BitsAndBytesConfig( - load_in_4bit=True, bnb_4bit_quant_type="nf4", - bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16, - ) - if MOE_QUANT: - # Axolotl's patch is what makes load_in_4bit reach fused experts: - # it wraps transformers' set_param_for_module and quantizes every - # >=3-D CUDA parameter as it lands, and disables the caching - # allocator warmup that would otherwise pre-reserve the bf16 size - # and eat the saving it just made. Reproduced by CALLING axolotl, - # not by reimplementing it -- a preflight that quantizes - # differently from the trainer measures a run nobody will make. - quantized_count = _apply_axolotl_moe_patch() - - torch.cuda.reset_peak_memory_stats() - started = time.time() - model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, **kwargs) - load_seconds = time.time() - started - layout, shape, dtype = expert_layout(model) - weights_peak = gib(torch.cuda.max_memory_allocated()) - experts_quantized = quantized_count() - print(f"== weights loaded in {load_seconds:.0f}s ==") - print(f" routed experts: {layout} {shape or ''} {dtype}") - print(f" expert parameters quantized on load: {experts_quantized}") - print(f" allocated {gib(torch.cuda.memory_allocated()):.1f} GiB, " - f"peak {weights_peak:.1f} GiB, driver sees {smi_used():.1f} GiB") - - # "Did the flag do anything" is answered by the count when axolotl is - # present, and by the layout when it is not. Either way the answer is - # taken after the weights landed, not predicted before. - honest = not (MOE_QUANT and LOAD_DTYPE == "4bit" and not experts_quantized - and layout == "fused_parameter" and "bfloat16" in dtype) - if not honest: - print("\n!! The experts loaded FUSED and in bf16, and nothing " - "quantized them: this is the config that does not fit, not the " - "one the bundle emits. Install axolotl and re-run.", - file=sys.stderr) - - from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training - if LOAD_DTYPE == "4bit": - model = prepare_model_for_kbit_training( - model, use_gradient_checkpointing=PROFILE.gradient_checkpointing != "false") - model = get_peft_model(model, LoraConfig( - r=PROFILE.lora_r, lora_alpha=PROFILE.lora_alpha, lora_dropout=0.0, - bias="none", task_type="CAUSAL_LM", - target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], - )) - if PROFILE.gradient_checkpointing != "false": - model.gradient_checkpointing_enable() - model.enable_input_require_grads() - trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) - print(f"== adapter ==\n {trainable / 1e6:.1f}M trainable parameters") - - from torch.optim import AdamW - optimizer = AdamW([p for p in model.parameters() if p.requires_grad], lr=PROFILE.learning_rate) - ids = torch.randint(0, 1000, (PROFILE.micro_batch_size, SEQ_LEN), device="cuda") - torch.cuda.reset_peak_memory_stats() - model.train() - step_failed = None - started = time.time() - try: - loss = model(input_ids=ids, labels=ids).loss - loss.backward() - optimizer.step() - optimizer.zero_grad(set_to_none=True) - torch.cuda.synchronize() - except torch.cuda.OutOfMemoryError as exc: - step_failed = str(exc).splitlines()[0] - step_seconds = time.time() - started - step_peak = gib(torch.cuda.max_memory_allocated()) - driver_peak = smi_used() - - print(f"== one training step ({step_seconds:.0f}s) ==") - if step_failed: - print(f" OUT OF MEMORY: {step_failed}") - else: - print(f" loss {loss.item():.3f}") - print(f" step peak {step_peak:.1f} GiB allocated, driver {driver_peak:.1f} GiB " - f"of {total:.1f} GiB") - - verdict = ("OOM" if step_failed else - "FITS" if honest else "MEASURED_THE_WRONG_CONFIG") - headroom = total - driver_peak - if verdict == "FITS": - print(f"\nVERDICT: FITS -- {headroom:.1f} GiB headroom at seq_len {SEQ_LEN}, " - f"micro_batch {PROFILE.micro_batch_size}." - + ("" if headroom > 8 else " Thin: raising sequence length, batch " - "size or LoRA targets will not survive.")) - else: - print(f"\nVERDICT: {verdict}") - - report = { - "base_model": BASE_MODEL, "gpu": name, "total_vram_gib": round(total, 1), - "load_dtype": LOAD_DTYPE, "quantize_moe_experts": MOE_QUANT, - "expert_layout": layout, "expert_dtype": dtype, - "experts_quantized_on_load": experts_quantized, - "sequence_len": SEQ_LEN, "micro_batch_size": PROFILE.micro_batch_size, - "lora_r": PROFILE.lora_r, - "weights_peak_gib": round(weights_peak, 1), - "step_peak_gib": round(step_peak, 1), - "driver_peak_gib": round(driver_peak, 1), - "transformers": transformers.__version__, "torch": torch.__version__, - "verdict": verdict, "measured_the_declared_config": honest, - } - out = Path(os.environ.get("PREFLIGHT_REPORT", "load-preflight.json")) - out.write_text(json.dumps(report, indent=2) + "\n") - print(f" report: {out}") - - del model, optimizer, ids - torch.cuda.empty_cache() - return 0 if verdict == "FITS" else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/qwen3-finetune/cloud/load_preflight.sh b/qwen3-finetune/cloud/load_preflight.sh deleted file mode 100644 index fe47bcc..0000000 --- a/qwen3-finetune/cloud/load_preflight.sh +++ /dev/null @@ -1,130 +0,0 @@ -#!/bin/bash -# Does this card actually hold the model, loaded the way training will load it? -# -# Answers ONE question, empirically, and trains nothing: -# -# stop inference -> load with the exact quantization config -> measure the -# peak -> unload -> restart inference -# -# It exists because the answer has been guessed twice and been wrong twice. A -# documentation figure said one thing, a reading of the installed transformers -# said another, and the run that settled it cost a rented B200 -- for a job -# that, on the stack it actually pinned, would have fitted a far smaller card. -# The rule this file enforces is the one the rest of the harness already -# applies to sandboxes and budgets: measure, do not deduce. -# -# bash cloud/load_preflight.sh # 4-bit with MoE experts quantized -# MOE_QUANT=0 bash cloud/load_preflight.sh # 4-bit WITHOUT -- the failing case -# LOAD_DTYPE=bf16 bash cloud/load_preflight.sh -# -# Run it ON the training host. On a shared host that means the reserved card, which -# is also the card serving the model: this script stops the server, and puts it -# back, because 5 GiB free out of 97 answers nothing. -# -# The point is to make renting a card unnecessary. If this says FITS, the -# local card does the fine-tune and no pod is booked; if it says -# OOM, it says so in the ten minutes a load takes rather than in the third hour -# of a paid run. -set -e -cd "$(dirname "$0")/.." - -BASE_MODEL="${BASE_MODEL:-Qwen/Qwen3-Coder-Next}" -BASE_GB="${BASE_GB:-159}" -MOE_QUANT="${MOE_QUANT:-1}" -LOAD_DTYPE="${LOAD_DTYPE:-4bit}" -SERVE_SCRIPT="${SERVE_SCRIPT:-$HOME/spear/serve-model.sh}" -export HF_HOME="${HF_HOME:-$HOME/spear/hf}" -export HF_HUB_CACHE="${HF_HUB_CACHE:-$HF_HOME/hub}" -export HF_HUB_DISABLE_XET=1 -export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True -export PYTHONUNBUFFERED=1 - -# ── disk, before anything else ─────────────────────────────────────────── -# The binding constraint may not be the card, it is the filesystem. -# Measured 2026-08-25: /home had 97 GB free of 1399, most of the rest being a -# colleagues' Hugging Face cache that is not ours to purge. The bf16 shards are -# 159 GB, and 4-bit does not change that: bitsandbytes quantizes AT LOAD, from -# shards that must land on disk first. Disk is the cheap constraint -- it is -# bought, not rented by the hour -- so this check exists to name the exact -# number of GB to add, in two seconds, rather than to have it discovered at -# 90 % of a download. -CACHED_DIR="$HF_HUB_CACHE/models--${BASE_MODEL//\//--}" -HAVE_GB=$(du -sBG --apparent-size "$CACHED_DIR" 2>/dev/null | awk '{print $1+0}') -HAVE_GB="${HAVE_GB:-0}" -NEED_GB=$((BASE_GB - HAVE_GB)); [ "$NEED_GB" -lt 0 ] && NEED_GB=0 -FREE_GB=$(df -BG --output=avail "$HF_HOME" 2>/dev/null | tail -1 | tr -dc '0-9') -FREE_GB="${FREE_GB:-0}" -echo "== disk ==" -echo " $HF_HOME: ${FREE_GB} GB free, ${HAVE_GB} GB cached, ${NEED_GB} GB to fetch" -if [ "$FREE_GB" -lt "$NEED_GB" ]; then - SHORT_GB=$((NEED_GB - FREE_GB)) - cat >&2 < (~45 GB). Valid for the - VRAM question, but note it measures THAT checkpoint, not the bf16 one the - bundle YAML names. - -What is NOT an option: purging the caches under other users' home on this -shared machine. -EOF - exit 1 -fi - -# ── the card ───────────────────────────────────────────────────────────── -GPU_CONF="${GPU_CONF:-$HOME/spear/client/active-gpu.conf}" -if [ -z "$FT_GPU" ] && [ -f "$GPU_CONF" ]; then - FT_GPU=$(tr -d '[:space:]' < "$GPU_CONF") -fi -[ -n "$FT_GPU" ] || { echo "No GPU pinned: set FT_GPU or fill $GPU_CONF" >&2; exit 2; } -export CUDA_VISIBLE_DEVICES="$FT_GPU" - -STOPPED=0 -if pgrep -f "build/bin/llama-server --model" >/dev/null 2>&1; then - echo "== stopping inference (it holds the card) ==" - if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet spear-llm; then - sudo -n systemctl stop spear-llm && STOPPED=unit - else - SERVER_PID=$(pgrep -f "build/bin/llama-server --model" | head -1) - kill "$SERVER_PID" 2>/dev/null && STOPPED=pid - fi - for _ in $(seq 1 60); do - pgrep -f "build/bin/llama-server --model" >/dev/null 2>&1 || break - sleep 2 - done -fi - -restore_inference() { - [ "$STOPPED" = 0 ] && return 0 - echo "== restarting inference ==" - if [ "$STOPPED" = unit ]; then - sudo -n systemd-run --unit=spear-llm --collect "$SERVE_SCRIPT" >/dev/null 2>&1 || \ - setsid "$SERVE_SCRIPT" >>"$HOME/spear/llama-server.log" 2>&1 < /dev/null & - else - setsid "$SERVE_SCRIPT" >>"$HOME/spear/llama-server.log" 2>&1 < /dev/null & - fi -} -# Put the server back whatever happens below -- including the OOM this script -# exists to provoke. A preflight that leaves the machine without its model is -# worse than no preflight. -trap restore_inference EXIT - -nvidia-smi -i "$FT_GPU" --query-gpu=name,memory.total,memory.free \ - --format=csv,noheader | sed 's/^/ GPU /' - -# ── the measurement ────────────────────────────────────────────────────── -PY="${FT_VENV:-$PWD/.venv}/bin/python" -[ -x "$PY" ] || PY=python3 -BASE_MODEL="$BASE_MODEL" MOE_QUANT="$MOE_QUANT" LOAD_DTYPE="$LOAD_DTYPE" \ - "$PY" cloud/load_preflight.py diff --git a/qwen3-finetune/cloud/train_lora_qwen3next.py b/qwen3-finetune/cloud/train_lora_qwen3next.py deleted file mode 100644 index 43d933c..0000000 --- a/qwen3-finetune/cloud/train_lora_qwen3next.py +++ /dev/null @@ -1,268 +0,0 @@ -"""LoRA fine-tune of Qwen3-Coder-Next (80B-A3B, arch qwen3_next) in bf16. - -CLOUD script — a rented multi-GPU pod: this needs ~160 GB of -VRAM for the weights alone, more than a single-card host has, and more free -disk. Bring back only the LoRA adapter (~10-400 MB) and serve it on top of the -Q8_0 GGUF the server already has: `llama-server --lora`. - -Why this loads bf16, and why that is not a recommendation. The argument was -that bitsandbytes quantizes nn.Linear while this model keeps its 512 routed -experts as fused 3-D nn.Parameter tensors, so 4-bit would buy nothing. That is -true of transformers 5.x. It is NOT true of the 4.57.6 this script pins, where -the experts load as an nn.ModuleList of ordinary nn.Linear -- nor of the -published checkpoint, which stores them separately (24 576 per-expert tensors, -no fused one). 4-bit was available and would very likely have halved the card -this needs. Kept as-is because the runs it produced are the ones measured in -cloud/README.md; read that file before choosing hardware. - -What is adapted, and what must never be: - - `self_attn.{q,k,v,o}_proj` — present only in the FULL-attention layers, - one every `full_attention_interval` (4) of the 48, so 12 layers. The other - 36 are Gated-DeltaNet (linear attention) and have no such projections. - - `mlp.shared_expert.{gate,up,down}_proj` — a real nn.Linear that runs on - EVERY token in ALL 48 layers. It is the only always-on MLP path, so it can - carry fact->symbol associations that 12 attention layers alone cannot. - - NEVER `linear_attn.{in_proj_qkvz,in_proj_ba,out_proj}`. On the way to GGUF, - Qwen3NextModel.modify_tensors permutes and splits in_proj_qkvz into - attn_qkv + attn_gate; an adapter on those cannot be mapped back, and the - run would produce weights that nothing can serve. The regex below excludes - them and the guard after get_peft_model refuses to continue if one slipped - through. - - The routed experts are nn.Parameter, not nn.Linear: PEFT never touches - them, which is also why VRAM stays predictable. - -Both adapted families map cleanly to GGUF (`blk.N.attn_{q,k,v,output}`, -`blk.N.ffn_{gate,up,down}_shexp`) and llama.cpp's qwen3next graph runs both -through build_lora_mm / build_ffn — checked in llama.cpp-next before this -script was written, because an adapter that converts but is silently ignored -at inference looks exactly like a fine-tune that did not work. - -Env knobs: - BASE_MODEL HF repo id or local snapshot dir of the BF16 base - FT_DATA_DIR dir holding the jsonl datasets - FT_TRAIN_FILE / FT_VAL_FILE {"messages": [...]} jsonl - FT_OUT_DIR / FT_RUN_NAME adapter output - FT_TARGETS attn | attn+shexp (default attn+shexp) - FT_RANK LoRA rank (default 32) - FT_EPOCHS epochs (default 4) - FT_MAX_LEN max sample tokens (default 2560 — the ib corpus tops at - 2364, so nothing is truncated) - FT_BATCH / FT_ACCUM micro-batch and accumulation - FT_LR learning rate (default 2e-4) - FT_MAX_STEPS >0 = smoke test - FT_GPU_RESERVE_GIB headroom left per card for activations (default 10) -""" -import os -from pathlib import Path - -import torch -from datasets import load_dataset -from peft import LoraConfig, get_peft_model -from transformers import ( - AutoConfig, - AutoModelForCausalLM, - AutoTokenizer, - DataCollatorForLanguageModeling, - Trainer, - TrainingArguments, -) - -BASE_MODEL = os.environ.get("BASE_MODEL", "Qwen/Qwen3-Coder-Next") -HERE = Path(__file__).resolve().parent -DATA = Path(os.environ.get("FT_DATA_DIR", HERE.parent / "data")) -OUT = Path(os.environ.get("FT_OUT_DIR", HERE.parent / "checkpoints")) / \ - os.environ.get("FT_RUN_NAME", "qlora-spear-v1") -MAX_LEN = int(os.environ.get("FT_MAX_LEN", "2560")) -TRAIN_FILE = os.environ.get("FT_TRAIN_FILE", "ib_train.jsonl") -VAL_FILE = os.environ.get("FT_VAL_FILE", "ib_val.jsonl") - -# Regexes, not bare module names: `gate_proj` alone would also be the right -# name in a dense Qwen MLP, and naming the full path is what documents that -# only the SHARED expert is meant here — never a routed one, never the router. -_ATTN = r".*\.self_attn\.(q|k|v|o)_proj" -_SHEXP = r".*\.mlp\.shared_expert\.(gate|up|down)_proj" -_PRESETS = { - "attn": _ATTN, - "attn+shexp": f"({_ATTN}|{_SHEXP})", -} - - -def _placement() -> dict: - """Where the weights go, as kwargs for from_pretrained. - - On the pod: spread over every card, each capped below its real size. - device_map="auto" otherwise fills each one to the brim and the first - optimizer step OOMs on the logits — vocab 151936 x seq x fp32 is several - GB on whichever card ends up holding the LM head. - - With no CUDA device at all it returns nothing and the model loads on the - CPU. That is not a training mode: it is what lets this script be rehearsed - against a miniature qwen3_next before a pod is rented by the hour. - """ - if not torch.cuda.is_available(): - print("no CUDA device: loading on CPU (rehearsal only)") - return {} - reserve = float(os.environ.get("FT_GPU_RESERVE_GIB", "10")) - budget = {} - for i in range(torch.cuda.device_count()): - total = torch.cuda.get_device_properties(i).total_memory / 2**30 - budget[i] = f"{max(total - reserve, 1.0):.0f}GiB" - print(f"loading in bf16 across {len(budget)} card(s): {budget}") - return {"device_map": "auto", "max_memory": budget} - - -def main() -> None: - cfg = AutoConfig.from_pretrained(BASE_MODEL, trust_remote_code=True) - n_layers = getattr(cfg, "num_hidden_layers", 0) - interval = getattr(cfg, "full_attention_interval", 0) - print(f"base : {BASE_MODEL}") - print(f"arch : {cfg.model_type}, {n_layers} layers, " - f"full-attention every {interval}") - - tok = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True) - if tok.pad_token is None: - tok.pad_token = tok.eos_token - - model = AutoModelForCausalLM.from_pretrained( - BASE_MODEL, - dtype=torch.bfloat16, - trust_remote_code=True, - **_placement(), - ) - # Accelerate falls back to CPU (or disk) offload when the weights do not - # fit the budget, and offload does not fail — it just makes a one-hour run - # a one-week run, on a card billed by the hour. Refuse instead. - spilled = {d for d in getattr(model, "hf_device_map", {}).values() - if d in ("cpu", "disk")} - if spilled and torch.cuda.is_available(): - raise SystemExit( - f"the base spilled to {sorted(spilled)}: the cards cannot hold it. " - "Lower FT_GPU_RESERVE_GIB only if you know what is left fits the " - "activations, otherwise take a bigger pod.") - - model.config.use_cache = False - model.gradient_checkpointing_enable( - gradient_checkpointing_kwargs={"use_reentrant": False}) - model.enable_input_require_grads() - - targets = _PRESETS[os.environ.get("FT_TARGETS", "attn+shexp")] - rank = int(os.environ.get("FT_RANK", "32")) - model = get_peft_model(model, LoraConfig( - r=rank, lora_alpha=2 * rank, lora_dropout=0.05, bias="none", - task_type="CAUSAL_LM", target_modules=targets, - )) - model.print_trainable_parameters() - - # What PEFT actually matched, checked rather than assumed. A regex that - # matches nothing trains an adapter full of zeros for two hours and reports - # success; one that matches the linear-attention projections trains - # something that convert_lora_to_gguf cannot map afterwards. - adapted = sorted({n.rsplit(".lora_A", 1)[0] - for n, _ in model.named_modules() if n.endswith("lora_A")}) - forbidden = [n for n in adapted if "linear_attn" in n] - if forbidden: - raise SystemExit( - "LoRA matched linear-attention projections, which cannot be " - f"converted to GGUF: {forbidden[:3]} ... ({len(forbidden)} total)") - n_attn = len([n for n in adapted if ".self_attn." in n]) - n_shexp = len([n for n in adapted if ".shared_expert." in n]) - print(f"adapted: {len(adapted)} modules " - f"({n_attn} attention, {n_shexp} shared-expert)") - if not adapted: - raise SystemExit(f"LoRA matched no module with pattern {targets!r}") - expected_attn = 4 * (n_layers // interval) if interval else 0 - if expected_attn and n_attn != expected_attn: - print(f"WARNING: expected {expected_attn} attention modules for " - f"{n_layers} layers / interval {interval}, matched {n_attn}") - - ds = load_dataset("json", data_files={ - "train": str(DATA / TRAIN_FILE), - "validation": str(DATA / VAL_FILE), - }) - - def tokenize(batch): - texts = [ - tok.apply_chat_template(m, tokenize=False, - add_generation_prompt=False) - for m in batch["messages"] - ] - return tok(texts, truncation=True, max_length=MAX_LEN) - - ds = ds.map(tokenize, batched=True, - remove_columns=ds["train"].column_names) - truncated = sum(1 for r in ds["train"] if len(r["input_ids"]) == MAX_LEN) - if truncated: - print(f"WARNING: {truncated} training samples hit FT_MAX_LEN=" - f"{MAX_LEN} and lost their tail") - - max_steps = int(os.environ.get("FT_MAX_STEPS", "-1")) - smoke = max_steps > 0 - - args = TrainingArguments( - output_dir=str(OUT), - # FT_BATCH defaults to 4, not 1. Measured on a B200: one 350-token - # sample takes ~22 s, of which the arithmetic is ~6 ms — the cost is - # kernel launches, dominated by the sequential Gated-DeltaNet - # recurrence in 36 of the 48 layers (the fla + causal-conv1d fast path - # is rarely installed, and transformers needs both). That recurrence - # is walked once per FORWARD, not once per sample, so the batch rides - # along nearly free. The ceiling is the loss, not the model: logits are - # batch x seq x 151936, upcast to fp32 and backed by a gradient of the - # same size, so 4 x 2560 tokens is what fits the ~30 GiB a B200 has - # left after the weights. - per_device_train_batch_size=int(os.environ.get("FT_BATCH", "4")), - per_device_eval_batch_size=1, - gradient_accumulation_steps=int(os.environ.get("FT_ACCUM", "2")), - num_train_epochs=float(os.environ.get("FT_EPOCHS", "4")), - max_steps=max_steps, - learning_rate=float(os.environ.get("FT_LR", "2e-4")), - lr_scheduler_type="cosine", - warmup_ratio=0.03, - bf16=torch.cuda.is_available(), - gradient_checkpointing=True, - gradient_checkpointing_kwargs={"use_reentrant": False}, - # adamw_torch, not paged_adamw_8bit: without bitsandbytes in the - # picture there is no reason to pull it back in for the few million - # LoRA parameters this trains. - optim="adamw_torch", - # Batches of samples of similar length. The corpus runs from 179 to - # 2364 tokens with a median of 349, so a random batch is padded to its - # longest member and most of what the card computes is padding. This - # only reorders samples; the gradient is the same. - group_by_length=os.environ.get("FT_GROUP_BY_LENGTH", "1") == "1", - logging_steps=1 if smoke else 5, - save_strategy="no" if smoke else "epoch", - eval_strategy="no" if smoke else "epoch", - # Keep every epoch and end on the best one. 311 samples against 20 M - # trainable parameters overfits early, and the epoch that scores best - # on the validation split is not reliably the last: `save_total_limit=2` - # would already have thrown away epoch 1 and 2 by the time that is - # visible. A LoRA checkpoint here is ~80 MB, so keeping all four costs - # nothing worth having. - save_total_limit=None, - load_best_model_at_end=True, - metric_for_best_model="eval_loss", - greater_is_better=False, - report_to="none", - ) - - trainer = Trainer( - model=model, args=args, - train_dataset=ds["train"], eval_dataset=ds["validation"], - data_collator=DataCollatorForLanguageModeling(tok, mlm=False), - ) - from transformers.trainer_utils import get_last_checkpoint - last = get_last_checkpoint(str(OUT)) if OUT.is_dir() else None - if last: - print(f"Resuming from {last}") - trainer.train(resume_from_checkpoint=last) - if smoke: - print("smoke test OK — nothing saved") - return - trainer.save_model(str(OUT)) - tok.save_pretrained(str(OUT)) - print(f"LoRA adapter saved -> {OUT}") - - -if __name__ == "__main__": - main() diff --git a/scripts/bootstrap-runtime.sh b/scripts/bootstrap-runtime.sh index 9860968..bcd53d8 100755 --- a/scripts/bootstrap-runtime.sh +++ b/scripts/bootstrap-runtime.sh @@ -54,7 +54,7 @@ Options: --manifest PATH override the manifest (or SPEAR_RUNTIME_MANIFEST) --verify report state, write nothing --dry-run report intent, write nothing - --checksum with --verify, hash the model shards (reads ~79 GB) + --checksum with --verify, hash the model shards (reads the whole model) --probe with --verify, encode through the worker end to end --skip-model leave /models alone --skip-llama leave /llama.cpp alone @@ -115,6 +115,7 @@ LLAMA_BIN_REL=$(m llama_cpp.binary) CUDA_ARCH="${SPEAR_SERVER_CUDA_ARCH:-$(m llama_cpp.cuda_architecture)}" MODEL_REPO=$(m model.repository) MODEL_DIR=$(m model.directory) +MODEL_REV=$(m model.revision) MODEL_FIRST=$(m model.first_shard) EMBED_PROTOCOL=$(m embedding.protocol_version) EMBED_MODEL=$(m embedding.probe.model) @@ -253,7 +254,8 @@ else # One implementation of "download a sharded GGUF". Naming any member # fetches the set, and -c resumes rather than restarting. SPEAR_SERVER_MODEL_REPO="$MODEL_REPO" \ - SPEAR_SERVER_MODEL_FILE="$MODEL_DIR/$MODEL_FIRST" \ + SPEAR_SERVER_MODEL_REVISION="${MODEL_REV:-main}" \ + SPEAR_SERVER_MODEL_FILE="${MODEL_DIR:+$MODEL_DIR/}$MODEL_FIRST" \ SPEAR_SERVER_MODELS_DIR="$MODELS" \ "$REPO/server/scripts/fetch-model.sh" ok "fetched $missing shard(s)" diff --git a/scripts/spear-client-setup.sh b/scripts/spear-client-setup.sh deleted file mode 100755 index 6047238..0000000 --- a/scripts/spear-client-setup.sh +++ /dev/null @@ -1,93 +0,0 @@ -#!/bin/bash -# Prepares a workstation to run the REDS SPEAR project image: trusts the -# registry, logs in, pulls the image and installs the spear launcher. -# -# Needs docker (your user in the docker group), sudo once for the -# certificate, the HEIG-VD VPN and the registry's pull password. Run it -# again to update the image: spear-client-setup.sh [image] - -set -e - -REG=reds-ml-2.reds-heig-vd.in:5000 -IMAGE=${1:-$REG/spear:0.3.0-project} - -sudo mkdir -p /etc/docker/certs.d/$REG -sudo tee /etc/docker/certs.d/$REG/ca.crt >/dev/null <<'CRT' ------BEGIN CERTIFICATE----- -MIIFYjCCA0qgAwIBAgIUHRcg/cuV348HP8saz7FbXZndy8UwDQYJKoZIhvcNAQEL -BQAwJDEiMCAGA1UEAwwZcmVkcy1tbC0yLnJlZHMtaGVpZy12ZC5pbjAeFw0yNjEx -MjYxNTQyMTdaFw0zNjExMjMxNTQyMTdaMCQxIjAgBgNVBAMMGXJlZHMtbWwtMi5y -ZWRzLWhlaWctdmQuaW4wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDg -VKJiU3/nUxD3WJY2qjP3bD95gIYG0yUkHrg8CjoUQhZOPaSohOgbkCrxLL0Qkjdr -xoll/rodGgv++EgxcKV5blTqM3f6LIQqYWgawTyXUBxelebWQ9X6acChETjIhVQe -2uYEM9fFuyIjo5KhSdYWUlpyTShZL6xgPOCdGJtG6EUmLXww1Sl7rWJec+dzXpz8 -HU9vUEELcDXL7OXogU0xOouiN0tD/ZIMLPaqQSieaBjjjmefc/RNBintTRUBoDI6 -YD0xR3syLnm+8iEnnUc8NP7rT/gUl5DXWht+hTVyntR3uE8dsEr+rAm5KMkhBhhl -bWLsPRBn9ypgRMAwe1AJ+egk9TSsLu1Fw8Gbge6Dx2BTGMGLFeo4s6hQYkuMfu0K -aQgCO56Fff5MkrZdzwvX4D9ZqIc5e9PVbUTeosbJ2p63I0oNZP1k3e0cN1YlhOjc -hZRyDuvfqlHbyM3RNwrx1/vmx33T4SyotiGd0Tql1+DNyElzEIH9amGfKqFTM5pM -G+TaQDsyLBCaqOTHcDQ9wGDD9O6uBhwqRh5brwY+HeGNbmIEhKE69kBX5nhFbhSV -pxDWw8cFwANPM6e5rAOZAKQ9731CVDx3dRP4Vv34m74DMdKDIaQj9u8Ubf5pPqyD -KsX0Ng3nTmJLHvcdrPLJiO+oNv0NEMyKd3eqtYuBHwIDAQABo4GLMIGIMB0GA1Ud -DgQWBBQsWcLBLmsm6dfZzNjcRO8UIv1AazAfBgNVHSMEGDAWgBQsWcLBLmsm6dfZ -zNjcRO8UIv1AazA1BgNVHREELjAsghlyZWRzLW1sLTIucmVkcy1oZWlnLXZkLmlu -gglyZWRzLW1sLTKHBAq+pNowDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsF -AAOCAgEAU6l9Tx45TS1Rt0xxvILvYDtR1fGFMqeTQvTe5G/sxpaHctXPWwwmtlCL -p7f1nr9uB/dm1rfYLm/X32atD0Q0fbCuq36honGLWwVqngUmjaQ2vB15mgVKSjyz -xNjlo+uH2qHBzGajnQM7eB4J9fXNdpXJ2IWn309cBBrajMNPgJ1Wfrsgt0pOiGWY -u1oltWN8yCXD6qeyaz6QBzyhUUh6bMPD5a8YttWImMRa8VtGOcDLDzoqr8GB8W4A -z7xCq1cuevEJL0HZPY5f8X3AdGvUrOSciTythisuQJ8zFhQA4EliNMKVG+pDMuoJ -LLB1HNs7cxLuEqMjxqzB1amGG/r26CsvlgRL4CYCMi1cqm6Lqr6SI1qgvC25sf+p -EmqgRM6wAGcLZbdYCg3lbwdYL6NKOVMBqwVZT67uq5fib0CkLzbHg/VEzqM3/LSF -CdwK5q2ZCmIHjmB7nT7HSkr5/ZSFoXkmBe3yDmB6LbR+FIvrXmAd3qhGm/rrpzD2 -+diZoht+8AFHHLgNZ/bevTeMnOK7Y4EKSEDIzqgIKFBltyBAfHfP3y6M8Nuew0/x -421W3CLHwEGDDyiJJRQphjtcSwrvA19qFN0vxPKLwbszLFWQLzBPT/LDuFvTp3lB -aRNXrE75DvbQ1A8fzkWW5+ckvWso1tvECsRcple7qUWte8dbqsI= ------END CERTIFICATE----- -CRT - -# The registry's pull password is not in this file: ask Daniel for it, then -# give it in SPEAR_REGISTRY_PASSWORD or type it when asked. - -if [ -n "${SPEAR_REGISTRY_PASSWORD:-}" ]; then - printf '%s' "$SPEAR_REGISTRY_PASSWORD" | docker login "$REG" -u spear --password-stdin -else - docker login "$REG" -u spear -fi -docker pull "$IMAGE" - -# The launcher travels in the image; --install copies it to ~/.local/bin and -# writes ~/.config/spear/local.conf naming the image, unless one exists. - -tmp=$(mktemp) -docker run --rm --entrypoint cat "$IMAGE" /opt/spear/spear > "$tmp" -bash "$tmp" --install --image "$IMAGE" -rm -f "$tmp" - -# The configuration of opencn-ng/spear-private/workstation.conf: an existing -# file that says something else is kept as local.conf.bak. - -CONF="${XDG_CONFIG_HOME:-$HOME/.config}/spear/local.conf" -new=$(mktemp) -cat > "$new" <.context_length`, so serve.sh # overrides that key -- and needs its name. -#SPEAR_SERVER_ARCH=qwen3next +#SPEAR_SERVER_ARCH=qwen35 # ---------------------------------------------------------------- optional diff --git a/server/inference/serve.sh b/server/inference/serve.sh index 07542e9..7c19487 100755 --- a/server/inference/serve.sh +++ b/server/inference/serve.sh @@ -198,7 +198,7 @@ if [ "${SPEAR_SERVER_NATIVE_CTX:-0}" -gt 0 ] \ # named after the architecture, which a shell cannot read from the file. [ -n "${SPEAR_SERVER_ARCH:-}" ] || { echo "serve.sh: SPEAR_SERVER_ARCH is required past the trained context" >&2 - echo " (the GGUF general.architecture, e.g. qwen3next)" >&2 + echo " (the GGUF general.architecture, e.g. qwen35)" >&2 exit 78 } ARGS+=(--rope-scaling yarn --rope-scale "$SCALE" diff --git a/server/runtime/manifest.json b/server/runtime/manifest.json index be4dc42..f13e17a 100644 --- a/server/runtime/manifest.json +++ b/server/runtime/manifest.json @@ -1,28 +1,38 @@ { "spear_runtime_manifest": 1, - "profile": { - "name": "qwen3-coder-next-q8-cuda13", - "description": "The deployment this manifest was measured against: one 96 GB Blackwell card, CUDA 13, a Q8_0 Qwen3-Coder-Next served at 524288 tokens (YaRN x2 over its trained 262144), and a bge-m3 embedding worker whose vectors were shown bit-identical to the worker it replaced.", - "validated": "2026-09-14", + "name": "qwen38-27b-q8-cuda13", + "description": "The deployment this manifest was measured against: one 96 GB Blackwell card, CUDA 13, a Q8_0 Qwen3.8-27B served at its native 262144 tokens, and a bge-m3 embedding worker whose vectors were shown bit-identical to the worker it replaced.", + "validated": "2026-11-11", "notes": "A profile, not a requirement. Nothing here names a host, an account, a card or a filesystem path: the machine-specific values (root, GPU UUID, port) are supplied to bootstrap-runtime.sh, never written here." }, - "layout": { - "directories": ["llama.cpp", "models/gguf", "embed", "config", "log"], + "directories": [ + "llama.cpp", + "models/gguf", + "embed", + "config", + "log" + ], "excluded": { "reason": "Reconstructible runtime only. These exist in some deployments as the sediment of past migrations; they are deliberately NOT part of what a bootstrap rebuilds, and not versioned.", - "patterns": ["S1-*", "S3-*", "staging", "log/*", "*.rollback", "config/*.local"] + "patterns": [ + "S1-*", + "S3-*", + "staging", + "log/*", + "*.rollback", + "config/*.local" + ] } }, - "llama_cpp": { "repository": "https://github.com/ggml-org/llama.cpp", - "revision": "dc64a1620e8ae6f01fb33f09470b7160f69fd0f2", - "describe": "b10524-9-gdc64a1620", - "build_number": 10533, - "commit_short": "dc64a1620", - "committed": "2026-08-20", + "revision": "0ec4027a2a0183de87c007069adddc06e665f7de", + "describe": "b12020", + "build_number": 12020, + "commit_short": "0ec4027a2", + "committed": "2026-10-30", "binary": "build/bin/llama-server", "cmake": { "GGML_CUDA": "ON", @@ -33,40 +43,24 @@ "cuda_minimum": "12.8", "revision_policy": "An immutable commit, never a branch. A moving ref is not a reproducibility contract: the binary that serves today would differ from the one measured, with nothing recording that it changed." }, - "model": { - "family": "qwen3-coder-next", + "family": "qwen3.8", "quantisation": "Q8_0", - "architecture": "qwen3next", - "repository": "Qwen/Qwen3-Coder-Next-GGUF", - "directory": "Qwen3-Coder-Next-Q8_0", - "first_shard": "Qwen3-Coder-Next-Q8_0-00001-of-00004.gguf", - "total_bytes": 84812055968, + "architecture": "qwen35", + "repository": "ggml-org/Qwen3.8-27B-GGUF", + "revision": "a316ea527fde32c12487be7574e2db5ac2ad2a7e", + "directory": "", + "first_shard": "Qwen3.8-27B-Q8_0.gguf", + "total_bytes": 28595763648, "shards": [ { - "name": "Qwen3-Coder-Next-Q8_0-00001-of-00004.gguf", - "size": 26190321568, - "sha256": "30b7554fc0c846a5dc3ecf585884c77471f73e3da698a8ba4fabd8e7868c6533" - }, - { - "name": "Qwen3-Coder-Next-Q8_0-00002-of-00004.gguf", - "size": 26212935584, - "sha256": "3f96379de5a5c4655cb378710ea571d5e9cc96f260120a44a6477198efcdc27d" - }, - { - "name": "Qwen3-Coder-Next-Q8_0-00003-of-00004.gguf", - "size": 26047157792, - "sha256": "5dd1ce07eaae95ee430331dc9c6f3120ff88e4211ad3a0cceeaa963f25328504" - }, - { - "name": "Qwen3-Coder-Next-Q8_0-00004-of-00004.gguf", - "size": 6361641024, - "sha256": "76730702c630bf76305139165cb85421858604030851dfd64fe96a5e67cda99d" + "name": "Qwen3.8-27B-Q8_0.gguf", + "size": 28595763648, + "sha256": "aab65c67ef0dad127960efef9247f1832bca105faa1c7a052cc039b223cf86a1" } ], - "integrity_policy": "Size is the cheap check and runs every time; sha256 reads 79 GB and runs only when asked for. The hashes are the publisher's own, recorded so a shard can be proven rather than assumed -- a truncated or half-resumed download has the wrong size, but a corrupted one does not." + "integrity_policy": "Size is the cheap check and runs every time; sha256 reads the whole file and runs only when asked for. The hash is the one recorded when this file was fetched at the pinned revision, so a file can be proven rather than assumed -- a truncated or half-resumed download has the wrong size, but a corrupted one does not." }, - "embedding": { "requirements": "server/embed/requirements.txt", "constraints": "server/embed/constraints-reds-tested.txt", @@ -84,11 +78,10 @@ }, "semantics": "The CLIENT owns model, prefix, cap, normalisation and batching; the server owns device, dtype and loading. The probe values are what this profile's client asks for, recorded so a bootstrap can verify the answer has the right shape." }, - "server_defaults": { - "SPEAR_SERVER_CTX": "524288", + "SPEAR_SERVER_CTX": "262144", "SPEAR_SERVER_NATIVE_CTX": "262144", - "SPEAR_SERVER_ARCH": "qwen3next", + "SPEAR_SERVER_ARCH": "qwen35", "SPEAR_SERVER_PARALLEL": "1", "SPEAR_SERVER_NGL": "99", "SPEAR_SERVER_THREADS": "16", @@ -97,9 +90,13 @@ "SPEAR_SERVER_NCPUMOE": "0", "SPEAR_SERVER_LORA": "none" }, - "server_fixed_flags": { "reason": "Decided by server/inference/serve.sh for every deployment, listed here so verification can prove the launcher still emits them rather than trusting that it does.", - "flags": ["--flash-attn on", "--cache-type-k q8_0", "--cache-type-v q8_0", "--jinja"] + "flags": [ + "--flash-attn on", + "--cache-type-k q8_0", + "--cache-type-v q8_0", + "--jinja" + ] } } diff --git a/server/scripts/fetch-model.sh b/server/scripts/fetch-model.sh index d6302f1..c28a1c7 100755 --- a/server/scripts/fetch-model.sh +++ b/server/scripts/fetch-model.sh @@ -13,7 +13,7 @@ # # wget rather than a hub client, and this is measured rather than assumed: on # the GPU host used here a hub client sustained 1.8 MB/s against 40 MB/s for a -# plain HTTPS pull -- twelve hours against thirty minutes for the same 85 GB. +# plain HTTPS pull. # It is also one fewer Python dependency on a machine that only has to serve. # # -c so an interrupted fetch resumes instead of starting over. @@ -40,7 +40,9 @@ if [ "${#missing[@]}" -gt 0 ]; then exit 78 fi -BASE="${SPEAR_SERVER_HF_ENDPOINT:-https://huggingface.co}/$REPO/resolve/main" +# A pinned revision when the manifest names one: a moving "main" is not the +# file that was measured. +BASE="${SPEAR_SERVER_HF_ENDPOINT:-https://huggingface.co}/$REPO/resolve/${SPEAR_SERVER_MODEL_REVISION:-main}" # -00001-of-000NN.gguf -> every member. Anything else is one file. name="$(basename "$FILE")" diff --git a/server/tests/test_runtime_bootstrap.py b/server/tests/test_runtime_bootstrap.py index e1e1c46..c507ca7 100644 --- a/server/tests/test_runtime_bootstrap.py +++ b/server/tests/test_runtime_bootstrap.py @@ -2,7 +2,7 @@ A deployment that cannot be rebuilt is a deployment nobody may touch. What makes rebuilding possible is not the script -- it is the manifest: an -immutable llama.cpp commit, exact shard sizes with the publisher's hashes, a +immutable llama.cpp commit, exact shard sizes with their recorded hashes, a tested constraints file. The script is only what carries them out. So most of these tests are about the manifest, and the ones about the script @@ -119,9 +119,9 @@ def test_the_server_defaults_reproduce_the_validated_semantics(self): """ defaults = MANIFEST["server_defaults"] - self.assertEqual(defaults["SPEAR_SERVER_CTX"], "524288") + self.assertEqual(defaults["SPEAR_SERVER_CTX"], "262144") self.assertEqual(defaults["SPEAR_SERVER_NATIVE_CTX"], "262144") - self.assertEqual(defaults["SPEAR_SERVER_ARCH"], "qwen3next") + self.assertEqual(defaults["SPEAR_SERVER_ARCH"], "qwen35") self.assertEqual(defaults["SPEAR_SERVER_PARALLEL"], "1") self.assertEqual(defaults["SPEAR_SERVER_NGL"], "99") self.assertEqual(defaults["SPEAR_SERVER_THREADS"], "16") @@ -371,7 +371,7 @@ def test_a_shard_of_the_wrong_size_is_the_only_one_refetched(self): for shard in MANIFEST["model"]["shards"]: with open(models / shard["name"], "wb") as handle: handle.truncate(shard["size"]) - bad = MANIFEST["model"]["shards"][2] + bad = MANIFEST["model"]["shards"][-1] with open(models / bad["name"], "wb") as handle: handle.truncate(12345) diff --git a/server/tests/test_server_config.py b/server/tests/test_server_config.py index 1517d4a..1f88e3b 100644 --- a/server/tests/test_server_config.py +++ b/server/tests/test_server_config.py @@ -140,7 +140,7 @@ def test_the_environment_beats_the_file(self): def test_a_window_past_the_trained_one_turns_yarn_on(self): self.serve(env=self.complete(SPEAR_SERVER_CTX="524288", SPEAR_SERVER_NATIVE_CTX="262144", - SPEAR_SERVER_ARCH="qwen3next")) + SPEAR_SERVER_ARCH="qwen35")) served = self.served() self.assertEqual(served["--rope-scaling"], "yarn") self.assertEqual(served["--rope-scale"], "2") @@ -150,8 +150,8 @@ def test_the_trained_length_is_raised_so_the_slot_is_not_capped(self): """Without it llama-server served 262144 of the 524288 asked for.""" self.serve(env=self.complete(SPEAR_SERVER_CTX="524288", SPEAR_SERVER_NATIVE_CTX="262144", - SPEAR_SERVER_ARCH="qwen3next")) - self.assertIn("qwen3next.context_length=int:524288", + SPEAR_SERVER_ARCH="qwen35")) + self.assertIn("qwen35.context_length=int:524288", self.argv.read_text()) def test_yarn_without_the_architecture_is_refused(self):