Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(verify): read RoPE bases from either config layout

thread3dd1021f5416f1
diff --git a/setup_laya.sh b/setup_laya.sh
deleted file mode 100755
index 8fbe7a42..00000000
--- a/setup_laya.sh
+++ /dev/null
@@ -1,108 +0,0 @@
-#!/usr/bin/env bash
-# Reproducible local setup for Laya on this machine (macOS on Intel x86_64).
-#
-# Creates an isolated virtualenv, installs the only PyTorch release that still ships a
-# macOS Intel wheel, installs the newest transformers that runs on it, downloads the three
-# Laya checkpoints, and verifies the result with a real forward pass.
-#
-# Usage: ./setup_laya.sh [--skip-models] [--skip-verify]
-# Idempotent: re-running only fixes what is missing.
-set -euo pipefail
-
-ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # repository root
-VENV="$ROOT/.venv"
-PYTHON_BIN="${PYTHON:-python3}"
-
-# Keep every byte this setup writes inside the project directory.
-export PIP_CACHE_DIR="$ROOT/.pip-cache"
-export HF_HOME="$ROOT/.hf-cache"
-export HF_HUB_DISABLE_TELEMETRY=1
-export TOKENIZERS_PARALLELISM=false
-export USE_TF=0 # Laya is torch-only; a stray TensorFlow install can deadlock loading
-export USE_TORCH=1
-
-SKIP_MODELS=0
-SKIP_VERIFY=0
-for arg in "$@"; do
- case "$arg" in
- --skip-models) SKIP_MODELS=1 ;;
- --skip-verify) SKIP_VERIFY=1 ;;
- *) echo "unknown option: $arg" >&2; exit 2 ;;
- esac
-done
-
-say() { printf '\n\033[1m==> %s\033[0m\n' "$*"; }
-
-say "Host"
-uname -srm
-"$PYTHON_BIN" -c 'import platform,sys;print("python", sys.version.split()[0], platform.machine())'
-
-if [ "$(uname -s)" != "Darwin" ]; then
- echo "warning: this script targets macOS; continuing anyway" >&2
-fi
-
-say "Virtualenv at $VENV"
-if [ ! -x "$VENV/bin/python" ]; then
- "$PYTHON_BIN" -m venv "$VENV"
-fi
-"$VENV/bin/python" -m pip install --quiet --upgrade pip
-
-say "Dependencies"
-# torch: PyPI and download.pytorch.org both stopped publishing macOS x86_64 wheels after
-# 2.2.2, so this is the newest PyTorch this CPU can run from a wheel.
-# numpy: torch 2.2.2 was compiled against NumPy 1.x and fails to initialise under NumPy 2.
-# transformers: 4.57.x is the last 4.x line (5.x requires torch>=2.4, unavailable here) and
-# the oldest line that reads both the ModernBERT and mmBERT checkpoints.
-# huggingface_hub is capped <1.0 by transformers 4.x.
-"$VENV/bin/python" -m pip install \
- "numpy<2" \
- "torch==2.2.2" \
- "transformers==4.57.6" \
- "safetensors>=0.4.0" \
- "huggingface_hub>=0.34.0,<1.0"
-
-say "Installing the laya package (editable)"
-"$VENV/bin/python" -m pip install --quiet -e "$ROOT"
-
-if [ "$SKIP_MODELS" -eq 0 ]; then
- say "Checkpoints -> $ROOT/models"
- if [ -f "$ROOT/models/laya/model.safetensors" ]; then
- echo "already present, skipping download"
- else
- # One repo bundles all three checkpoints; ~2.3 GB of safetensors.
- ( cd "$ROOT" && "$VENV/bin/python" - <<'PY'
-from huggingface_hub import snapshot_download
-p = snapshot_download(
- "convaiinnovations/laya",
- local_dir="models/laya",
- allow_patterns=["*.json", "*.safetensors", "*.txt", "tokenizer.json"],
-)
-print("downloaded ->", p)
-PY
- )
- fi
- # tests/test_local_e2e.py expects <root>/{laya,laya-multilingual,laya-typed-decisions};
- # the bundle ships the two extra checkpoints as subfolders of the first.
- ln -sfn laya/multilingual "$ROOT/models/laya-multilingual"
- ln -sfn laya/typed-decisions "$ROOT/models/laya-typed-decisions"
- ls -l "$ROOT/models"
-fi
-
-# A truncated or silently-updated download turns into quietly wrong answers, so check the weights
-# against the hashes recorded in verify/checkpoints.json. Runs whenever the weights are there,
-# including on a --skip-models re-run.
-if [ -f "$ROOT/models/laya/model.safetensors" ]; then
- say "Checking checkpoint integrity"
- "$VENV/bin/python" "$ROOT/verify/checkpoints.py" --models "$ROOT/models"
-elif [ "$SKIP_MODELS" -eq 0 ]; then
- echo "warning: models/laya/model.safetensors is still missing" >&2
-fi
-
-if [ "$SKIP_VERIFY" -eq 0 ]; then
- say "Verifying with real weights"
- "$VENV/bin/python" "$ROOT/laya_smoke_test.py" --models "$ROOT/models"
-fi
-
-say "Done"
-echo "Activate with: source \"$VENV/bin/activate\""
-echo "Run the suite: python tests/test_local_e2e.py \"$ROOT/models\""
diff --git a/tests/test_packaging.py b/tests/test_packaging.py
index f4349a3d..66971a35 100644
--- a/tests/test_packaging.py
+++ b/tests/test_packaging.py
@@ -117,11 +117,9 @@ def _headings(path):
_md = []
for _dirpath, _dirnames, _filenames in os.walk("."):
- # `.pytest_cache` ships a README of its own and is not part of the repository, and `.hf-cache`
- # holds third-party dataset cards downloaded by setup_laya.sh (both are gitignored).
+ # `.pytest_cache` ships a README of its own and is not part of the repository.
_dirnames[:] = [d for d in _dirnames
- if d not in (".git", "__pycache__", "node_modules", ".pytest_cache",
- ".hf-cache")]
+ if d not in (".git", "__pycache__", "node_modules", ".pytest_cache")]
_md.extend(os.path.normpath(os.path.join(_dirpath, f))
for f in _filenames if f.endswith(".md"))
_md = sorted(_md)
diff --git a/laya_smoke_test.py b/verify/laya_smoke_test.py
similarity index 100%
rename from laya_smoke_test.py
rename to verify/laya_smoke_test.py
diff --git a/verify/numerics_check.py b/verify/numerics_check.py
index 09956c91..1b5bd2a9 100644
--- a/verify/numerics_check.py
+++ b/verify/numerics_check.py
@@ -1,8 +1,9 @@
"""Numerics check: is the forward pass on this machine trustworthy?
For every checkpoint:
- 1. The RoPE base transformers 4.x actually uses == the one the checkpoint was trained with
- (transformers 5 records it as `rope_parameters`).
+ 1. The RoPE bases actually in use == the ones the checkpoint records, read from either config
+ layout (`rope_parameters` on transformers 5; `global_rope_theta` / `local_rope_theta` on
+ 4.x).
2. Run-to-run determinism (same model, same input, twice) -- the float32 noise floor.
3. SDPA (what Laya asks transformers for) vs eager (reference math), on the user-visible
answers: choice labels, probabilities, confidence, noul, score.
@@ -67,6 +68,38 @@ def compare(label, a, b):
return worst
+def _theta(node, layer, flat=None):
+ """A per-layer `rope_theta` from a `rope_parameters` mapping, or the flat fallback."""
+ if isinstance(node, dict):
+ params = node.get(layer)
+ if isinstance(params, dict) and "rope_theta" in params:
+ return float(params["rope_theta"])
+ if flat is not None:
+ return float(flat)
+ return None
+
+
+def rope_pair(source):
+ """The (full_attention, sliding_attention) RoPE bases a config records.
+
+ transformers 5 stores them per attention layer under `rope_parameters`; 4.x keeps
+ `global_rope_theta` / `local_rope_theta` flat. `source` is a live config (after
+ `_apply_rope_config`, which maps the 5.x layout onto the attributes 4.x reads) or the raw
+ config.json, so this runs without assuming which version produced the checkpoint.
+ """
+ rope = (source.get("rope_parameters") if isinstance(source, dict)
+ else getattr(source, "rope_parameters", None))
+ if isinstance(rope, dict):
+ flat = rope.get("rope_theta")
+ full = _theta(rope, "full_attention", flat)
+ sliding = _theta(rope, "sliding_attention", flat)
+ if full is not None and sliding is not None:
+ return full, sliding
+ if isinstance(source, dict):
+ return source.get("global_rope_theta"), source.get("local_rope_theta")
+ return getattr(source, "global_rope_theta", None), getattr(source, "local_rope_theta", None)
+
+
def main():
print("torch %s" % torch.__version__)
failures = []
@@ -75,14 +108,15 @@ def main():
path = os.path.join(ROOT, rel)
raw = json.load(open(os.path.join(path, "encoder", "config.json")))
ecfg = AutoConfig.from_pretrained(os.path.join(path, "encoder"))
+ # transformers 4.x reads flat attributes, so map the 5.x `rope_parameters` layout onto
+ # them first; on 5.x this is a no-op and the live config already carries that mapping.
_apply_rope_config(ecfg)
- want = raw.get("rope_parameters") or {}
- rope_ok = (float(want["full_attention"]["rope_theta"]) == ecfg.global_rope_theta and
- float(want["sliding_attention"]["rope_theta"]) == ecfg.local_rope_theta)
+ full, sliding = rope_pair(ecfg)
+ want_full, want_sliding = rope_pair(raw)
+ rope_ok = (full is not None and sliding is not None and
+ full == want_full and sliding == want_sliding)
print("\n %-16s rope full=%-8s sliding=%-8s (trained %s / %s) %s"
- % (name, ecfg.global_rope_theta, ecfg.local_rope_theta,
- want["full_attention"]["rope_theta"], want["sliding_attention"]["rope_theta"],
- "OK" if rope_ok else "MISMATCH"))
+ % (name, full, sliding, want_full, want_sliding, "OK" if rope_ok else "MISMATCH"))
if not rope_ok:
failures.append("%s rope theta" % name)