Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(long-context): compose llama3 RoPE on a native llama3 block, refuse other re-scaling (#1239) (#1311)
Alpamys Makazhan7020716bfdff
diff --git a/changelog.d/0.75.1/1311.fixed.md b/changelog.d/0.75.1/1311.fixed.mdnew file mode 100644index 00000000..07636e27--- /dev/null+++ b/changelog.d/0.75.1/1311.fixed.md@@ -0,0 +1 @@+- **`rope_scaling_type: llama3` on a checkpoint that already ships Llama 3.1 RoPE scaling now composes with that scaling instead of replacing it (#1239 in #1311).** Llama-3.1 checkpoints ship `max_position_embeddings: 131072` with a native `llama3` block (factor 8 over an original 8192 tokens). Extending one to 262144 tokens rebuilt the block as factor 2 over 131072, so 35 of the 64 frequency pairs of an 8B head rotated up to 8x faster than in pretraining, and the run printed only "Long-context enabled". `llama3` on a native `llama3` block now keeps the checkpoint's `original_max_position_embeddings`, `low_freq_factor` and `high_freq_factor`, and multiplies its `factor` by `data.max_length / max_position_embeddings` (factor 16 over 8192 in that example), so no pair rotates faster than in the checkpoint. **New refusals:** extending a checkpoint whose RoPE block is already scaled in any other way is refused before the model is built, with an error that names the checkpoint's `rope_type` and `factor`. That covers `linear`, `dynamic` or `yarn` on a native `llama3` block, and any `rope_scaling_type` on a native `yarn`, `longrope`, `linear` or `dynamic` block. `rope_scaling_type: longrope` is now refused at config load, in any spelling. Its per-dimension factors exist only on checkpoints already scaled with LongRoPE, and extending those is refused, so it cannot extend any checkpoint; the error names the types that extend a checkpoint without RoPE scaling (`linear`, `dynamic`, `yarn` or `llama3`). Fine-tuning a LongRoPE checkpoint such as Phi-3-mini-128k at its native length, with `rope_scaling_type` unset, is unchanged. A `data.max_length` at or below the checkpoint's `max_position_embeddings` still changes nothing, and checkpoints without RoPE scaling (Llama 2, Mistral, the 8k Llama 3) extend exactly as before. `task: sft` and `task: pretrain`, the two tasks that apply RoPE scaling, both get the new behaviour.diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex ba43ac1e..41c1515b 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -127,17 +127,17 @@ The `JinjaTemplateAnalyzer` (also v0.37.0) walks chat-template ASTs to discover## Long Context — YaRN, Llama 3.1 NTK, LongLoRA-Soup ships five RoPE-scaling strategies (LongLoRA is refused, see below):+Soup ships four RoPE-scaling strategies (`linear`, `dynamic`, `yarn`, `llama3`); LongLoRA is refused, see below:```yaml# soup.yaml-base: meta-llama/Llama-3.1-8B+base: meta-llama/Meta-Llama-3-8B # 8k, no native RoPE scalingtask: sftdata:train: ./data.jsonlmax_length: 32768 # extend from 8k → 32ktraining:- rope_scaling_type: yarn # linear | dynamic | yarn | longrope | llama3+ rope_scaling_type: yarn # linear | dynamic | yarn | llama3yarn_factor: 4.0 # 4x extensionyarn_beta_fast: 32yarn_beta_slow: 1@@ -147,20 +147,20 @@ training:**YaRN.** Best quality for 4-8x extension. Tunables (`yarn_factor`, `yarn_attn_factor`, `yarn_beta_fast`, `yarn_beta_slow`) only apply when `rope_scaling_type=yarn`; the schema rejects them otherwise. Pure-Python math kernels are exposed at `soup_cli.utils.long_context.yarn_*` for reference / config-emit. The actual RoPE rotation runs inside HF Transformers.-**Llama 3.1 NTK-aware.** Use `rope_scaling_type: llama3` for the canonical Llama 3.1 frequency-band scaling (`scale_factor=8`, `low_freq_factor=1`, `high_freq_factor=4`, `old_context_len=8192`). `detect_llama3_rope_in_config` can identify the block in an HF model config dict, but `soup train` changes RoPE only when `rope_scaling_type` is explicit; omitting it preserves the checkpoint's native RoPE configuration.+**Llama 3.1 NTK-aware.** Use `rope_scaling_type: llama3` for Llama 3.1-style frequency-band scaling. On a checkpoint without RoPE scaling it emits `factor = data.max_length / max_position_embeddings` over `original_max_position_embeddings = max_position_embeddings`, with `low_freq_factor` 1 and `high_freq_factor` 4, so an 8k checkpoint extended to 64k gets Llama 3.1's own factor 8 over 8192. `detect_llama3_rope_in_config` can identify the block in an HF model config dict, but `soup train` changes RoPE only when `rope_scaling_type` is explicit; omitting it preserves the checkpoint's native RoPE configuration. On a checkpoint that already ships a `llama3` block (Llama 3.1, 3.2 and 3.3 do), `rope_scaling_type: llama3` composes with it instead of replacing it: the checkpoint's `original_max_position_embeddings`, `low_freq_factor` and `high_freq_factor` are kept, and its `factor` is multiplied by `data.max_length / max_position_embeddings`. Llama-3.1-8B extended from 131072 to 262144 tokens trains with factor 16 over 8192, so no frequency pair rotates faster than it did in pretraining.-RoPE scaling is applied before model construction for the Transformers text paths of `task: sft` and `task: pretrain`. Vision, audio, layer-streaming and Unsloth setup paths do not consume these fields, nor do other training tasks. Existing type-independent model parameters such as `rope_theta` are preserved; tunables belonging to a previous RoPE algorithm are removed when the type changes. Models such as Gemma 3 that use nested per-layer RoPE sections are refused rather than partially modified. `longrope` additionally requires a checkpoint that already ships its learned `short_factor` and `long_factor` vectors; Soup refuses to invent those model-specific values.+RoPE scaling is applied before model construction for the Transformers text paths of `task: sft` and `task: pretrain`. Vision, audio, layer-streaming and Unsloth setup paths do not consume these fields, nor do other training tasks. Existing type-independent model parameters such as `rope_theta` are preserved; tunables belonging to a previous RoPE algorithm are removed when the type changes. A checkpoint whose RoPE block is already scaled (any `rope_type` other than `default`, for example `yarn`, `longrope` or `llama3`) is never replaced: apart from `llama3` on a `llama3` block, extending it is refused before the model is built, and the error names the checkpoint's `rope_type` and `factor`. A `data.max_length` at or below the checkpoint's `max_position_embeddings` extends nothing, so none of these refusals applies to it. Models such as Gemma 3 that use nested per-layer RoPE sections are refused rather than partially modified. `rope_scaling_type: longrope` is refused at config load, whatever `data.max_length` is. Its per-dimension `short_factor` and `long_factor` vectors exist only on checkpoints already scaled with LongRoPE, and extending those is refused, so it cannot extend any checkpoint. To extend a checkpoint without RoPE scaling, use `linear`, `dynamic`, `yarn` or `llama3`. To fine-tune a LongRoPE checkpoint such as Phi-3-mini-128k at its native length, leave `rope_scaling_type` unset: the checkpoint's own RoPE block is used as shipped.**LongLoRA S².** `training.use_longlora: true` is refused at config load ([#1240](https://github.com/MakazhanAlpamys/Soup/issues/1240)): the override it installed leaked future tokens into earlier positions and applied no S² grouping (see [LongLoRA Forward Override](#longlora-forward-override)). Use one of the RoPE-scaling strategies above with plain LoRA instead.```yaml-# Llama 3.1 with NTK-aware scaling out to 128k+# Llama 3.1 ships llama3 scaling to 128k; this composes with it out to 256kbase: meta-llama/Llama-3.1-8Btraining:rope_scaling_type: llama3gradient_checkpointing: fulldata:- max_length: 131072+ max_length: 262144```diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 3f1ff0fe..01ab4f4b 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -1018,7 +1018,7 @@ training:gradient_checkpointing: true # Required for long sequences# Long-context (128k+ tokens)- rope_scaling_type: dynamic # RoPE scaling: linear, dynamic, yarn, longrope+ rope_scaling_type: dynamic # RoPE scaling: linear, dynamic, yarn, llama3# use_ring_attention: true # Sequence parallelism across GPUsdata:diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex af201f27..39eed82f 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -22,6 +22,10 @@ from soup_cli.utils.layer_stream import (SUPPORTED_STREAM_TASKS as _STREAM_SUPPORTED_TASKS,)+# The longrope refusal (#1239) lives with the runtime so config load and+# apply_long_context_config say the same thing (long_context has no torch).+from soup_cli.utils.long_context import LONGROPE_REFUSAL+# Stdlib-only structural check shared by every regex a config can carry.from soup_cli.utils.safe_regex import check_config_regex@@ -2938,12 +2942,12 @@ class TrainingConfig(BaseModel):)# Long-context — RoPE scalingrope_scaling_type: Optional[- Literal["linear", "dynamic", "yarn", "longrope", "llama3"]+ Literal["linear", "dynamic", "yarn", "llama3"]] = Field(default=None,description=(- "RoPE scaling method for long-context: linear, dynamic, yarn, longrope, "- "llama3 (v0.49.0)."+ "RoPE scaling method for long-context: linear, dynamic, yarn or llama3 "+ "(v0.49.0). 'longrope' is refused at config load (#1239)."),)# v0.49.0 Part A — YaRN-specific tunables (only meaningful when@@ -3842,6 +3846,18 @@ class TrainingConfig(BaseModel):)return value+ @field_validator("rope_scaling_type", mode="before")+ @classmethod+ def _refuse_longrope(cls, value: Any) -> Any:+ """#1239 — ``longrope`` can extend no checkpoint, so it is refused in any+ spelling ahead of the Literal check, with the reason instead of a list of+ the other types."""+ if isinstance(value, str):+ squashed = "".join(value.split()).lower().replace("_", "").replace("-", "")+ if squashed == "longrope":+ raise ValueError(LONGROPE_REFUSAL)+ return value+@model_validator(mode="after")def _validate_yarn_fields_require_yarn_type(self) -> "TrainingConfig":"""v0.49.0 Part A — yarn_* fields are no-ops unlessdiff --git a/src/soup_cli/utils/long_context.py b/src/soup_cli/utils/long_context.pyindex e09b6b7c..4032a2cc 100644--- a/src/soup_cli/utils/long_context.py+++ b/src/soup_cli/utils/long_context.py@@ -8,7 +8,8 @@ windows beyond their pre-training length. Supports multiple scaling strategies:- yarn: YaRN (Yet another RoPE extensioN) — best quality for 4-8x extension(v0.49.0 Part A — math kernel + config-emit; HF Transformers owns theactual rotation under the hood)-- longrope: LongRoPE — progressive extension with search-based factors+- longrope: LongRoPE — progressive extension with search-based factors.+ Refused since #1239: its factors exist only on already-scaled checkpoints.- llama3: Llama 3.1 frequency-band NTK-aware scaling (v0.49.0 Part D)Also handles gradient checkpointing configuration for memory efficiency@@ -21,7 +22,8 @@ import mathfrom collections.abc import Mappingfrom typing import Any-# Supported RoPE scaling methods (v0.49.0 adds "llama3").+# Supported RoPE scaling methods (v0.49.0 adds "llama3"). get_rope_scaling_config+# can still emit "longrope"; soup.yaml and apply_long_context_config refuse it (#1239).ROPE_SCALING_TYPES = ("linear", "dynamic", "yarn", "longrope", "llama3")# Values that remain meaningful when switching from one RoPE algorithm to@@ -29,6 +31,25 @@ ROPE_SCALING_TYPES = ("linear", "dynamic", "yarn", "longrope", "llama3")# not leak into the replacement block._ROPE_TYPE_AGNOSTIC_KEYS = ("rope_theta", "partial_rotary_factor")+# The RoPE type transformers assumes when a checkpoint ships no scaling block.+# Any other native type is a block Soup must not silently replace (#1239).+_UNSCALED_ROPE_TYPE = "default"++# #1239: LongRoPE's per-dimension factors were searched for one extension and+# ship only with checkpoints already scaled by it, which may not be extended+# again, so the type can extend nothing. Config load (schema.py) and+# apply_long_context_config both refuse it with this text.+LONGROPE_REFUSAL = (+ "training.rope_scaling_type='longrope' is refused (#1239): it cannot extend any "+ "checkpoint. Its per-dimension short_factor and long_factor vectors exist only on "+ "checkpoints already scaled with LongRoPE, and extending an already-scaled "+ "checkpoint is refused, because replacing its RoPE block would discard the scaling "+ "it was trained with. To extend a checkpoint without RoPE scaling, use linear, "+ "dynamic, yarn or llama3; on a Llama 3.1-style checkpoint, llama3 composes with its "+ "own block. To fine-tune a LongRoPE checkpoint (Phi-3-mini-128k, for example) at "+ "its native length, leave rope_scaling_type unset."+)+# Default context lengths for known model families.MODEL_DEFAULT_CONTEXT: dict[str, int] = {"llama-3": 8192,@@ -278,6 +299,112 @@ def detect_llama3_rope_in_config(config: Mapping[str, Any]) -> bool:return isinstance(type_value, str) and type_value.lower() == "llama3"+def _native_rope_type(rope: Mapping[str, Any]) -> str:+ """Return a checkpoint's RoPE type, read the way transformers reads it."""+ for key in ("rope_type", "type"):+ value = rope.get(key)+ if value is not None:+ return str(value)+ return _UNSCALED_ROPE_TYPE+++def compose_llama3_rope_parameters(+ native: Mapping[str, Any],+ *,+ max_position_embeddings: int,+ target_length: float,+) -> dict[str, Any]:+ """Extend a checkpoint's own Llama 3.1 RoPE block instead of replacing it (#1239).++ Keeps the checkpoint's ``original_max_position_embeddings``,+ ``low_freq_factor`` and ``high_freq_factor`` and multiplies its ``factor``+ by ``target_length / max_position_embeddings``. The frequency bands depend+ only on the kept values, so high-frequency pairs are untouched and every+ other pair only slows down. At ``target_length == max_position_embeddings``+ the block is the checkpoint's own. A missing+ ``original_max_position_embeddings`` means ``max_position_embeddings``, as+ in transformers.+ """+ native_type = _native_rope_type(native)+ if native_type.lower() != "llama3":+ raise ValueError(+ "compose_llama3_rope_parameters needs a llama3 RoPE block "+ f"(got rope_type={native_type!r})"+ )+ if (+ isinstance(max_position_embeddings, bool)+ or not isinstance(max_position_embeddings, int)+ or max_position_embeddings <= 0+ ):+ raise ValueError(+ f"max_position_embeddings must be a positive int (got {max_position_embeddings!r})"+ )+ target = _finite_positive(target_length, "target_length")+ if target < max_position_embeddings:+ raise ValueError(+ f"target_length ({target_length}) is below max_position_embeddings "+ f"({max_position_embeddings}): a smaller llama3 factor would make the "+ "checkpoint's low-frequency pairs rotate faster than it was trained with (#1239)"+ )+ factor = _finite_positive(native.get("factor"), "the checkpoint's llama3 factor")+ low = _finite_positive(native.get("low_freq_factor"), "the checkpoint's llama3 low_freq_factor")+ # No high > low check: the bands are the checkpoint's own, and some ship+ # high == low (Llama 4 Scout), which transformers only warns about.+ high = _finite_positive(+ native.get("high_freq_factor"), "the checkpoint's llama3 high_freq_factor"+ )+ original = native.get("original_max_position_embeddings", max_position_embeddings)+ if isinstance(original, float) and original.is_integer():+ original = int(original) # transformers accepts 8192.0 there, with a warning+ if isinstance(original, bool) or not isinstance(original, int) or original <= 0:+ raise ValueError(+ "the checkpoint's llama3 original_max_position_embeddings must be a positive "+ f"int (got {original!r})"+ )+ return {+ "rope_type": "llama3",+ "factor": factor * (target / max_position_embeddings),+ "original_max_position_embeddings": original,+ "low_freq_factor": low,+ "high_freq_factor": high,+ }+++def _requested_label(requested: str | None, resolved: str) -> str:+ """How a refusal names the requested type, auto-detection included."""+ return repr(resolved) if requested is not None else f"None (auto-detected {resolved!r})"+++def _already_scaled_error(+ native: Mapping[str, Any],+ *,+ native_type: str,+ requested: str | None,+ resolved: str,+ original_length: int,+ target_length: Any,+) -> ValueError:+ """Refusal for extending a checkpoint whose RoPE block is already scaled (#1239)."""+ shown = _requested_label(requested, resolved)+ if native_type.lower() == "llama3":+ way_out = (+ "Use rope_scaling_type='llama3', which composes with the checkpoint's own "+ f"llama3 block, or keep data.max_length at or below {original_length}."+ )+ else:+ way_out = (+ f"Keep data.max_length at or below {original_length}, or start from a "+ "checkpoint without RoPE scaling."+ )+ return ValueError(+ f"training.rope_scaling_type={shown} cannot extend this checkpoint from "+ f"{original_length} to {target_length} tokens: its RoPE block is already scaled "+ f"(rope_type={native_type!r}, factor={native.get('factor')!r}) and {resolved!r} "+ "has no defined composition with it, so replacing the block would discard the "+ f"scaling the checkpoint was trained with (#1239). {way_out}"+ )++# ---------------------------------------------------------------------------# Public config emission# ---------------------------------------------------------------------------@@ -396,6 +523,15 @@ def apply_long_context_config(constructed. Transformers 5 derives ``inv_freq`` in the rotary embeddingconstructor, so mutating the config after ``from_pretrained`` is a no-op.Existing model-native values such as ``rope_theta`` are retained.++ A checkpoint whose RoPE block is already scaled (any ``rope_type`` other+ than ``default``) is never replaced (#1239). ``llama3`` on a native+ ``llama3`` block composes through :func:`compose_llama3_rope_parameters`;+ every other combination raises ``ValueError`` before ``model_config`` is+ touched, naming the checkpoint's ``rope_type`` and ``factor``. ``longrope``+ is refused on a checkpoint without scaling too (:data:`LONGROPE_REFUSAL`),+ so it extends nothing. A ``target_length`` at or below+ ``max_position_embeddings`` stays a no-op."""original_length = getattr(model_config,@@ -417,34 +553,50 @@ def apply_long_context_config(f"sections found: {', '.join(nested_sections)}. Soup refuses to ""change max_position_embeddings without scaling every RoPE section")+ # #1239: a scaled native block was already extended to max_position_embeddings,+ # so rebuilding a block over that length discards the scaling it was trained with.+ # One reader, transformers' key order, serves both the auto-detect and the check.+ native_type = _native_rope_type(existing)+ requested_type = rope_scaling_typeif rope_scaling_type is None:- if isinstance(existing, Mapping) and detect_llama3_rope_in_config(- {"rope_scaling": existing}- ):- rope_scaling_type = "llama3"- else:- rope_scaling_type = "dynamic"- rope_config = get_rope_scaling_config(- scaling_type=rope_scaling_type,- target_length=target_length,- original_length=original_length,- yarn_factor=yarn_factor,- yarn_attn_factor=yarn_attn_factor,- yarn_beta_fast=yarn_beta_fast,- yarn_beta_slow=yarn_beta_slow,- )+ rope_scaling_type = "llama3" if native_type.lower() == "llama3" else "dynamic"+ if native_type.lower() == _UNSCALED_ROPE_TYPE:+ if rope_scaling_type == "longrope":+ raise ValueError(LONGROPE_REFUSAL)+ rope_config = get_rope_scaling_config(+ scaling_type=rope_scaling_type,+ target_length=target_length,+ original_length=original_length,+ yarn_factor=yarn_factor,+ yarn_attn_factor=yarn_attn_factor,+ yarn_beta_fast=yarn_beta_fast,+ yarn_beta_slow=yarn_beta_slow,+ )+ elif native_type.lower() == "llama3" and rope_scaling_type == "llama3":+ try:+ rope_config = compose_llama3_rope_parameters(+ existing,+ max_position_embeddings=original_length,+ target_length=target_length,+ )+ except ValueError as exc:+ raise ValueError(+ f"training.rope_scaling_type={_requested_label(requested_type, 'llama3')} "+ f"cannot compose with this checkpoint's llama3 RoPE block (#1239): {exc}. "+ "Fix the checkpoint's rope_parameters, or keep data.max_length at or below "+ f"{original_length}."+ ) from exc+ else:+ raise _already_scaled_error(+ existing,+ native_type=native_type,+ requested=requested_type,+ resolved=rope_scaling_type,+ original_length=original_length,+ target_length=target_length,+ )if not rope_config:return None- if rope_scaling_type == "longrope":- missing = [name for name in ("short_factor", "long_factor") if name not in existing]- if missing:- raise ValueError(- "rope_scaling_type='longrope' requires model-native "- f"{', '.join(missing)} vectors; choose a checkpoint that ships "- "LongRoPE factors or use linear, dynamic, yarn, or llama3"- )- rope_config["short_factor"] = existing["short_factor"]- rope_config["long_factor"] = existing["long_factor"]merged = {name: existing[name]for name in _ROPE_TYPE_AGNOSTIC_KEYSdiff --git a/tests/test_issue1239_llama3_rope_compose.py b/tests/test_issue1239_llama3_rope_compose.pynew file mode 100644index 00000000..686926d0--- /dev/null+++ b/tests/test_issue1239_llama3_rope_compose.py@@ -0,0 +1,1060 @@+"""#1239 — extending a checkpoint whose RoPE block is already scaled.++Llama-3.1 checkpoints ship ``max_position_embeddings: 131072`` with a native+``llama3`` block: factor 8 over ``original_max_position_embeddings`` 8192,+``low_freq_factor`` 1, ``high_freq_factor`` 4. ``rope_scaling_type: llama3``+used to REPLACE that block with factor 2 over 131072, so 35 of the 64 frequency+pairs of an 8B-shaped head rotated up to 8x faster than in pretraining.++It now COMPOSES: the checkpoint's original length and band factors are kept+and its factor is multiplied by ``target / max_position_embeddings``. Every+other extension of a checkpoint whose RoPE block is not ``default`` is refused+before the model is built, and the message names the checkpoint's+``rope_type`` and ``factor``. Checkpoints without RoPE scaling extend exactly as+before.++``rope_scaling_type: longrope`` is refused at config load, in every spelling:+its per-dimension ``short_factor`` / ``long_factor`` vectors exist only on+checkpoints already scaled with LongRoPE, and extending those is refused, so it+cannot extend anything; the refusal points at the types that can. Fine-tuning a+LongRoPE checkpoint at its native length with ``rope_scaling_type`` unset keeps+working, and a control trains one for real.++Reference inverse frequencies come from transformers' own llama3 init+(``ROPE_INIT_FUNCTIONS["llama3"]``, i.e. ``_compute_llama3_parameters``), never+from a re-implementation. The tiny models are config-built (hidden 64, one+layer) with ``head_dim`` 128, so they have the 64 frequency pairs of the 8B.+"""++import json+import math+import re+from copy import deepcopy+from types import SimpleNamespace++import pytest+import yaml++from soup_cli.config.loader import load_config_from_string++# Llama-3.1-8B model-card values.+NATIVE_MAX = 131072+NATIVE_LLAMA31 = {+ "rope_type": "llama3",+ "factor": 8.0,+ "low_freq_factor": 1.0,+ "high_freq_factor": 4.0,+ "original_max_position_embeddings": 8192,+ "rope_theta": 500000.0,+}+TARGET = 262144+# The composition #1239 asks for: same original length and bands, factor x2.+COMPOSED_LLAMA31 = {+ "rope_theta": 500000.0,+ "rope_type": "llama3",+ "factor": 16.0,+ "original_max_position_embeddings": 8192,+ "low_freq_factor": 1.0,+ "high_freq_factor": 4.0,+}++# Native blocks that are already scaled and have no defined composition.+NATIVE_YARN = {+ "rope_type": "yarn",+ "factor": 4.0,+ "original_max_position_embeddings": 32768,+ "rope_theta": 1000000.0,+}+NATIVE_LONGROPE = { # Phi-3-mini-128k style: learned vectors, no ``factor`` key+ "rope_type": "longrope",+ "short_factor": [1.0] * 4,+ "long_factor": [2.0] * 4,+ "original_max_position_embeddings": 4096,+ "rope_theta": 10000.0,+}+NATIVE_LINEAR = {"rope_type": "linear", "factor": 4.0, "rope_theta": 10000.0}+NATIVE_DYNAMIC = {"rope_type": "dynamic", "factor": 2.0, "rope_theta": 10000.0}++REQUESTED_TYPES = ("llama3", None, "linear", "dynamic", "yarn", "longrope")++# The refusal on a native llama3 block points at the one composition that exists.+_COMPOSE_HINT = "rope_scaling_type='llama3', which composes with the checkpoint's own llama3 block"+++def _requires_train_extra() -> None:+ for module in ("torch", "transformers", "peft"):+ pytest.importorskip(module, reason=f"{module} is only in the [train] extra")+++def _tiny_llama_config(*, max_position_embeddings: int, rope_parameters: dict):+ from transformers import LlamaConfig++ return LlamaConfig(+ vocab_size=64,+ hidden_size=64,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=1,+ num_key_value_heads=1,+ head_dim=128,+ max_position_embeddings=max_position_embeddings,+ rope_parameters=deepcopy(rope_parameters),+ )+++def _transformers_llama3_inv_freq(*, max_position_embeddings: int, rope_parameters: dict):+ """The inverse frequencies transformers' own llama3 init computes."""+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS++ config = _tiny_llama_config(+ max_position_embeddings=max_position_embeddings,+ rope_parameters=rope_parameters,+ )+ inv_freq, _attention_factor = ROPE_INIT_FUNCTIONS["llama3"](config, None)+ return inv_freq+++def _native_inv_freq():+ return _transformers_llama3_inv_freq(+ max_position_embeddings=NATIVE_MAX, rope_parameters=NATIVE_LLAMA31+ )+++def _bands():+ """Masks of the high / low frequency bands for Llama-3.1's native block."""+ import torch++ base = 1.0 / (+ NATIVE_LLAMA31["rope_theta"] ** (torch.arange(0, 128, 2, dtype=torch.int64).float() / 128)+ )+ wavelen = 2 * math.pi / base+ high = wavelen < 8192 / NATIVE_LLAMA31["high_freq_factor"]+ low = wavelen > 8192 / NATIVE_LLAMA31["low_freq_factor"]+ return high, low+++def _snapshot(config) -> dict:+ return deepcopy(vars(config))+++def _message_names(exc_info, *parts: str) -> None:+ message = str(exc_info.value)+ for part in parts:+ assert part in message, (part, message)+++# ---------------------------------------------------------------------------+# The composition itself+# ---------------------------------------------------------------------------+++class TestComposeLlama3RopeParameters:+ def test_keeps_the_native_bands_and_multiplies_the_factor(self) -> None:+ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ block = compose_llama3_rope_parameters(+ NATIVE_LLAMA31, max_position_embeddings=NATIVE_MAX, target_length=TARGET+ )++ assert block == {+ "rope_type": "llama3",+ "factor": 16.0,+ "original_max_position_embeddings": 8192,+ "low_freq_factor": 1.0,+ "high_freq_factor": 4.0,+ }++ def test_reduces_to_the_native_inv_freq_when_target_equals_max(self) -> None:+ _requires_train_extra()+ import torch++ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ block = compose_llama3_rope_parameters(+ NATIVE_LLAMA31, max_position_embeddings=NATIVE_MAX, target_length=NATIVE_MAX+ )+ composed = _transformers_llama3_inv_freq(+ max_position_embeddings=NATIVE_MAX,+ rope_parameters={**block, "rope_theta": NATIVE_LLAMA31["rope_theta"]},+ )++ assert block["factor"] == NATIVE_LLAMA31["factor"]+ assert torch.equal(composed, _native_inv_freq())++ @pytest.mark.parametrize("target", [131073, 200000, TARGET, 1048576])+ def test_no_pair_rotates_faster_than_the_checkpoint(self, target: int) -> None:+ _requires_train_extra()+ import torch++ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ block = compose_llama3_rope_parameters(+ NATIVE_LLAMA31, max_position_embeddings=NATIVE_MAX, target_length=target+ )+ composed = _transformers_llama3_inv_freq(+ max_position_embeddings=target,+ rope_parameters={**block, "rope_theta": NATIVE_LLAMA31["rope_theta"]},+ )+ native = _native_inv_freq()+ high, low = _bands()++ assert composed.shape == native.shape == (64,)+ faster = [int(k) for k in torch.nonzero(composed > native).flatten()]+ assert faster == [], f"pairs rotating faster than pretrained: {faster}"+ assert torch.equal(composed[high], native[high])+ assert bool((composed[low] < native[low]).all())++ def test_the_issue_target_slows_the_same_35_pairs_the_bug_sped_up(self) -> None:+ _requires_train_extra()+ import torch++ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ block = compose_llama3_rope_parameters(+ NATIVE_LLAMA31, max_position_embeddings=NATIVE_MAX, target_length=TARGET+ )+ composed = _transformers_llama3_inv_freq(+ max_position_embeddings=TARGET,+ rope_parameters={**block, "rope_theta": NATIVE_LLAMA31["rope_theta"]},+ )+ native = _native_inv_freq()+ high, low = _bands()+ medium = ~high & ~low++ assert (int(high.sum()), int(low.sum()), int(medium.sum())) == (29, 29, 6)+ assert int((composed != native).sum()) == 35+ # Factor 8 -> 16: the low band rotates exactly half as fast as pretrained.+ assert torch.equal(composed[low], native[low] / 2)+ assert bool((composed[medium] < native[medium]).all())+ assert bool((composed[medium] > native[medium] / 2).all())++ def test_a_missing_original_length_falls_back_like_transformers(self) -> None:+ """transformers reads a llama3 block without ``original_max_position_embeddings``+ as if it were ``max_position_embeddings``; the composition keeps that value."""+ _requires_train_extra()+ import torch++ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ native = {+ key: value+ for key, value in NATIVE_LLAMA31.items()+ if key != "original_max_position_embeddings"+ }+ block = compose_llama3_rope_parameters(+ native, max_position_embeddings=8192, target_length=8192+ )+ assert block["original_max_position_embeddings"] == 8192+ assert torch.equal(+ _transformers_llama3_inv_freq(+ max_position_embeddings=8192,+ rope_parameters={**block, "rope_theta": native["rope_theta"]},+ ),+ _transformers_llama3_inv_freq(max_position_embeddings=8192, rope_parameters=native),+ )++ extended = compose_llama3_rope_parameters(+ native, max_position_embeddings=8192, target_length=32768+ )+ assert extended["original_max_position_embeddings"] == 8192+ assert extended["factor"] == 32.0++ def test_refuses_to_shrink_the_factor(self) -> None:+ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ with pytest.raises(ValueError, match=r"#1239") as exc_info:+ compose_llama3_rope_parameters(+ NATIVE_LLAMA31, max_position_embeddings=NATIVE_MAX, target_length=65536+ )+ _message_names(exc_info, "65536", "131072")++ def test_refuses_a_block_that_is_not_llama3(self) -> None:+ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ with pytest.raises(ValueError, match=r"rope_type='yarn'"):+ compose_llama3_rope_parameters(+ NATIVE_YARN, max_position_embeddings=NATIVE_MAX, target_length=TARGET+ )++ def test_equal_band_factors_compose_too(self) -> None:+ """Llama 4 Scout's text block ships ``low == high == 1``; transformers only+ warns about that, and the composition must keep it rather than refuse it."""+ _requires_train_extra()+ import torch++ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ scout = {+ "rope_type": "llama3",+ "factor": 16.0,+ "low_freq_factor": 1.0,+ "high_freq_factor": 1.0,+ "original_max_position_embeddings": 8192,+ "rope_theta": 500000.0,+ }+ scout_max = 10485760+ block = compose_llama3_rope_parameters(+ scout, max_position_embeddings=scout_max, target_length=2 * scout_max+ )+ composed = _transformers_llama3_inv_freq(+ max_position_embeddings=2 * scout_max,+ rope_parameters={**block, "rope_theta": scout["rope_theta"]},+ )+ native = _transformers_llama3_inv_freq(+ max_position_embeddings=scout_max, rope_parameters=scout+ )++ assert block["factor"] == 32.0+ assert (block["low_freq_factor"], block["high_freq_factor"]) == (1.0, 1.0)+ assert bool(torch.isfinite(composed).all())+ assert bool((composed <= native).all())+ assert bool((composed < native).any())++ @pytest.mark.parametrize(+ ("override", "match"),+ [+ ({"factor": None}, "factor"),+ ({"factor": float("nan")}, "factor"),+ ({"low_freq_factor": True}, "low_freq_factor"),+ ({"high_freq_factor": -4.0}, "high_freq_factor"),+ ({"original_max_position_embeddings": 0}, "original_max_position_embeddings"),+ ({"original_max_position_embeddings": 8192.5}, "original_max_position_embeddings"),+ ({"original_max_position_embeddings": None}, "original_max_position_embeddings"),+ ],+ ids=[+ "no-factor",+ "nan-factor",+ "bool-low",+ "negative-high",+ "zero-original",+ "float-original",+ "null-original",+ ],+ )+ def test_refuses_a_malformed_native_block(self, override: dict, match: str) -> None:+ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ native = {**NATIVE_LLAMA31, **override}+ with pytest.raises(ValueError, match=match):+ compose_llama3_rope_parameters(+ native, max_position_embeddings=NATIVE_MAX, target_length=TARGET+ )++ def test_an_integral_float_original_length_is_kept_as_an_int(self) -> None:+ """transformers accepts ``8192.0`` there (it only warns), so this does too."""+ from soup_cli.utils.long_context import compose_llama3_rope_parameters++ block = compose_llama3_rope_parameters(+ {**NATIVE_LLAMA31, "original_max_position_embeddings": 8192.0},+ max_position_embeddings=NATIVE_MAX,+ target_length=TARGET,+ )++ assert block["original_max_position_embeddings"] == 8192+ assert type(block["original_max_position_embeddings"]) is int+++# ---------------------------------------------------------------------------+# apply_long_context_config — compose or refuse, before any mutation+# ---------------------------------------------------------------------------+++def _llama31_namespace(spelling: str = "rope_parameters") -> SimpleNamespace:+ """The native block in each spelling a config object can carry."""+ if spelling == "rope_parameters":+ return SimpleNamespace(+ max_position_embeddings=NATIVE_MAX, rope_parameters=dict(NATIVE_LLAMA31)+ )+ if spelling == "rope_scaling+type":+ legacy = {k: v for k, v in NATIVE_LLAMA31.items() if k != "rope_type"}+ return SimpleNamespace(+ max_position_embeddings=NATIVE_MAX, rope_scaling={**legacy, "type": "llama3"}+ )+ assert spelling == "rope_scaling+rope_type"+ return SimpleNamespace(max_position_embeddings=NATIVE_MAX, rope_scaling=dict(NATIVE_LLAMA31))+++class TestApplyLongContextConfigOnScaledCheckpoints:+ @pytest.mark.parametrize(+ "spelling", ["rope_parameters", "rope_scaling+type", "rope_scaling+rope_type"]+ )+ @pytest.mark.parametrize("requested", ["llama3", None])+ def test_llama3_on_a_native_llama3_block_composes(self, spelling: str, requested) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ config = _llama31_namespace(spelling)+ applied = apply_long_context_config(+ config, target_length=TARGET, rope_scaling_type=requested+ )++ assert applied == COMPOSED_LLAMA31+ assert config.rope_parameters == COMPOSED_LLAMA31+ assert config.max_position_embeddings == TARGET++ def test_a_real_llama_config_composes(self) -> None:+ _requires_train_extra()+ from soup_cli.utils.long_context import apply_long_context_config++ config = _tiny_llama_config(+ max_position_embeddings=NATIVE_MAX, rope_parameters=NATIVE_LLAMA31+ )+ applied = apply_long_context_config(config, TARGET, "llama3")++ assert applied == COMPOSED_LLAMA31+ assert config.rope_parameters == COMPOSED_LLAMA31+ assert config.max_position_embeddings == TARGET++ def test_composition_keeps_partial_rotary_factor(self) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ config = SimpleNamespace(+ max_position_embeddings=NATIVE_MAX,+ rope_parameters={**NATIVE_LLAMA31, "partial_rotary_factor": 0.5},+ )+ applied = apply_long_context_config(config, TARGET, "llama3")++ assert applied == {**COMPOSED_LLAMA31, "partial_rotary_factor": 0.5}++ @pytest.mark.parametrize("requested", ["linear", "dynamic", "yarn", "longrope"])+ @pytest.mark.parametrize(+ "spelling", ["rope_parameters", "rope_scaling+type", "rope_scaling+rope_type"]+ )+ def test_other_types_on_a_native_llama3_block_are_refused_before_any_mutation(+ self, requested: str, spelling: str+ ) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ config = _llama31_namespace(spelling)+ before = _snapshot(config)++ with pytest.raises(ValueError, match=r"#1239") as exc_info:+ apply_long_context_config(config, TARGET, requested)++ _message_names(+ exc_info,+ f"rope_scaling_type={requested!r}",+ "rope_type='llama3', factor=8.0",+ _COMPOSE_HINT,+ f"at or below {NATIVE_MAX}",+ )+ assert _snapshot(config) == before++ @pytest.mark.parametrize("requested", REQUESTED_TYPES)+ @pytest.mark.parametrize(+ ("native", "shown"),+ [+ (NATIVE_YARN, "rope_type='yarn', factor=4.0"),+ (NATIVE_LONGROPE, "rope_type='longrope', factor=None"),+ (NATIVE_LINEAR, "rope_type='linear', factor=4.0"),+ (NATIVE_DYNAMIC, "rope_type='dynamic', factor=2.0"),+ ],+ ids=["yarn", "longrope", "linear", "dynamic"],+ )+ def test_extending_any_other_scaled_checkpoint_is_refused(+ self, native: dict, shown: str, requested+ ) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ config = SimpleNamespace(max_position_embeddings=NATIVE_MAX, rope_parameters=dict(native))+ before = _snapshot(config)++ with pytest.raises(ValueError, match=r"#1239") as exc_info:+ apply_long_context_config(config, TARGET, requested)++ _message_names(exc_info, shown, f"at or below {NATIVE_MAX}")+ if requested is None:+ _message_names(exc_info, "rope_scaling_type=None (auto-detected 'dynamic')")+ else:+ _message_names(exc_info, f"rope_scaling_type={requested!r}")+ # llama3 composes only with a llama3 block, so it is not offered here.+ assert _COMPOSE_HINT not in str(exc_info.value)+ assert _snapshot(config) == before++ def test_a_legacy_type_key_on_a_scaled_block_is_refused_too(self) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ legacy = {k: v for k, v in NATIVE_YARN.items() if k != "rope_type"}+ config = SimpleNamespace(+ max_position_embeddings=NATIVE_MAX, rope_scaling={**legacy, "type": "yarn"}+ )+ before = _snapshot(config)++ with pytest.raises(ValueError, match=re.escape("rope_type='yarn', factor=4.0")):+ apply_long_context_config(config, TARGET, "yarn")+ assert _snapshot(config) == before++ def test_autodetect_reads_the_type_the_way_transformers_does(self) -> None:+ """With both keys present transformers builds from ``rope_type``; the None+ auto-detect follows it, so a stale legacy ``type`` cannot turn a llama3+ block into a refused ``dynamic`` request."""+ from soup_cli.utils.long_context import apply_long_context_config++ config = SimpleNamespace(+ max_position_embeddings=NATIVE_MAX,+ rope_parameters={**NATIVE_LLAMA31, "type": "linear"},+ )++ assert apply_long_context_config(config, TARGET, None) == COMPOSED_LLAMA31++ @pytest.mark.parametrize(+ "override",+ [{"factor": None}, {"low_freq_factor": True}, {"original_max_position_embeddings": 0}],+ ids=["no-factor", "bool-low", "zero-original"],+ )+ @pytest.mark.parametrize("requested", ["llama3", None])+ def test_a_malformed_native_llama3_block_is_refused_with_the_setting_and_a_way_out(+ self, override: dict, requested+ ) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ config = SimpleNamespace(+ max_position_embeddings=NATIVE_MAX,+ rope_parameters={**NATIVE_LLAMA31, **override},+ )+ before = _snapshot(config)++ with pytest.raises(ValueError) as exc_info:+ apply_long_context_config(config, TARGET, requested)++ shown = "'llama3'" if requested else "None (auto-detected 'llama3')"+ _message_names(+ exc_info,+ f"training.rope_scaling_type={shown}",+ "#1239",+ next(iter(override)),+ f"at or below {NATIVE_MAX}",+ )+ assert _snapshot(config) == before+++# ---------------------------------------------------------------------------+# Controls — behaviour that must NOT change+# ---------------------------------------------------------------------------+++def _default_rope_configs():+ """Checkpoints without RoPE scaling, in the shapes the loader can hand over."""+ configs = {"no-rope-attributes": SimpleNamespace(max_position_embeddings=4096)}+ try:+ from transformers import LlamaConfig, MistralConfig+ except ImportError: # pragma: no cover - the [train] extra is absent+ return configs+ configs["llama2-style"] = LlamaConfig(+ vocab_size=64,+ hidden_size=64,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=1,+ num_key_value_heads=1,+ max_position_embeddings=4096,+ rope_theta=10000.0,+ )+ configs["mistral-style"] = MistralConfig(+ vocab_size=64,+ hidden_size=64,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=1,+ num_key_value_heads=1,+ max_position_embeddings=4096,+ rope_theta=1000000.0,+ )+ return configs+++# What every rope_scaling_type produced for 4096 -> 16384 before #1239 (the+# control tests pass unchanged on the unfixed module, which is the point).+_EXPECTED_DEFAULT = {+ "linear": {"rope_type": "linear", "factor": 4.0},+ "dynamic": {"rope_type": "dynamic", "factor": 4.0},+ None: {"rope_type": "dynamic", "factor": 4.0},+ "yarn": {"rope_type": "yarn", "factor": 4.0, "original_max_position_embeddings": 4096},+ "llama3": {+ "rope_type": "llama3",+ "factor": 4.0,+ "original_max_position_embeddings": 4096,+ "low_freq_factor": 1.0,+ "high_freq_factor": 4.0,+ },+}+_THETA = {"no-rope-attributes": None, "llama2-style": 10000.0, "mistral-style": 1000000.0}+++class TestControls:+ @pytest.mark.parametrize("requested", ["linear", "dynamic", None, "yarn", "llama3"])+ @pytest.mark.parametrize("shape", ["no-rope-attributes", "llama2-style", "mistral-style"])+ def test_a_checkpoint_without_rope_scaling_extends_exactly_as_before(+ self, shape: str, requested+ ) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ configs = _default_rope_configs()+ if shape not in configs:+ pytest.skip("transformers is only in the [train] extra")+ config = configs[shape]+ expected = dict(_EXPECTED_DEFAULT[requested])+ if _THETA[shape] is not None:+ expected = {"rope_theta": _THETA[shape], **expected}++ applied = apply_long_context_config(config, 16384, requested)++ assert applied == expected+ assert list(applied) == list(expected)+ assert config.rope_parameters == expected+ assert config.max_position_embeddings == 16384++ @pytest.mark.parametrize("requested", REQUESTED_TYPES)+ @pytest.mark.parametrize("target", [NATIVE_MAX, 8192])+ @pytest.mark.parametrize(+ "native",+ [NATIVE_LLAMA31, NATIVE_YARN, NATIVE_LONGROPE],+ ids=["llama3", "yarn", "longrope"],+ )+ def test_a_target_at_or_below_max_is_still_a_no_op(+ self, native: dict, target: int, requested+ ) -> None:+ from soup_cli.utils.long_context import apply_long_context_config++ config = SimpleNamespace(max_position_embeddings=NATIVE_MAX, rope_parameters=dict(native))+ before = _snapshot(config)++ assert apply_long_context_config(config, target, requested) is None+ assert _snapshot(config) == before+++# ---------------------------------------------------------------------------+# longrope — refused at config load+# ---------------------------------------------------------------------------++# What the refusal must say: why longrope can extend nothing, the issue, how to+# extend a checkpoint instead, and how to fine-tune a LongRoPE one.+_LONGROPE_REASONS = (+ "#1239",+ "cannot extend any checkpoint",+ "exist only on checkpoints already scaled with LongRoPE",+ "extending an already-scaled checkpoint is refused",+ "To extend a checkpoint without RoPE scaling, use linear, dynamic, yarn or llama3",+ "leave rope_scaling_type unset",+)+++def _yaml_config(+ training: dict, *, task: str = "sft", backend: str = "transformers", max_length: int = 2048+) -> str:+ return yaml.safe_dump(+ {+ "base": "microsoft/Phi-3-mini-128k-instruct",+ "task": task,+ "backend": backend,+ "data": {"train": "train.jsonl", "max_length": max_length},+ "training": training,+ }+ )+++class TestLongropeIsRefusedAtConfigLoad:+ @pytest.mark.parametrize(+ "spelling",+ ["longrope", "LongRoPE", "LONGROPE", " longrope ", "long_rope", "long-rope", "Long RoPE"],+ )+ def test_every_spelling_is_refused_with_the_reason(self, spelling: str) -> None:+ with pytest.raises(ValueError) as exc_info:+ load_config_from_string(_yaml_config({"rope_scaling_type": spelling}))++ _message_names(exc_info, "rope_scaling_type", *_LONGROPE_REASONS)++ @pytest.mark.parametrize(+ ("task", "backend", "max_length"),+ [+ ("sft", "transformers", 2048),+ ("sft", "transformers", 262144),+ ("pretrain", "transformers", 4096),+ ("dpo", "transformers", 2048),+ ("sft", "unsloth", 2048),+ ],+ ids=["sft-short", "sft-long", "pretrain", "dpo", "unsloth"],+ )+ def test_the_refusal_is_unconditional(self, task: str, backend: str, max_length: int) -> None:+ """Not tied to a task, a backend, or whether max_length extends anything."""+ with pytest.raises(ValueError) as exc_info:+ load_config_from_string(+ _yaml_config(+ {"rope_scaling_type": "longrope"},+ task=task,+ backend=backend,+ max_length=max_length,+ )+ )++ _message_names(exc_info, *_LONGROPE_REASONS)++ def test_the_training_model_refuses_it_directly(self) -> None:+ from pydantic import ValidationError++ from soup_cli.config.schema import TrainingConfig++ with pytest.raises(ValidationError) as exc_info:+ TrainingConfig(rope_scaling_type="longrope")++ _message_names(exc_info, *_LONGROPE_REASONS)++ def test_an_unknown_type_is_no_longer_offered_longrope(self) -> None:+ with pytest.raises(ValueError) as exc_info:+ load_config_from_string(_yaml_config({"rope_scaling_type": "ntk"}))++ message = str(exc_info.value)+ for offered in ("'linear'", "'dynamic'", "'yarn'", "'llama3'"):+ assert offered in message, (offered, message)+ assert "longrope" not in message.lower()++ @pytest.mark.parametrize("kind", ["linear", "dynamic", "yarn", "llama3", None])+ def test_the_other_types_and_unset_still_load(self, kind) -> None:+ """Control: only longrope is refused."""+ training = {} if kind is None else {"rope_scaling_type": kind}+ config = load_config_from_string(_yaml_config(training))++ assert config.training.rope_scaling_type == kind++ @pytest.mark.parametrize("shape", ["no-rope-attributes", "llama2-style", "mistral-style"])+ def test_the_runtime_helper_gives_the_same_answer(self, shape: str) -> None:+ """A direct call on a checkpoint without scaling no longer advises choosing+ a LongRoPE checkpoint, which the #1239 rule refuses to extend."""+ from soup_cli.utils.long_context import apply_long_context_config++ configs = _default_rope_configs()+ if shape not in configs:+ pytest.skip("transformers is only in the [train] extra")+ config = configs[shape]+ before = _snapshot(config)++ with pytest.raises(ValueError) as exc_info:+ apply_long_context_config(config, 16384, "longrope")++ _message_names(exc_info, *_LONGROPE_REASONS)+ assert "choose a checkpoint that ships LongRoPE factors" not in str(exc_info.value)+ assert _snapshot(config) == before+++# ---------------------------------------------------------------------------+# End to end — the SFT and pretrain trainers+# ---------------------------------------------------------------------------+++def _write_tiny_tokenizer(directory) -> None:+ from tokenizers import Tokenizer, models, pre_tokenizers++ vocab = {"<unk>": 0, "<s>": 1, "</s>": 2, "<pad>": 3}+ for word in ("hello", "world", "hi", "yo"):+ vocab[word] = len(vocab)+ tokenizer = Tokenizer(models.WordLevel(vocab=vocab, unk_token="<unk>"))+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()+ tokenizer.save(str(directory / "tokenizer.json"))+ with open(directory / "tokenizer_config.json", "w", encoding="utf-8") as handle:+ json.dump(+ {+ "tokenizer_class": "PreTrainedTokenizerFast",+ "unk_token": "<unk>",+ "bos_token": "<s>",+ "eos_token": "</s>",+ "pad_token": "<pad>",+ "model_max_length": TARGET,+ "clean_up_tokenization_spaces": False,+ },+ handle,+ )+++def _save_tiny_checkpoint(directory, *, max_position_embeddings: int, rope_parameters: dict):+ import torch+ from transformers import LlamaForCausalLM++ torch.manual_seed(0)+ config = _tiny_llama_config(+ max_position_embeddings=max_position_embeddings, rope_parameters=rope_parameters+ )+ LlamaForCausalLM(config).save_pretrained(directory)+ _write_tiny_tokenizer(directory)+ return str(directory)++[email protected](scope="module")+def llama31_checkpoint(tmp_path_factory) -> str:+ _requires_train_extra()+ return _save_tiny_checkpoint(+ tmp_path_factory.mktemp("tiny-llama31"),+ max_position_embeddings=NATIVE_MAX,+ rope_parameters=NATIVE_LLAMA31,+ )++[email protected](scope="module")+def yarn_checkpoint(tmp_path_factory) -> str:+ _requires_train_extra()+ return _save_tiny_checkpoint(+ tmp_path_factory.mktemp("tiny-yarn"),+ max_position_embeddings=NATIVE_MAX,+ rope_parameters=NATIVE_YARN,+ )++[email protected](scope="module")+def longrope_checkpoint(tmp_path_factory) -> str:+ """A config-built Phi-3 shaped like Phi-3-mini-128k: LongRoPE over 4096, window 131072."""+ _requires_train_extra()+ import torch+ from transformers import Phi3Config, Phi3ForCausalLM++ half = 32 # head_dim 64 -> 32 frequency pairs, one factor each+ torch.manual_seed(0)+ config = Phi3Config(+ vocab_size=64,+ hidden_size=64,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=1,+ num_key_value_heads=1,+ max_position_embeddings=NATIVE_MAX,+ original_max_position_embeddings=4096,+ rope_parameters={+ "rope_type": "longrope",+ "short_factor": [1.0] * half,+ "long_factor": [1.0 + 15.0 * k / (half - 1) for k in range(half)],+ "rope_theta": 10000.0,+ },+ pad_token_id=3,+ bos_token_id=1,+ eos_token_id=2,+ )+ directory = tmp_path_factory.mktemp("tiny-phi3-longrope")+ Phi3ForCausalLM(config).save_pretrained(directory)+ _write_tiny_tokenizer(directory)+ return str(directory)++[email protected](scope="module")+def default_rope_checkpoint(tmp_path_factory) -> str:+ _requires_train_extra()+ return _save_tiny_checkpoint(+ tmp_path_factory.mktemp("tiny-default"),+ max_position_embeddings=8192,+ rope_parameters={"rope_type": "default", "rope_theta": 500000.0},+ )+++def _config(+ base: str,+ output,+ *,+ task: str = "sft",+ rope_type: str | None = "llama3",+ max_length: int = TARGET,+ target_modules: tuple[str, ...] = ("q_proj", "v_proj"),+):+ lora = {"r": 4, "alpha": 8, "target_modules": list(target_modules)}+ data = {"train": "unused.jsonl", "max_length": max_length}+ if task == "sft":+ data["chat_template"] = "chatml"+ training = {"quantization": "none", "batch_size": 1, "epochs": 1, "lora": lora}+ if rope_type is not None: # None leaves the key out: the setting is unset+ training["rope_scaling_type"] = rope_type+ return load_config_from_string(+ yaml.safe_dump(+ {+ "base": base,+ "task": task,+ "backend": "transformers",+ "data": data,+ "training": training,+ "output": str(output),+ }+ )+ )+++_CHAT_ROWS = {+ "train": [+ {"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "yo"}]}+ ]+ * 2+}+_TEXT_ROWS = {"train": [{"text": "hello world hi yo"}] * 2}+++def _rotary(model):+ matches = [module.rotary_emb for module in model.modules() if hasattr(module, "rotary_emb")]+ assert matches+ return matches[0]+++def _inv_freq_on_cpu(model):+ """The built model's rotary ``inv_freq``, on CPU for comparison.++ ``setup()`` builds an HF Trainer, which moves the model to the accelerator+ it finds even with ``device="cpu"`` (MPS on the macOS runners), while every+ reference tensor here is computed on CPU. ``inv_freq`` is computed on CPU+ when the model is built, so the copy back is exact.+ """+ return _rotary(model).inv_freq.detach().cpu()+++def _assert_built_with_the_composed_block(model) -> None:+ import torch++ built = _inv_freq_on_cpu(model)+ expected = _transformers_llama3_inv_freq(+ max_position_embeddings=TARGET, rope_parameters=COMPOSED_LLAMA31+ )+ native = _native_inv_freq()++ assert model.config.rope_parameters == COMPOSED_LLAMA31+ assert model.config.max_position_embeddings == TARGET+ assert torch.equal(built, expected)+ faster = [int(k) for k in torch.nonzero(built > native).flatten()]+ assert faster == [], f"pairs rotating faster than pretrained: {faster}"+ assert int((built != native).sum()) == 35+++class TestTrainers:+ def test_sft_setup_composes_the_native_llama3_block(self, llama31_checkpoint, tmp_path) -> None:+ from soup_cli.trainer.sft import SFTTrainerWrapper++ config = _config(llama31_checkpoint, tmp_path / "out")+ wrapper = SFTTrainerWrapper(config, device="cpu")+ wrapper.setup(deepcopy(_CHAT_ROWS))++ _assert_built_with_the_composed_block(wrapper.model)++ # longrope never reaches setup: config load refuses it (TestLongropeIsRefusedAtConfigLoad).+ @pytest.mark.parametrize("requested", ["linear", "dynamic", "yarn"])+ def test_sft_setup_refuses_before_the_model_is_built(+ self, llama31_checkpoint, tmp_path, requested: str+ ) -> None:+ from soup_cli.trainer.sft import SFTTrainerWrapper++ config = _config(llama31_checkpoint, tmp_path / "out", rope_type=requested)+ wrapper = SFTTrainerWrapper(config, device="cpu")++ with pytest.raises(ValueError, match=r"#1239") as exc_info:+ wrapper.setup(deepcopy(_CHAT_ROWS))++ _message_names(+ exc_info, f"rope_scaling_type={requested!r}", "rope_type='llama3', factor=8.0"+ )+ assert wrapper.model is None++ def test_sft_refuses_to_extend_a_native_yarn_checkpoint_again(+ self, yarn_checkpoint, tmp_path+ ) -> None:+ from soup_cli.trainer.sft import SFTTrainerWrapper++ config = _config(yarn_checkpoint, tmp_path / "out", rope_type="yarn")+ wrapper = SFTTrainerWrapper(config, device="cpu")++ with pytest.raises(ValueError, match=re.escape("rope_type='yarn', factor=4.0")):+ wrapper._setup_transformers(config, config.training)+ assert wrapper.model is None++ def test_pretrain_composes_the_native_llama3_block(self, llama31_checkpoint, tmp_path) -> None:+ from soup_cli.trainer.pretrain import PretrainTrainerWrapper++ config = _config(llama31_checkpoint, tmp_path / "out", task="pretrain")+ wrapper = PretrainTrainerWrapper(config, device="cpu")+ wrapper._setup_transformers(config, config.training)++ _assert_built_with_the_composed_block(wrapper.model)++ def test_pretrain_refuses_before_the_model_is_built(self, llama31_checkpoint, tmp_path) -> None:+ from soup_cli.trainer.pretrain import PretrainTrainerWrapper++ config = _config(llama31_checkpoint, tmp_path / "out", task="pretrain", rope_type="linear")+ wrapper = PretrainTrainerWrapper(config, device="cpu")++ with pytest.raises(ValueError, match=re.escape("rope_type='llama3', factor=8.0")):+ wrapper._setup_transformers(config, config.training)+ assert wrapper.model is None++ def test_sft_target_within_the_native_window_leaves_the_block_alone(+ self, llama31_checkpoint, tmp_path+ ) -> None:+ """Control: nothing is extended, so nothing is refused or rebuilt."""+ import torch++ from soup_cli.trainer.sft import SFTTrainerWrapper++ config = _config(llama31_checkpoint, tmp_path / "out", rope_type="linear", max_length=4096)+ wrapper = SFTTrainerWrapper(config, device="cpu")+ wrapper._setup_transformers(config, config.training)++ assert wrapper.model.config.max_position_embeddings == NATIVE_MAX+ assert wrapper.model.config.rope_parameters == NATIVE_LLAMA31+ assert torch.equal(_inv_freq_on_cpu(wrapper.model), _native_inv_freq())++ @pytest.mark.parametrize("task", ["sft", "pretrain"])+ def test_a_longrope_checkpoint_fine_tunes_at_its_native_length(+ self, longrope_checkpoint, tmp_path, task: str+ ) -> None:+ """Control: refusing rope_scaling_type=longrope must not refuse the checkpoint.++ Unset rope_scaling_type, set data.max_length to the full native window and+ run the real setup() and train(): optimizer steps happen with a finite loss,+ and the model keeps the checkpoint's own LongRoPE block. The rows are short,+ so the short-factor half of LongRoPE is the one exercised.+ """+ import torch+ from transformers import AutoConfig, AutoModelForCausalLM++ config = _config(+ longrope_checkpoint,+ tmp_path / "out",+ task=task,+ rope_type=None,+ max_length=NATIVE_MAX,+ target_modules=("qkv_proj",),+ )+ assert config.training.rope_scaling_type is None+ if task == "sft":+ from soup_cli.trainer.sft import SFTTrainerWrapper++ wrapper = SFTTrainerWrapper(config, device="cpu")+ wrapper.setup(deepcopy(_CHAT_ROWS))+ else:+ from soup_cli.trainer.pretrain import PretrainTrainerWrapper++ wrapper = PretrainTrainerWrapper(config, device="cpu")+ wrapper.setup(deepcopy(_TEXT_ROWS))+ result = wrapper.train()++ assert result["total_steps"] >= 1, result+ assert result["loss_summary_kind"] != "unavailable", result+ assert math.isfinite(result["final_loss"]) and result["final_loss"] > 0, result++ native_config = AutoConfig.from_pretrained(longrope_checkpoint)+ native_model = AutoModelForCausalLM.from_pretrained(longrope_checkpoint)+ native_rotary = _rotary(native_model)+ built_rotary = _rotary(wrapper.model)++ assert native_config.rope_parameters["rope_type"] == "longrope"+ assert wrapper.model.config.rope_parameters == native_config.rope_parameters+ assert wrapper.model.config.max_position_embeddings == NATIVE_MAX+ assert torch.equal(_inv_freq_on_cpu(wrapper.model), _inv_freq_on_cpu(native_model))+ assert built_rotary.attention_scaling == native_rotary.attention_scaling++ def test_sft_default_rope_checkpoint_extends_exactly_as_before(+ self, default_rope_checkpoint, tmp_path+ ) -> None:+ """Control: a checkpoint without scaling still gets the block it got before."""+ from soup_cli.trainer.sft import SFTTrainerWrapper++ config = _config(default_rope_checkpoint, tmp_path / "out", max_length=32768)+ wrapper = SFTTrainerWrapper(config, device="cpu")+ wrapper._setup_transformers(config, config.training)++ assert wrapper.model.config.max_position_embeddings == 32768+ assert wrapper.model.config.rope_parameters == {+ "rope_theta": 500000.0,+ "rope_type": "llama3",+ "factor": 4.0,+ "original_max_position_embeddings": 8192,+ "low_freq_factor": 1.0,+ "high_freq_factor": 4.0,+ }diff --git a/tests/test_issue793_rope_scaling.py b/tests/test_issue793_rope_scaling.pyindex 75b44f15..c3216a86 100644--- a/tests/test_issue793_rope_scaling.py+++ b/tests/test_issue793_rope_scaling.py@@ -153,7 +153,7 @@ def test_pretrain_constructs_the_model_with_scaled_rope(tiny_llama) -> None:assert _rotary_embedding(wrapper.model).rope_type == "linear"-def test_longrope_refuses_to_invent_model_specific_factor_vectors() -> None:+def test_longrope_is_refused_on_a_checkpoint_without_factor_vectors() -> None:from transformers import LlamaConfigfrom soup_cli.utils.long_context import apply_long_context_config@@ -165,7 +165,9 @@ def test_longrope_refuses_to_invent_model_specific_factor_vectors() -> None:num_attention_heads=4,max_position_embeddings=64,)- with pytest.raises(ValueError, match="requires model-native short_factor, long_factor"):+ # #1239: the vectors exist only on already-LongRoPE-scaled checkpoints, which+ # may not be extended either, so the refusal no longer suggests finding one.+ with pytest.raises(ValueError, match="exist only on checkpoints already scaled with LongRoPE"):apply_long_context_config(config, 256, "longrope")@@ -199,10 +201,13 @@ def test_switching_rope_type_drops_foreign_algorithm_tunables() -> None:from soup_cli.utils.long_context import apply_long_context_config+ # #1239: a native llama3 block is no longer replaced (linear on top of it is+ # refused, see test_issue1239_llama3_rope_compose.py), so a type switch now+ # starts from an unscaled block. It must still shed another algorithm's keys.config = SimpleNamespace(max_position_embeddings=64,rope_parameters={- "rope_type": "llama3",+ "rope_type": "default","factor": 8.0,"low_freq_factor": 1.0,"high_freq_factor": 4.0,diff --git a/tests/test_performance.py b/tests/test_performance.pyindex ae35ff65..192f5dc9 100644--- a/tests/test_performance.py+++ b/tests/test_performance.py@@ -726,7 +726,8 @@ class TestCombinedPerformanceConfig:assert dumped["training"]["rope_scaling_type"] == "yarn"def test_rope_scaling_all_types_accepted(self):- for scaling_type in ("linear", "dynamic", "yarn", "longrope"):+ # longrope is refused at config load (#1239): test_issue1239_llama3_rope_compose.py.+ for scaling_type in ("linear", "dynamic", "yarn"):cfg = SoupConfig(base="test/model",data={"train": "./data.jsonl"},diff --git a/tests/test_v0490.py b/tests/test_v0490.pyindex b96b6d7f..41bcb242 100644--- a/tests/test_v0490.py+++ b/tests/test_v0490.py@@ -721,7 +721,8 @@ class TestCoverageGapFixes:class TestRopeScalingTypeLiteral:- @pytest.mark.parametrize("rt", ["linear", "dynamic", "yarn", "longrope", "llama3"])+ # longrope is refused at config load (#1239): test_issue1239_llama3_rope_compose.py.+ @pytest.mark.parametrize("rt", ["linear", "dynamic", "yarn", "llama3"])def test_all_types_accepted(self, rt):yaml_in = f"""base: meta-llama/Llama-3.1-8Bdiff --git a/tests/test_v0534.py b/tests/test_v0534.pyindex ddb71ca5..7792ccb4 100644--- a/tests/test_v0534.py+++ b/tests/test_v0534.py@@ -319,14 +319,18 @@ class TestApplyLongContextLlama3Autodetect:"low_freq_factor": 1.0, "high_freq_factor": 4.0},)# Caller explicitly asks for linear — must not silently switch to llama3.- result = apply_long_context_config(- model_config,- target_length=16384,- rope_scaling_type="linear",- model_name="meta-llama/Llama-3.1-8B",- )- assert result is not None- assert result["rope_type"] == "linear"+ # #1239: nor may linear silently replace the checkpoint's own llama3+ # block, so the explicit pick is refused by name rather than rewritten.+ with pytest.raises(ValueError, match="rope_scaling_type='linear'") as exc_info:+ apply_long_context_config(+ model_config,+ target_length=16384,+ rope_scaling_type="linear",+ model_name="meta-llama/Llama-3.1-8B",+ )+ assert "rope_type='llama3', factor=8.0" in str(exc_info.value)+ assert model_config.max_position_embeddings == 8192+ assert not hasattr(model_config, "rope_parameters")def test_rope_scaling_with_rope_type_alias(self):"""v0.49.0 detect helper also accepts the newer ``rope_type`` key."""