FarmHouse: Laya connections (Forge concrete path, extra questions, capture, fine-tuning data, card roles)
farmhouse_laya.py: Laya as a second opinion over Forge's concrete candidate ids (shadow by default; assist never overrides a pick Forge tagged stops_immediate_win/wins_now), two extra typed questions in the same forward pass, a laya-shadow-v1 capture log, batched cached card-role classification. scripts/farmhouse_laya_dataset.py turns the capture log into train/valid files with the baselines to beat; farmhouse_laya_roles_eval.py measures role accuracy. Hooks into farmhouse_decide.py. Reference copies of the Laya image, manifests and CI in farmhouse/laya/. docs/LAYA-CONNECTIONS.md. 39 offline tests. All off by default. The matching hook in routes/policy.py is in the working tree only: that route belongs to the pending strategic-evaluator work. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016Er49soaMyG7Yburq57PeB
This commit is contained in:
1 parent
32ab268f88
commit
6569bb6f0d
13 files changed
+1185
-1
No files matched your search
@@ -50,6 +50,12 @@ sure; `off` (default) does nothing. `scripts/farmhouse_decision_eval.py` replays
|
||||
guessing the commonest action** (English 16.1%, typed-decisions 18.6%, baseline 27.5%), at 2-4 s per answer on a 4-thread CPU. It is only
|
||||
worth using after fine-tuning on this game's decisions; the write-up is `LAYA-EVALUATION.md` in the farmhouse-os repo's commander-lab folder.
|
||||
|
||||
### Laya connections (all off by default)
|
||||
Forge's concrete priority path, extra typed questions in the same call, a capture log, a fine-tuning dataset exporter, and card-role classification:
|
||||
`src/commander_ai_lab/sim/farmhouse_laya.py`, `scripts/farmhouse_laya_dataset.py`, `scripts/farmhouse_laya_roles_eval.py`, tests `tests/farmhouse/test_farmhouse_laya*.py`.
|
||||
How it fits the strategic-intelligence work, what is measured and how to fine-tune: [docs/LAYA-CONNECTIONS.md](docs/LAYA-CONNECTIONS.md). Reference copies of the Laya
|
||||
image, manifests and CI are in `farmhouse/laya/`.
|
||||
|
||||
## Settings (environment variables)
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# Laya connections
|
||||
|
||||
Laya (and Kev: same `POST /v1/systemone` API) is a **decision model**: typed multiple-choice, yes/no and score questions about a text, answered in
|
||||
one forward pass, no generated text. This page is where it plugs into the strategic-intelligence work in this repository
|
||||
([INTELLIGENCE-HANDOFF.md](INTELLIGENCE-HANDOFF.md)), what is measured, and how to make it worth using. Written 2026-10-26.
|
||||
|
||||
**Short version.** Every connection below is built, tested offline and **off by default**. Zero-shot, Laya is a poor action chooser
|
||||
(below the always-guess baseline) but a reasonable card classifier (48% against 17% by chance); it is too slow on a CPU for Forge's
|
||||
priority path (8 s against a 1.5 s budget). The way forward is fine-tuning on the decisions these connections record.
|
||||
|
||||
## What connects where
|
||||
|
||||
| Connection | Code | Mode | Notes |
|
||||
|---|---|---|---|
|
||||
| Farmhouse macro choice: Laya picks among CSIE's candidate macros, reading the CSIE ranking and ITI objective in its text | `farmhouse_decide.py` (called from `deepseek_brain.py`) | `DECISION_MODE=shadow` records agreement with the LLM; `assist` uses a pick it is `DECISION_MIN_CONF` sure of | existing; only offered candidates are accepted |
|
||||
| **Forge concrete priority choice**: Laya picks among the same concrete candidate IDs Forge sent to `/api/policy/decide/concrete` | `farmhouse_laya.advise_concrete` / `attach_concrete`, called from `routes/policy.py` | `shadow`: adds `laya` to the response, selection unchanged. `assist`: may replace `selected_id`, never one Forge tagged `stops_immediate_win` / `wins_now`; the original is kept as `csie_selected_id` | candidate described by kind, card, cost, target, tags (never by its opaque id); Forge still executes only an ID it sent |
|
||||
| **Extra questions in the same call**: "how dangerous are the opponents' boards?" (none/low/moderate/high/lethal) and "is there a threat that must be answered?" | `farmhouse_laya._extra_questions` | whenever Laya is asked | one forward pass answers all questions, so they cost almost nothing; recorded as weak signals for the learned-threat work, **not used to decide** |
|
||||
| **Capture**: every call is appended to `data/decisions/laya-shadow-<date>.jsonl` (`laya-shadow-v1`) | `farmhouse_laya.capture` | shadow / assist | the text Laya read, the offered options, its answer and extras, and the other deciders' picks (`labels`: `llm`, `csie`, `selected`) |
|
||||
| **Fine-tuning data**: capture log -> `train.jsonl` / `valid.jsonl` / `manifest.json`, split by game, with the baselines to beat | `scripts/farmhouse_laya_dataset.py` | offline | the manifest reports commonest-action, CSIE-vs-teacher and Laya-zero-shot agreement on the validation side |
|
||||
| **Card role evidence**: removal, board wipe, ramp, card draw, counterspell, protection, tutor, creature, other, from Oracle text | `farmhouse_laya.classify_roles` (batched, cached, with `source: laya:<model>` provenance); `scripts/farmhouse_laya_roles_eval.py` measures it | on demand | evidence for ITI / Tagger-style use, never a rules fact |
|
||||
|
||||
Not built (still the open items in the handoff, none of which Laya can substitute for): compiling and running the Forge controller, the bounded
|
||||
combo executor, the multi-turn planner, the calibrated learned-threat model. Laya's "threat" and "must answer" extras are only raw material for that last one.
|
||||
|
||||
## Where the hooks are
|
||||
- `src/commander_ai_lab/sim/farmhouse_decide.py` (committed): the macro-choice client gained the extra questions, the state text/options in its
|
||||
answer, and `record()` writes the capture line.
|
||||
- `routes/policy.py` (**working tree only, uncommitted**: the route itself is part of the pending strategic-evaluator work, so the hook was
|
||||
left for that commit). It is one block in `decide_concrete`, after the result is computed:
|
||||
`if _L.mode() != "off": advice = await run_in_threadpool(_L.advise_concrete, ...); result = _L.attach_concrete(...)`, guarded by `except ImportError`.
|
||||
- Everything else is new files: `farmhouse_laya.py`, the two scripts, `tests/farmhouse/test_farmhouse_laya*.py`, `farmhouse/laya/`.
|
||||
|
||||
## Settings
|
||||
`DECISION_URL` (e.g. `http://laya.commander-lab.svc.cluster.local:8080`), `DECISION_MODE` (`off` default / `shadow` / `assist`), `DECISION_MODEL`
|
||||
(a checkpoint such as `typed-decisions`), `DECISION_MIN_CONF` (0.7), `DECISION_TIMEOUT` (5 s), `DECISION_TIMEOUT_FORGE` (**1.5 s**: Forge waits on this),
|
||||
`DECISION_API_KEY`, `LAYA_CAPTURE_DIR` (`data/decisions`), `LAYA_CAPTURE=0` to stop writing capture lines. Three failures in a row pause asking for a minute.
|
||||
|
||||
## Rules the code enforces
|
||||
1. Text is built from public facts and the acting player's own hand. An opponent's `hand` field is never read, even if a client sends one (tested).
|
||||
2. Laya's answer must be one of the options that were offered; anything else is discarded.
|
||||
3. In assist, a pick Forge marked `stops_immediate_win` / `wins_now` is never overridden, and the response says what CSIE chose.
|
||||
4. A missing, slow or broken server returns "no answer"; nothing raises and the game proceeds as without Laya.
|
||||
5. Scores and probabilities are relative signals; Laya's probabilities are not calibrated for this game.
|
||||
|
||||
## What was measured (2026-10-26, `typed-decisions` checkpoint, 4-thread CPU)
|
||||
- **Macro action vs the LLM, 149 recorded decisions:** 16.1% (English) and 18.6% (typed-decisions); always guessing the commonest action 27.5%.
|
||||
- **Forge-shaped priority choice, 3 scenarios, with CSIE's ranking in the text:** agreed with CSIE all three times (expected: the ranking is in the
|
||||
text it reads), 42-48% sure, **7.5-8.4 s per call** with the extra questions. That is five times Forge's 1.5 s budget: on this CPU the Forge path
|
||||
would time out and fall back; it needs a GPU (33 ms quoted) or a smaller text.
|
||||
- **Extras:** "threat" said *high* for a lethal stack, a calm board and a behind board alike (useless zero-shot); "must answer" gave 0.48 for the
|
||||
lethal stack against 0.25 and 0.29 for the others (right direction, weak).
|
||||
- **Card roles from Oracle text, 150 unambiguous cards:** 48.0% (16.7% by chance among the six roles present); counterspell 76%, board wipe 64%,
|
||||
removal 40%, tutor 40%, ramp 36%, card draw 32%; when 70% sure, 69% right but only 11% of cards reach that. **3.2 s per card** in batches on the CPU:
|
||||
fine for the cards in a hand (cached), not for tagging 30,000 cards (about a day).
|
||||
|
||||
## How to make it worth using
|
||||
1. Run games with `DECISION_URL` set and `DECISION_MODE=shadow` (Farmhouse LLM games, and Forge games through `/api/policy/decide/concrete`).
|
||||
2. `python scripts/farmhouse_laya_dataset.py --teacher llm` (or `csie`, or `selected`). Read `manifest.json`: the **validation baselines** are the bar.
|
||||
A student of CSIE can at best equal CSIE, which is free; a student of the LLM is the useful one. Several thousand rows are needed.
|
||||
3. Fine-tune with Laya's own notebook/script (github.com/NandhaKishorM/laya, `notebooks/`; 2xT4 about 4-5 hours, or Apple silicon). Its worked example
|
||||
(browser agent choosing among ~45 concrete candidates) went from 0.10 zero-shot to 0.66, so a concrete-candidate head is the shape that works.
|
||||
Adapt the row field names if its loader differs.
|
||||
4. Serve the result (`LAYA_EXTRA_MODELS` / `DECISION_MODEL`), rerun `scripts/farmhouse_decision_eval.py` and the dataset manifest, and only then
|
||||
try `assist`. A GPU host makes the Forge path possible.
|
||||
5. Keep game result and decision quality separate (handoff boundary 6 / learned-threat contract): a captured label is a teacher's choice, not proof it was right.
|
||||
|
||||
Deployment reference copies are in `farmhouse/laya/` (image, manifests, CI); the source of truth is the farmhouse-os GitOps repo.
|
||||
@@ -0,0 +1,34 @@
|
||||
# Laya (https://github.com/NandhaKishorM/laya, Apache-2.0): a "decision model". It answers typed multiple-choice / yes-no / score
|
||||
# questions about a piece of text in ONE forward pass (about 33 ms on a GPU) and never writes text. Here it is staged for the Commander
|
||||
# AI Lab simulator, which asks an LLM "which action?" about 25 times per game; a small classifier can answer that class of question
|
||||
# far faster, if it is accurate enough (it is measured in shadow mode first, see ../README.md).
|
||||
#
|
||||
# CPU only. The weights are baked in at a pinned Hugging Face commit and the pod has NO network access (NetworkPolicy), so the
|
||||
# running service fetches nothing. Two checkpoints are included so they can be compared: the English base and the fine-tuned
|
||||
# "typed-decisions" one (about 840 MB each).
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
ARG LAYA_VERSION=0.4.15
|
||||
ARG LAYA_HF_REVISION=7b928d828b7b0e022f929d9bd2e44165aa270148
|
||||
|
||||
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HOME=/opt/hf
|
||||
|
||||
RUN pip install torch --index-url https://download.pytorch.org/whl/cpu \
|
||||
&& pip install "laya[serve]==${LAYA_VERSION}"
|
||||
|
||||
# Weights at the pinned commit. HF's offline lookup resolves the "main" ref, which a commit-pinned download does not create, so it is
|
||||
# written by hand to the same commit.
|
||||
RUN python -c "from huggingface_hub import snapshot_download; snapshot_download('convaiinnovations/laya', revision='${LAYA_HF_REVISION}', ignore_patterns=['multilingual/*','assets/*','eval/*'])" \
|
||||
&& mkdir -p /opt/hf/hub/models--convaiinnovations--laya/refs \
|
||||
&& printf '%s' "${LAYA_HF_REVISION}" > /opt/hf/hub/models--convaiinnovations--laya/refs/main \
|
||||
&& chmod -R a+rX /opt/hf
|
||||
|
||||
RUN useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin laya
|
||||
USER 10001
|
||||
|
||||
ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
|
||||
LAYA_HOST=0.0.0.0 LAYA_PORT=8080 \
|
||||
LAYA_MODELS=english,typed-decisions LAYA_DEFAULT_MODEL=english LAYA_MAX_LOADED=2 LAYA_PRELOAD=1 LAYA_THREADS=4
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["laya-serve"]
|
||||
@@ -0,0 +1,52 @@
|
||||
# Laya as the simulator's "which action?" model: evaluation, 2026-10-26
|
||||
|
||||
**Result: not usable as shipped.** Both checkpoints agreed with the LLM less often than a model that always answers the commonest action.
|
||||
|
||||
## What was measured
|
||||
The simulator's LLM brain ("twin-turbo") picks one of nine actions about 25 times a game. A decision model (Laya, or Kev; both serve
|
||||
`POST /v1/systemone`) could answer that kind of question in one forward pass instead of a 7-second generation. To find out whether it
|
||||
could stand in, every LLM decision the app had recorded (`/app/logs/decisions/*.jsonl`: the game state and the action the LLM chose)
|
||||
was replayed through Laya with the same question, and the answers compared. The LLM is the *teacher*, not the truth: this measures
|
||||
whether a fast model can imitate the slow one, not which plays better.
|
||||
|
||||
Script: `image/farmhouse_decision_eval.py` (in the app image as `/app/scripts/farmhouse_decision_eval.py`):
|
||||
`DECISION_URL=http://laya:8080 python scripts/farmhouse_decision_eval.py /app/logs/decisions english typed-decisions`
|
||||
|
||||
## Numbers (149 recorded decisions)
|
||||
LLM's choices: play_land 41, hold 31, attack_all 28, cast_creature 20, cast_spell 13, attack_safe 7, cast_removal 5, cast_ramp 4.
|
||||
|
||||
| | agrees with the LLM | answers | time per answer | what it picked |
|
||||
|---|---|---|---|---|
|
||||
| always "play_land" (baseline) | **27.5%** | 149 | 0 | |
|
||||
| `english` (ModernBERT-large, base) | 16.1% | 149 | 1.9 s | cast_creature 105, attack_all 26; never hold, almost never play_land |
|
||||
| `typed-decisions` (fine-tuned) | 18.6% | 140 (9 timed out at 5 s) | ~4 s (shared CPU) | cast_creature 99, attack_all 26 |
|
||||
|
||||
It could say "cast_creature" and "attack_all" and little else; it never recognised "hold" (31 of the LLM's choices) or a removal spell.
|
||||
|
||||
## Why, and caveats
|
||||
- The shipped checkpoints are trained on generic ticket-triage style decisions. Laya's own README says fine-tuning "on decisions from your
|
||||
own domain is where accuracy jumps" (0.766 against 0.362 for the base on its own benchmark). This game's decisions were never in its training.
|
||||
- Speed on this cluster's CPU (4 threads) was 2-4 s per answer, not the ~33 ms quoted for a GPU. Against the LLM's ~7.5 s that is not the
|
||||
speed-up that was hoped for either, without a GPU.
|
||||
- The question wording (the nine action descriptions) and the compact text it reads (`farmhouse_decide.compact_state`) are mine; a
|
||||
better prompt might help a little, not from 18% to usable.
|
||||
- Part of the recorded data predates the card-data fix (v10), so some states had thinner hands than they would now.
|
||||
- The LLM being the "truth" also caps the result: where the LLM is wrong, agreeing with it is not a win.
|
||||
|
||||
## Where this leaves it
|
||||
- Laya is **staged but scaled to 0 replicas** (`deployment-laya.yaml`: `replicas: 0`; set to 1 to run it). The image
|
||||
(`ghcr.io/fez5587/farmhouse-laya:v1`, offline, weights baked in), the service and the network policy remain.
|
||||
- The app is wired to use it (`DECISION_URL`, `DECISION_MODE`) and `DECISION_MODE` is `off`. `shadow` records agreement without
|
||||
affecting games; `assist` uses it when it is `DECISION_MIN_CONF` sure. Kev speaks the same API, so swapping is a URL.
|
||||
- To make it worth using: fine-tune on this game's decisions (Laya ships a Kaggle 2xT4 notebook, about 4 hours, and an Apple/CPU
|
||||
script). The labels would be the LLM's recorded decisions; a few thousand are needed, so generate them first (LLM games at ~7 s a
|
||||
decision, or label states with the engine's own heuristic for the cheap, abundant version). Then re-run this evaluation.
|
||||
- Node memory: it needed about 2 GB (3.6 GB with both checkpoints, which pushed the control-plane node to 92%; it is pinned to the other node).
|
||||
|
||||
## Later the same day: the new connections (see docs/LAYA-CONNECTIONS.md in the fork)
|
||||
- **Forge-shaped priority choice** (CSIE's ranking in the text, three scenarios): agreed with CSIE each time, 42-48% sure, 7.5-8.4 s per call on the CPU against Forge's
|
||||
1.5 s budget. Not usable on a CPU; the code falls back silently.
|
||||
- **Card roles from Oracle text** (150 unambiguous cards, 6 roles present, 9 offered): 48% against 17% by chance (counterspell 76%, board wipe 64%, removal 40%, tutor 40%,
|
||||
ramp 36%, card draw 32%), 3.2 s per card in batches. Much better than the action choice; useful as on-demand evidence for the cards in a hand, too slow to tag the whole pool.
|
||||
- **Extra questions** in the same call: "threat" said *high* for everything; "must answer" gave 0.48 for a lethal stack against 0.25-0.29 otherwise (right direction, weak).
|
||||
- Capture, dataset export and the rest are built and off by default; fine-tuning on the captured decisions is the path to making it useful.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Laya in this repository
|
||||
|
||||
Laya (https://github.com/NandhaKishorM/laya, Apache-2.0) is a **decision model**: it answers typed multiple-choice, yes/no and score
|
||||
questions about a piece of text in one forward pass and never writes text. Here it is a fast second opinion beside the LLM and CSIE.
|
||||
Kev (https://github.com/jaredpalmer/kev) serves the same `POST /v1/systemone` API, so swapping is a URL change (Kev needs a GPU).
|
||||
|
||||
| File | What |
|
||||
|---|---|
|
||||
| `Dockerfile` | CPU image: `laya[serve]` 0.4.15 + CPU torch, English and `typed-decisions` checkpoints baked in at Hugging Face commit `7b928d8`; runs offline |
|
||||
| `deployment-laya.yaml` | Kubernetes Deployment + Service + NetworkPolicy (no egress; only the app may call it). Currently `replicas: 0` |
|
||||
| `build-farmhouse-laya.workflow.yml` | the CI workflow that builds and smoke-tests the image offline (it lives in `.github/workflows/` of the farmhouse-os GitOps repo) |
|
||||
| `LAYA-EVALUATION.md` | why it is off: zero-shot both checkpoints agreed with the LLM less often than always guessing the commonest action |
|
||||
|
||||
The deployment source of truth is the farmhouse-os repo (`infrastructure/apps/commander-lab/`); these are reference copies so the
|
||||
fork is self-contained. Things learned running it:
|
||||
|
||||
- A Kubernetes Service named `laya` injects `LAYA_PORT=tcp://...`, which `laya-serve` reads as its own port setting and refuses. Set
|
||||
`enableServiceLinks: false` and `LAYA_PORT=8080` explicitly.
|
||||
- Two checkpoints resident use 3.6 GB; one uses about 1.9 GB. Do not place it on a control-plane node.
|
||||
- The CPU answers in 2-4 s, not the ~33 ms quoted for a GPU.
|
||||
- How the code in this repository connects to it, and how to fine-tune it: `docs/LAYA-CONNECTIONS.md`.
|
||||
@@ -0,0 +1,96 @@
|
||||
name: Build FarmHouse Laya
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "infrastructure/apps/commander-lab/laya/**"
|
||||
- ".github/workflows/build-farmhouse-laya.yml"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
env:
|
||||
IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/farmhouse-laya
|
||||
# Bump together with the image tag in infrastructure/apps/commander-lab/deployment-laya.yaml.
|
||||
IMAGE_TAG: v1
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set image name lowercase
|
||||
shell: bash
|
||||
run: |
|
||||
echo "IMAGE=$(echo "${IMAGE_NAME}" | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build validation image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: infrastructure/apps/commander-lab/laya
|
||||
load: true
|
||||
push: false
|
||||
tags: laya:test
|
||||
|
||||
# The service must answer with NO network (that is how it runs in the cluster) as the unprivileged user, for both checkpoints.
|
||||
- name: Smoke test (boots offline, answers a game-state question with both checkpoints)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run -d --name laya --network none laya:test
|
||||
cat > /tmp/ask.py <<'PY'
|
||||
import json, sys, time, urllib.request
|
||||
model = sys.argv[1]
|
||||
body = {"model": model,
|
||||
"state": {"body": "Turn 4. You have 4 lands untapped. Hand: Llanowar Elves, Swords to Plowshares, Forest. Opponent has a 6/6 creature attacking you."},
|
||||
"questions": {"action": {"type": "choice", "instructions": "Which action is best this turn?",
|
||||
"criteria": {"cast_creature": "put a creature onto the battlefield",
|
||||
"cast_removal": "destroy or exile an opposing permanent",
|
||||
"play_land": "play a land",
|
||||
"hold": "do nothing this turn"}}}}
|
||||
req = urllib.request.Request("http://127.0.0.1:8080/v1/systemone", data=json.dumps(body).encode(), headers={"content-type": "application/json"})
|
||||
t = time.time()
|
||||
out = json.load(urllib.request.urlopen(req, timeout=120))
|
||||
print(model, "%.0f ms" % ((time.time() - t) * 1000), json.dumps(out)[:600])
|
||||
assert "answers" in out and "action" in out["answers"], out
|
||||
PY
|
||||
docker cp /tmp/ask.py laya:/tmp/ask.py
|
||||
ok=0
|
||||
for i in $(seq 1 120); do
|
||||
if docker exec laya python -c "import socket; socket.create_connection(('127.0.0.1', 8080), 2)" 2>/dev/null; then ok=1; break; fi
|
||||
sleep 3
|
||||
done
|
||||
if [ "$ok" != 1 ]; then echo "laya did not open its port"; docker logs laya | tail -60; exit 1; fi
|
||||
for m in english typed-decisions; do docker exec laya python /tmp/ask.py "$m"; done
|
||||
docker exec laya id
|
||||
docker rm -f laya >/dev/null
|
||||
echo SMOKE OK
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and publish
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: infrastructure/apps/commander-lab/laya
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.IMAGE }}:${{ env.IMAGE_TAG }}
|
||||
${{ env.IMAGE }}:${{ github.sha }}
|
||||
labels: |
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
@@ -0,0 +1,93 @@
|
||||
# Laya, a CPU decision model (laya/Dockerfile), staged for the simulator. Reached only by the app, over the cluster network, on 8080.
|
||||
# No internet, no volume (weights are in the image), no service-account token.
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: laya
|
||||
namespace: commander-lab
|
||||
labels: {app: laya}
|
||||
spec:
|
||||
# 0 since 2026-10-26: both checkpoints scored BELOW the always-guess baseline against the LLM's recorded decisions (English 16.1%, typed-decisions
|
||||
# 18.6%, baseline 27.5%, 149 states), and ~2 GB of the node's memory was needed for the card-search index build. Set to 1 to bring it back
|
||||
# (image, service and policy stay in place); it is only worth running once it is fine-tuned on this game's decisions (README).
|
||||
replicas: 0
|
||||
selector:
|
||||
matchLabels: {app: laya}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: laya}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
# Kubernetes injects LAYA_PORT=tcp://<ip>:8080 for a Service named laya, and laya-serve reads LAYA_PORT as its own port setting
|
||||
# ("invalid LAYA_PORT 'tcp://...'", crash loop). Service-link variables are not wanted here at all.
|
||||
enableServiceLinks: false
|
||||
# NOT on talos-gmw: that node runs the Kubernetes API server, and Laya's first placement there (two checkpoints, 3.6 GB) took it from
|
||||
# 68% to 92% memory on 2026-10-26.
|
||||
nodeSelector: {kubernetes.io/hostname: talos-noy-0r4}
|
||||
imagePullSecrets:
|
||||
- name: ghcr-pull
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 10001
|
||||
runAsGroup: 10001
|
||||
seccompProfile: {type: RuntimeDefault}
|
||||
containers:
|
||||
- name: laya
|
||||
image: ghcr.io/fez5587/farmhouse-laya:v1
|
||||
ports:
|
||||
- {name: http, containerPort: 8080}
|
||||
env:
|
||||
- {name: LAYA_THREADS, value: "4"}
|
||||
- {name: LAYA_PORT, value: "8080"}
|
||||
# One checkpoint only (about 1.9 GB): the English base scored below the always-guess baseline against the LLM; typed-decisions is the
|
||||
# fine-tuned one still being measured.
|
||||
- {name: LAYA_MODELS, value: "typed-decisions"}
|
||||
- {name: LAYA_DEFAULT_MODEL, value: "typed-decisions"}
|
||||
- {name: LAYA_MAX_LOADED, value: "1"}
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
resources:
|
||||
requests: {cpu: "500m", memory: 2500Mi}
|
||||
limits: {cpu: "4", memory: 3Gi}
|
||||
# Loading two checkpoints takes a while; the port opens when the server is up.
|
||||
startupProbe:
|
||||
tcpSocket: {port: http}
|
||||
periodSeconds: 5
|
||||
failureThreshold: 90
|
||||
readinessProbe:
|
||||
tcpSocket: {port: http}
|
||||
periodSeconds: 10
|
||||
livenessProbe:
|
||||
tcpSocket: {port: http}
|
||||
periodSeconds: 30
|
||||
failureThreshold: 6
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: laya
|
||||
namespace: commander-lab
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector: {app: laya}
|
||||
ports:
|
||||
- {name: http, port: 8080, targetPort: http}
|
||||
---
|
||||
# IN: only the app. OUT: nothing at all (the weights are in the image; it needs no DNS and calls no one).
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: laya
|
||||
namespace: commander-lab
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels: {app: laya}
|
||||
policyTypes: [Ingress, Egress]
|
||||
ingress:
|
||||
- from:
|
||||
- podSelector:
|
||||
matchLabels: {app: commander-lab}
|
||||
ports:
|
||||
- {protocol: TCP, port: 8080}
|
||||
egress: []
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Turn the laya-shadow-v1 capture log into fine-tuning data for Laya (or Kev), plus the numbers a fine-tuned model must beat.
|
||||
|
||||
python scripts/farmhouse_laya_dataset.py [--in data/decisions] [--out data/laya-train] [--teacher llm|csie|selected]
|
||||
[--source all|farmhouse|forge] [--holdout 0.2] [--seed 193]
|
||||
|
||||
Reads every `laya-shadow-*.jsonl` (written when DECISION_MODE is shadow or assist: one line per call, with the text Laya read, the
|
||||
offered options, Laya's own zero-shot answer and the other deciders' picks), keeps the lines whose chosen teacher label is one of the
|
||||
offered options, drops exact duplicates, and splits BY GAME so no game appears on both sides (lines with no game id are split by
|
||||
the hash of their text, which is the same guarantee for identical states). Writes:
|
||||
|
||||
train.jsonl, valid.jsonl one /v1/systemone-shaped example per line: state, questions (with the offered options), answer, meta
|
||||
manifest.json counts, teacher, class balance, and the baselines on the VALIDATION side:
|
||||
- always the commonest action
|
||||
- CSIE's own pick vs the teacher (how much a fine-tuned model must add over the free heuristic)
|
||||
- Laya zero-shot vs the teacher (what was captured before any training)
|
||||
|
||||
Which teacher: `llm` (the slow model; the point is to make a fast student of it), `csie` (the deterministic heuristic; cheap and
|
||||
unlimited but a student can at best equal it), `selected` (what Forge executed). The labels are the teacher's choices, not proof they
|
||||
were right: a student trained on the LLM inherits its mistakes. Laya's own fine-tuning notebook/script (github.com/NandhaKishorM/laya,
|
||||
notebooks/) trains on this kind of typed-decision data; adapt the field names there if its loader differs.
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import glob
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_spec = importlib.util.spec_from_file_location("farmhouse_laya", os.path.join(HERE, "..", "src", "commander_ai_lab", "sim", "farmhouse_laya.py"))
|
||||
LAYA = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(LAYA)
|
||||
|
||||
|
||||
def read_records(directory):
|
||||
for path in sorted(glob.glob(os.path.join(directory, "laya-shadow-*.jsonl"))):
|
||||
for line in open(path, encoding="utf-8"):
|
||||
try:
|
||||
rec = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if rec.get("schema") == LAYA.CAPTURE_SCHEMA:
|
||||
yield rec
|
||||
|
||||
|
||||
def bucket(rec, seed):
|
||||
key = rec.get("game_id") or rec.get("state_text") or ""
|
||||
return int(hashlib.sha256(("%s|%s" % (seed, key)).encode("utf-8")).hexdigest()[:8], 16) / 0xFFFFFFFF
|
||||
|
||||
|
||||
def build(records, teacher="llm", source="all", holdout=0.2, seed=193):
|
||||
train, valid, seen = [], [], set()
|
||||
for rec in records:
|
||||
if source != "all" and rec.get("source") != source:
|
||||
continue
|
||||
row = LAYA.training_row(rec, teacher)
|
||||
if not row:
|
||||
continue
|
||||
key = (rec["state_text"], row["answer"]["action"], json.dumps(row["questions"]["action"]["criteria"], sort_keys=True))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
(valid if bucket(rec, seed) < holdout else train).append((row, rec))
|
||||
return train, valid
|
||||
|
||||
|
||||
def baselines(pairs, teacher):
|
||||
"""Agreement with the teacher on `pairs` of (row, record): commonest-action, CSIE, and Laya zero-shot."""
|
||||
n = len(pairs)
|
||||
if not n:
|
||||
return {"n": 0}
|
||||
targets = [r["answer"]["action"] for r, _ in pairs]
|
||||
common, k = collections.Counter(t.rsplit(":", 1)[-1] for t in targets).most_common(1)[0]
|
||||
out = {"n": n, "commonest_action": common, "commonest_agreement": round(k / n, 4)}
|
||||
csie = [(rec.get("labels") or {}).get("csie") for _, rec in pairs]
|
||||
if teacher != "csie":
|
||||
have = [(c, t) for c, t in zip(csie, targets) if c]
|
||||
if have:
|
||||
out["csie_vs_teacher"] = {"n": len(have), "agreement": round(sum(c == t for c, t in have) / len(have), 4)}
|
||||
laya = [((rec.get("laya") or {}).get("choice"), t) for (_, rec), t in zip(pairs, targets)]
|
||||
have = [(c, t) for c, t in laya if c]
|
||||
if have:
|
||||
out["laya_zero_shot_vs_teacher"] = {"n": len(have), "agreement": round(sum(c == t for c, t in have) / len(have), 4)}
|
||||
return out
|
||||
|
||||
|
||||
def write(out_dir, train, valid, teacher, source, holdout, seed):
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
for name, rows in (("train.jsonl", train), ("valid.jsonl", valid)):
|
||||
with open(os.path.join(out_dir, name), "w", encoding="utf-8", newline="\n") as f:
|
||||
for row, _ in rows:
|
||||
f.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
|
||||
balance = collections.Counter(r["answer"]["action"].rsplit(":", 1)[-1] for r, _ in train)
|
||||
manifest = {"schema": "laya-train-manifest-v1", "teacher": teacher, "source": source, "holdout": holdout, "seed": seed,
|
||||
"train": len(train), "valid": len(valid), "train_class_balance": dict(balance.most_common()),
|
||||
"validation_baselines": baselines(valid, teacher),
|
||||
"note": "Labels are the teacher's choices, not proof they were right. Split by game id (or text hash)."}
|
||||
with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(manifest, f, indent=2)
|
||||
return manifest
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
p.add_argument("--in", dest="inp", default=os.path.join("data", "decisions"))
|
||||
p.add_argument("--out", default=os.path.join("data", "laya-train"))
|
||||
p.add_argument("--teacher", choices=("llm", "csie", "selected"), default="llm")
|
||||
p.add_argument("--source", choices=("all", "farmhouse", "forge"), default="all")
|
||||
p.add_argument("--holdout", type=float, default=0.2)
|
||||
p.add_argument("--seed", type=int, default=193)
|
||||
a = p.parse_args(argv)
|
||||
train, valid = build(read_records(a.inp), a.teacher, a.source, a.holdout, a.seed)
|
||||
if not train and not valid:
|
||||
print("no usable records in %s for teacher %r (turn on DECISION_MODE=shadow and play some games first)" % (a.inp, a.teacher))
|
||||
return 1
|
||||
m = write(a.out, train, valid, a.teacher, a.source, a.holdout, a.seed)
|
||||
print(json.dumps(m, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,88 @@
|
||||
"""How well does a decision model classify a card's role from its Oracle text, zero-shot?
|
||||
|
||||
DECISION_URL=http://laya:8080 python scripts/farmhouse_laya_roles_eval.py [bulk_db] [per_role=25] [model]
|
||||
|
||||
Builds a sample from the local Scryfall bulk database using plain text patterns that give a card exactly ONE role (unambiguous cards
|
||||
only; many real cards have several roles, so this is a floor on how hard the task is, not a full test), classifies them in batches
|
||||
through farmhouse_laya.classify_roles, and prints accuracy, a confusion table and the time per card. Laya's output here would be
|
||||
evidence with provenance for ITI / Tagger-style role data, never a rules fact; this tells you whether that evidence is worth having.
|
||||
"""
|
||||
import collections
|
||||
import importlib.util
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
spec = importlib.util.spec_from_file_location("farmhouse_laya", os.path.join(HERE, "..", "src", "commander_ai_lab", "sim", "farmhouse_laya.py"))
|
||||
L = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(L)
|
||||
|
||||
PATTERNS = {
|
||||
"removal": re.compile(r"\b(destroy|exile) target (creature|permanent|nonland permanent|artifact|enchantment|planeswalker)", re.I),
|
||||
"board_wipe": re.compile(r"\b(destroy|exile) all (creatures|nonland permanents|permanents)|each creature (gets|is dealt)", re.I),
|
||||
"ramp": re.compile(r"search your library for (a|up to \w+) basic land|\badd \{[WUBRGC]\}", re.I),
|
||||
"card_draw": re.compile(r"\bdraw (a|two|three|\w+) cards?\b", re.I),
|
||||
"counterspell": re.compile(r"\bcounter target (spell|noncreature spell|creature spell|activated or triggered ability)", re.I),
|
||||
"tutor": re.compile(r"search your library for (a|an|up to \w+) (?!basic land)(card|creature|artifact|instant|sorcery|enchantment)", re.I),
|
||||
}
|
||||
|
||||
|
||||
def sample(db, per_role, seed=193):
|
||||
conn = sqlite3.connect(db)
|
||||
rows = conn.execute("SELECT name, type_line, oracle_text FROM cards WHERE oracle_text != '' AND type_line NOT LIKE '%Land%'").fetchall()
|
||||
random.Random(seed).shuffle(rows)
|
||||
out, taken, seen = [], collections.Counter(), set()
|
||||
for name, type_line, oracle in rows:
|
||||
if name in seen or len(oracle) > 700:
|
||||
continue
|
||||
hits = [r for r, p in PATTERNS.items() if p.search(oracle)]
|
||||
if len(hits) != 1 or taken[hits[0]] >= per_role:
|
||||
continue
|
||||
seen.add(name)
|
||||
taken[hits[0]] += 1
|
||||
out.append({"name": name, "type_line": type_line, "oracle": oracle, "truth": hits[0]})
|
||||
if all(taken[r] >= per_role for r in PATTERNS):
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
db = sys.argv[1] if len(sys.argv) > 1 else os.path.join("data", "scryfall_bulk.db")
|
||||
per_role = int(sys.argv[2]) if len(sys.argv) > 2 else 25
|
||||
if len(sys.argv) > 3:
|
||||
os.environ["DECISION_MODEL"] = sys.argv[3]
|
||||
if not os.environ.get("DECISION_URL"):
|
||||
print("set DECISION_URL")
|
||||
return 1
|
||||
cards = sample(db, per_role)
|
||||
t0 = time.time()
|
||||
got = L.classify_roles(cards)
|
||||
dt = time.time() - t0
|
||||
answered = [(c["truth"], got[c["name"]]["role"], got[c["name"]]["confidence"]) for c in cards if c["name"] in got]
|
||||
print("%d cards sampled (%s); %d classified in %.1f s (%.2f s per card)" % (
|
||||
len(cards), dict(collections.Counter(c["truth"] for c in cards)), len(answered), dt, dt / max(len(cards), 1)))
|
||||
if not answered:
|
||||
return 1
|
||||
ok = sum(t == p for t, p, _ in answered)
|
||||
print("accuracy %.1f%% (always-one-role baseline %.1f%%; there are %d roles to choose among)" % (
|
||||
100.0 * ok / len(answered), 100.0 / len(PATTERNS), len(L.ROLE_HELP)))
|
||||
for lo in (0.5, 0.7, 0.85):
|
||||
sel = [(t, p) for t, p, c in answered if c >= lo]
|
||||
if sel:
|
||||
print(" when >= %.2f sure: %d cards (%.0f%%), accuracy %.1f%%" % (lo, len(sel), 100.0 * len(sel) / len(answered),
|
||||
100.0 * sum(t == p for t, p in sel) / len(sel)))
|
||||
conf = collections.defaultdict(collections.Counter)
|
||||
for t, p, _ in answered:
|
||||
conf[t][p] += 1
|
||||
print("truth -> what it said:")
|
||||
for t in PATTERNS:
|
||||
print(" %-13s %s" % (t, dict(conf[t].most_common(4))))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -106,6 +106,11 @@ def ask(snap, actions=None):
|
||||
headers = {"content-type": "application/json"}
|
||||
if os.environ.get("DECISION_API_KEY"):
|
||||
headers["authorization"] = "Bearer " + os.environ["DECISION_API_KEY"]
|
||||
try: # extra questions ride in the same forward pass (farmhouse_laya.py); optional when the package is not importable
|
||||
from commander_ai_lab.sim import farmhouse_laya as _L
|
||||
body["questions"].update(_L._extra_questions())
|
||||
except ImportError:
|
||||
_L = None
|
||||
t0 = time.time()
|
||||
try:
|
||||
req = urllib.request.Request(url.rstrip("/") + "/v1/systemone", data=json.dumps(body).encode(), headers=headers)
|
||||
@@ -118,7 +123,10 @@ def ask(snap, actions=None):
|
||||
with _lock:
|
||||
_fail["n"] = 0
|
||||
return {"choice": choice, "confidence": float(probs.get(choice, ans.get("answer_confidence", 0.0))),
|
||||
"probabilities": probs, "ms": round((time.time() - t0) * 1000, 1), "model": model or "auto"}
|
||||
"probabilities": probs, "ms": round((time.time() - t0) * 1000, 1), "model": model or "auto",
|
||||
"extras": _L._extras(out["answers"]) if _L else {}, "state_text": body["state"]["body"],
|
||||
"options": {a: ACTION_HELP[a] for a in acts},
|
||||
"csie_selected": ((snap.get("strategic_advice") or {}).get("ranking") or {}).get("selected_id")}
|
||||
except Exception:
|
||||
with _lock:
|
||||
_fail["n"] += 1
|
||||
@@ -150,6 +158,13 @@ def record(answer, llm_action):
|
||||
row = STATS["by_action"].setdefault(llm_action, {"n": 0, "agreed": 0})
|
||||
row["n"] += 1
|
||||
row["agreed"] += 1 if agree else 0
|
||||
try: # one laya-shadow-v1 line per comparison: the raw material for fine-tuning (scripts/farmhouse_laya_dataset.py)
|
||||
from commander_ai_lab.sim import farmhouse_laya as _L
|
||||
_L.capture({"source": "farmhouse", "state_text": answer.get("state_text"), "options": answer.get("options"),
|
||||
"laya": {k: answer.get(k) for k in ("choice", "confidence", "probabilities", "extras", "ms", "model")},
|
||||
"labels": {"llm": llm_action, "csie": answer.get("csie_selected")}})
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
def stats():
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
"""Laya connections beyond "which macro action?" (the decision model also serves Kev: POST /v1/systemone).
|
||||
|
||||
Laya answers typed questions about a short text in ONE forward pass, so extra questions in the same request cost almost nothing. This
|
||||
module is where the repository uses that, without touching CSIE, ITI or PBIE:
|
||||
|
||||
advise_concrete / attach_concrete Forge's priority path. Laya picks among the SAME concrete candidate IDs Forge sent (never an
|
||||
ID it did not offer). shadow: recorded beside CSIE's pick. assist: may replace it when sure,
|
||||
but never when CSIE's pick carries a Forge-established `stops_immediate_win` or `wins_now`.
|
||||
extra questions "how dangerous are the opponents' boards?" and "is there a threat that must be answered?" ride
|
||||
in the same call and are recorded (a free weak signal for the learned-threat work).
|
||||
capture every shadow/assist call is appended to data/decisions/laya-shadow-<date>.jsonl as
|
||||
`laya-shadow-v1`: the text Laya read, the options, its answer, and the other deciders' picks.
|
||||
This is the raw material for fine-tuning (scripts/farmhouse_laya_dataset.py): Laya is a base to
|
||||
specialise, and zero-shot it is no better than guessing (farmhouse/laya/LAYA-EVALUATION.md).
|
||||
classify_roles card role evidence from Oracle text (batch, cached), with provenance, for ITI / Tagger-style use.
|
||||
|
||||
Hidden information: text is built from public facts and the ACTING player's own hand. An opponent's `hand` field is never read.
|
||||
Failures (no server, timeout, a bad answer) return None and never raise; three in a row pause asking for a minute.
|
||||
|
||||
Settings (shared with farmhouse_decide): DECISION_URL, DECISION_MODE (off|shadow|assist), DECISION_MODEL, DECISION_MIN_CONF,
|
||||
DECISION_TIMEOUT (5 s), DECISION_TIMEOUT_FORGE (1.5 s: Forge waits on this), DECISION_API_KEY, LAYA_CAPTURE_DIR, LAYA_CAPTURE=0 to disable.
|
||||
"""
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
CAPTURE_SCHEMA = "laya-shadow-v1"
|
||||
|
||||
THREAT_LEVELS = {
|
||||
"none": "no meaningful pressure on you",
|
||||
"low": "a small board that is not a danger yet",
|
||||
"moderate": "a board that will become dangerous if ignored",
|
||||
"high": "a board that threatens you within a turn or two",
|
||||
"lethal": "a board or stack that can kill you or win the game very soon",
|
||||
}
|
||||
|
||||
ROLE_HELP = {
|
||||
"removal": "destroys, exiles or otherwise removes one permanent or creature",
|
||||
"board_wipe": "destroys or removes many creatures or permanents at once",
|
||||
"ramp": "adds mana or fetches lands so you have more mana",
|
||||
"card_draw": "draws or otherwise gives you extra cards",
|
||||
"counterspell": "counters a spell or ability",
|
||||
"protection": "protects your permanents or players from removal or damage",
|
||||
"tutor": "searches your library for a card other than a basic land",
|
||||
"creature": "a creature whose main job is attacking, blocking or generating value on the battlefield",
|
||||
"other": "none of the above",
|
||||
}
|
||||
|
||||
_lock = threading.Lock()
|
||||
_fail = {"n": 0, "until": 0.0}
|
||||
_role_cache = {}
|
||||
_capture_lock = threading.Lock()
|
||||
|
||||
|
||||
def mode():
|
||||
m = os.environ.get("DECISION_MODE", "off").strip().lower()
|
||||
return m if m in ("shadow", "assist") and os.environ.get("DECISION_URL") else "off"
|
||||
|
||||
|
||||
def min_conf():
|
||||
try:
|
||||
return float(os.environ.get("DECISION_MIN_CONF", "0.7"))
|
||||
except ValueError:
|
||||
return 0.7
|
||||
|
||||
|
||||
def _post(path, body, timeout):
|
||||
"""JSON reply or None. Circuit breaker: three failures in a row pause for a minute."""
|
||||
url = os.environ.get("DECISION_URL")
|
||||
if not url:
|
||||
return None
|
||||
with _lock:
|
||||
if _fail["until"] > time.time():
|
||||
return None
|
||||
headers = {"content-type": "application/json"}
|
||||
if os.environ.get("DECISION_API_KEY"):
|
||||
headers["authorization"] = "Bearer " + os.environ["DECISION_API_KEY"]
|
||||
try:
|
||||
req = urllib.request.Request(url.rstrip("/") + path, data=json.dumps(body).encode(), headers=headers)
|
||||
out = json.load(urllib.request.urlopen(req, timeout=timeout))
|
||||
with _lock:
|
||||
_fail["n"] = 0
|
||||
return out
|
||||
except Exception:
|
||||
with _lock:
|
||||
_fail["n"] += 1
|
||||
if _fail["n"] >= 3:
|
||||
_fail["until"] = time.time() + 60
|
||||
_fail["n"] = 0
|
||||
return None
|
||||
|
||||
|
||||
def _extra_questions():
|
||||
return {"threat": {"type": "choice", "instructions": "How dangerous are the opponents' boards to you right now?",
|
||||
"criteria": dict(THREAT_LEVELS)},
|
||||
"must_answer": {"type": "noul", "instructions": "Is there an immediate threat that must be answered this turn?"}}
|
||||
|
||||
|
||||
def _extras(answers):
|
||||
out = {}
|
||||
t = (answers or {}).get("threat") or {}
|
||||
if t.get("choice") in THREAT_LEVELS:
|
||||
probs = t.get("probabilities") or {}
|
||||
out["threat"] = {"choice": t["choice"], "confidence": round(float(probs.get(t["choice"], 0.0)), 4)}
|
||||
m = (answers or {}).get("must_answer") or {}
|
||||
if "noul" in m:
|
||||
try:
|
||||
out["must_answer"] = round(float(m["noul"]), 4)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
# ---------- Forge's priority path -------------------------------------------------------------------------------------------
|
||||
|
||||
def _names(battlefield, limit=8):
|
||||
out = []
|
||||
for c in battlefield or []:
|
||||
out.append(str(c.get("name", "?")) if isinstance(c, dict) else str(c))
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def observation_text(obs, ranking=None):
|
||||
"""Public facts plus the acting player's own hand. An opponent's `hand` field is NEVER read."""
|
||||
actor = int(obs.get("priority_seat", 0))
|
||||
players = obs.get("players") or []
|
||||
parts = ["Phase %s, seat %s has priority (active seat %s)." % (obs.get("phase", "?"), actor, obs.get("active_seat", actor))]
|
||||
for p in players:
|
||||
seat = p.get("seat")
|
||||
head = "You (seat %s)" % seat if seat == actor else "Opponent seat %s" % seat
|
||||
bits = ["life %s" % p.get("life", "?"), "power on board %s" % p.get("total_power", 0)]
|
||||
if seat == actor:
|
||||
bits.append("mana available %s" % p.get("mana_available", "?"))
|
||||
hand = p.get("hand") # the actor's own hand only
|
||||
if isinstance(hand, list) and hand:
|
||||
bits.append("hand: " + ", ".join(_names(hand, 10)))
|
||||
else:
|
||||
bits.append("%s cards in hand" % p.get("cards_in_hand", "?"))
|
||||
else:
|
||||
bits.append("%s cards in hand" % p.get("cards_in_hand", p.get("hand_count", "?")))
|
||||
board = _names(p.get("battlefield"))
|
||||
bits.append("board: %s" % (", ".join(board) if board else "empty"))
|
||||
parts.append("%s: %s." % (head, "; ".join(bits)))
|
||||
stack = obs.get("stack") or []
|
||||
if stack:
|
||||
parts.append("Stack: %s." % "; ".join(
|
||||
"%s by seat %s%s" % (s.get("card", s.get("name", "a spell")), s.get("controller_seat", "?"),
|
||||
" (immediate win threat)" if s.get("immediate_win_threat") else "") for s in stack[:5]))
|
||||
else:
|
||||
parts.append("The stack is empty.")
|
||||
rows = (ranking or {}).get("ranked") or []
|
||||
if rows:
|
||||
parts.append("CSIE relative ranking: %s." % "; ".join(
|
||||
"%s %.2f" % (r["id"].rsplit(":", 1)[-1], r["score"]) for r in rows[:5]))
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def describe_candidate(c):
|
||||
"""What the candidate IS (kind, card, cost, tags). The opaque request-scoped ID is the key, never the description."""
|
||||
kind = str(c.get("kind", "other"))
|
||||
if kind == "pass":
|
||||
return "pass priority and do nothing"
|
||||
bits = [kind.replace("_", " ")]
|
||||
name = c.get("card_name") or c.get("card") or c.get("name")
|
||||
if name:
|
||||
bits.append(str(name))
|
||||
if c.get("mana_value") not in (None, ""):
|
||||
bits.append("mana value %s" % c["mana_value"])
|
||||
if c.get("target_seat") is not None:
|
||||
bits.append("targeting seat %s" % c["target_seat"])
|
||||
tags = [str(t) for t in (c.get("tags") or [])]
|
||||
if tags:
|
||||
bits.append("tags " + ", ".join(tags))
|
||||
return ", ".join(bits)
|
||||
|
||||
|
||||
def advise_concrete(observation, candidates, ranking=None):
|
||||
"""Laya's pick among Forge's concrete candidate IDs, or None. Shape: choice, confidence, probabilities, extras, ms, model, state_text, options."""
|
||||
ids = [c.get("id") for c in candidates if isinstance(c.get("id"), str)]
|
||||
if not ids or len(ids) != len(set(ids)) or mode() == "off":
|
||||
return None
|
||||
text = observation_text(observation, ranking)
|
||||
options = {c["id"]: describe_candidate(c) for c in candidates if isinstance(c.get("id"), str)}
|
||||
questions = {"action": {"type": "choice", "instructions": "Which action is best right now?", "criteria": options}}
|
||||
questions.update(_extra_questions())
|
||||
body = {"state": {"body": text}, "questions": questions}
|
||||
if os.environ.get("DECISION_MODEL"):
|
||||
body["model"] = os.environ["DECISION_MODEL"]
|
||||
t0 = time.time()
|
||||
out = _post("/v1/systemone", body, float(os.environ.get("DECISION_TIMEOUT_FORGE", "1.5")))
|
||||
try:
|
||||
ans = out["answers"]["action"]
|
||||
choice, probs = ans["choice"], ans.get("probabilities") or {}
|
||||
if choice not in options:
|
||||
return None
|
||||
return {"choice": choice, "confidence": float(probs.get(choice, ans.get("answer_confidence", 0.0))),
|
||||
"probabilities": probs, "extras": _extras(out["answers"]), "ms": round((time.time() - t0) * 1000, 1),
|
||||
"model": os.environ.get("DECISION_MODEL") or "auto", "state_text": text, "options": options}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def attach_concrete(result, observation, candidates, advice):
|
||||
"""Add Laya's view to the concrete-decision response; in assist mode it may replace the selection (guarded).
|
||||
|
||||
result is the dict /api/policy/decide/concrete returns ({"selected_id", "ranked", ...}). Forge executes only an ID it sent."""
|
||||
if not advice:
|
||||
return result
|
||||
by_id = {c.get("id"): c for c in candidates}
|
||||
csie_pick = result.get("selected_id")
|
||||
view = {k: advice[k] for k in ("choice", "confidence", "probabilities", "extras", "ms", "model")}
|
||||
view["agrees_with_selected"] = advice["choice"] == csie_pick
|
||||
out = dict(result)
|
||||
out["laya"] = view
|
||||
protected = bool(set((by_id.get(csie_pick) or {}).get("tags") or []) & {"stops_immediate_win", "wins_now"})
|
||||
if (mode() == "assist" and advice["choice"] in by_id and advice["choice"] != csie_pick
|
||||
and advice["confidence"] >= min_conf() and not protected):
|
||||
out["csie_selected_id"] = csie_pick
|
||||
out["selected_id"] = advice["choice"]
|
||||
out["laya_override"] = True
|
||||
capture({"source": "forge", "state_text": advice["state_text"], "options": advice["options"],
|
||||
"laya": view, "labels": {"csie": csie_pick, "selected": out["selected_id"]},
|
||||
"game_id": (observation or {}).get("game_id")})
|
||||
return out
|
||||
|
||||
|
||||
# ---------- recording (also the fine-tuning raw material) --------------------------------------------------------------------
|
||||
|
||||
def capture(record):
|
||||
"""Append one laya-shadow-v1 record. Never raises."""
|
||||
if os.environ.get("LAYA_CAPTURE", "1") == "0" or mode() == "off":
|
||||
return
|
||||
try:
|
||||
d = os.environ.get("LAYA_CAPTURE_DIR", os.path.join("data", "decisions"))
|
||||
os.makedirs(d, exist_ok=True)
|
||||
rec = dict(record, schema=CAPTURE_SCHEMA, ts=round(time.time(), 3), mode=mode())
|
||||
path = os.path.join(d, "laya-shadow-%s.jsonl" % datetime.datetime.utcnow().strftime("%Y%m%d"))
|
||||
with _capture_lock, open(path, "a", encoding="utf-8", newline="\n") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False, separators=(",", ":")) + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ---------- card role evidence ------------------------------------------------------------------------------------------------
|
||||
|
||||
def classify_roles(cards, batch_size=32):
|
||||
"""{name: {"role", "confidence", "probabilities", "source"}} for cards given as {"name", "oracle", "type_line"}.
|
||||
|
||||
One batched request per `batch_size` unseen cards (the server shares forward passes), cached by name. This is evidence with
|
||||
provenance (source says model and mode), never a rules fact; a card the server cannot classify is simply absent."""
|
||||
out, todo = {}, []
|
||||
for c in cards:
|
||||
n = c.get("name")
|
||||
if not n:
|
||||
continue
|
||||
if n in _role_cache:
|
||||
out[n] = _role_cache[n]
|
||||
elif all(n != t["name"] for t in todo):
|
||||
todo.append(c)
|
||||
questions = {"role": {"type": "choice", "instructions": "What is this card's main role in a Commander deck?", "criteria": dict(ROLE_HELP)}}
|
||||
model = os.environ.get("DECISION_MODEL") or "auto"
|
||||
for i in range(0, len(todo), batch_size):
|
||||
chunk = todo[i:i + batch_size]
|
||||
body = {"states": [{"body": ("%s. %s. %s" % (c["name"], c.get("type_line", ""), c.get("oracle", "")))[:1500]} for c in chunk],
|
||||
"questions": questions}
|
||||
if os.environ.get("DECISION_MODEL"):
|
||||
body["model"] = os.environ["DECISION_MODEL"]
|
||||
res = _post("/v1/systemone/batch", body, float(os.environ.get("DECISION_TIMEOUT", "5")) * max(2, len(chunk) // 4))
|
||||
results = (res or {}).get("results") or []
|
||||
for c, r in zip(chunk, results):
|
||||
try:
|
||||
a = r["answers"]["role"]
|
||||
probs = a.get("probabilities") or {}
|
||||
if a["choice"] not in ROLE_HELP:
|
||||
continue
|
||||
row = {"role": a["choice"], "confidence": round(float(probs.get(a["choice"], 0.0)), 4), "probabilities": probs,
|
||||
"source": "laya:%s" % model}
|
||||
_role_cache[c["name"]] = out[c["name"]] = row
|
||||
except Exception:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
# ---------- fine-tuning rows --------------------------------------------------------------------------------------------------
|
||||
|
||||
def training_row(rec, label="llm"):
|
||||
"""One /v1/systemone-shaped training example from a laya-shadow-v1 record, or None when it has no usable label.
|
||||
|
||||
label: which decider is the teacher: llm, csie, selected. The row carries provenance so a student trained on one teacher can be
|
||||
told apart from one trained on another, and the options (not just the winner) so the model learns to choose among them."""
|
||||
labels = rec.get("labels") or {}
|
||||
target = labels.get(label)
|
||||
options = rec.get("options") or {}
|
||||
if not rec.get("state_text") or target not in options:
|
||||
return None
|
||||
return {"state": {"body": rec["state_text"]},
|
||||
"questions": {"action": {"type": "choice", "instructions": "Which action is best right now?", "criteria": options}},
|
||||
"answer": {"action": target},
|
||||
"meta": {"schema": "laya-train-v1", "source": rec.get("source"), "teacher": label, "game_id": rec.get("game_id"),
|
||||
"laya_choice": (rec.get("laya") or {}).get("choice"), "ts": rec.get("ts")}}
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Run: python -I -X utf8 tests/farmhouse/test_farmhouse_laya.py (offline: a stub /v1/systemone server on localhost)
|
||||
|
||||
Loads the two modules by file path and registers them under a stub `commander_ai_lab.sim` package, so no upstream package code runs."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _load import load # noqa: E402
|
||||
|
||||
L = load("farmhouse_laya", "src/commander_ai_lab/sim/farmhouse_laya.py")
|
||||
pkg, sim = types.ModuleType("commander_ai_lab"), types.ModuleType("commander_ai_lab.sim")
|
||||
pkg.sim, sim.farmhouse_laya = sim, L
|
||||
sys.modules.update({"commander_ai_lab": pkg, "commander_ai_lab.sim": sim, "commander_ai_lab.sim.farmhouse_laya": L})
|
||||
D = load("farmhouse_decide", "src/commander_ai_lab/sim/farmhouse_decide.py")
|
||||
|
||||
FAILS = 0
|
||||
|
||||
|
||||
def ck(name, cond, detail=""):
|
||||
global FAILS
|
||||
print(" %s %s%s" % ("ok " if cond else "FAIL", name, (" -- " + str(detail)[:240]) if detail and not cond else ""))
|
||||
if not cond:
|
||||
FAILS += 1
|
||||
|
||||
|
||||
SEEN = []
|
||||
B = {"pick": None, "conf": 0.9, "delay": 0.0, "bogus": False}
|
||||
|
||||
|
||||
class Stub(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _answer(self, qs):
|
||||
ans = {}
|
||||
for name, q in qs.items():
|
||||
crit = list(q.get("criteria") or [])
|
||||
if q["type"] == "choice":
|
||||
pick = B["pick"] if B["pick"] in crit else crit[0]
|
||||
if B["bogus"] and name == "action":
|
||||
pick = "not_offered"
|
||||
probs = {k: (B["conf"] if k == pick else (1 - B["conf"]) / max(len(crit) - 1, 1)) for k in crit}
|
||||
ans[name] = {"type": "choice", "choice": pick, "probabilities": probs}
|
||||
else:
|
||||
ans[name] = {"type": "noul", "noul": 0.25}
|
||||
return ans
|
||||
|
||||
def do_POST(self):
|
||||
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
|
||||
SEEN.append((self.path, body))
|
||||
time.sleep(B["delay"])
|
||||
if self.path.endswith("/batch"):
|
||||
out = {"results": [{"answers": self._answer(body["questions"])} for _ in body["states"]]}
|
||||
else:
|
||||
out = {"answers": self._answer(body["questions"])}
|
||||
data = json.dumps(out).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/json")
|
||||
self.send_header("content-length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
srv = HTTPServer(("127.0.0.1", 0), Stub)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
os.environ["DECISION_URL"] = "http://127.0.0.1:%d" % srv.server_port
|
||||
CAP = tempfile.mkdtemp()
|
||||
os.environ["LAYA_CAPTURE_DIR"] = CAP
|
||||
|
||||
|
||||
def captured():
|
||||
rows = []
|
||||
for f in sorted(os.listdir(CAP)):
|
||||
rows += [json.loads(l) for l in open(os.path.join(CAP, f), encoding="utf-8")]
|
||||
return rows
|
||||
|
||||
|
||||
OBS = {"priority_seat": 0, "active_seat": 1, "phase": "MAIN1", "stack": [{"controller_seat": 1, "card": "Doomsday", "immediate_win_threat": True}],
|
||||
"players": [{"seat": 0, "life": 20, "mana_available": 5, "total_power": 3, "cards_in_hand": 2, "hand": ["Counterspell", "Island"],
|
||||
"battlefield": ["Llanowar Elves"]},
|
||||
{"seat": 1, "life": 40, "total_power": 9, "cards_in_hand": 4, "hand": ["SECRET OPPONENT CARD"], "battlefield": ["Wurm"]}]}
|
||||
CANDS = [{"id": "d1:0", "kind": "counter", "card_name": "Counterspell", "mana_value": 2, "tags": ["counter", "stops_immediate_win"]},
|
||||
{"id": "d1:1", "kind": "land", "mana_value": 0},
|
||||
{"id": "d1:pass", "kind": "pass", "mana_value": 0}]
|
||||
RANK = {"selected_id": "d1:0", "ranked": [{"id": "d1:0", "score": 9.1}, {"id": "d1:pass", "score": 0.2}]}
|
||||
|
||||
# --- text and hidden information
|
||||
t = L.observation_text(OBS, RANK)
|
||||
ck("the opponent's hand names are never in the text", "SECRET" not in t, t)
|
||||
ck("your own hand is", "Counterspell" in t and "Island" in t)
|
||||
ck("public facts, the stack and the ranking are", all(x in t for x in ("Wurm", "Doomsday", "immediate win threat", "d1:0".rsplit(":", 1)[-1])), t)
|
||||
ck("opponent hand COUNT is", "4 cards in hand" in t)
|
||||
ck("a candidate is described by what it is, not its opaque id", "d1" not in L.describe_candidate(CANDS[0]) and "Counterspell" in L.describe_candidate(CANDS[0]))
|
||||
ck("pass is described", "pass" in L.describe_candidate(CANDS[2]))
|
||||
|
||||
# --- modes
|
||||
for k in ("DECISION_MODE", "DECISION_MODEL", "DECISION_API_KEY"):
|
||||
os.environ.pop(k, None)
|
||||
ck("no mode: nothing asked", L.advise_concrete(OBS, CANDS, RANK) is None and not SEEN)
|
||||
os.environ["DECISION_MODE"] = "shadow"
|
||||
B.update(pick="d1:1", conf=0.9)
|
||||
adv = L.advise_concrete(OBS, CANDS, RANK)
|
||||
path, body = SEEN[-1]
|
||||
ck("one request, the action question plus the two extras, criteria keyed by the offered ids",
|
||||
path == "/v1/systemone" and set(body["questions"]) == {"action", "threat", "must_answer"}
|
||||
and list(body["questions"]["action"]["criteria"]) == ["d1:0", "d1:1", "d1:pass"], body["questions"].keys())
|
||||
ck("the answer, its extras, and the text it read", adv and adv["choice"] == "d1:1" and abs(adv["confidence"] - 0.9) < 1e-9
|
||||
and adv["extras"]["must_answer"] == 0.25 and adv["extras"]["threat"]["choice"] in L.THREAT_LEVELS and adv["state_text"] == t, adv)
|
||||
|
||||
# --- shadow never changes the selection
|
||||
res = L.attach_concrete(dict(RANK), OBS, CANDS, adv)
|
||||
ck("shadow: selection untouched, Laya's view attached", res["selected_id"] == "d1:0" and res["laya"]["choice"] == "d1:1"
|
||||
and res["laya"]["agrees_with_selected"] is False and "laya_override" not in res, res)
|
||||
rows = captured()
|
||||
ck("and a laya-shadow-v1 record was written with both labels", rows and rows[-1]["schema"] == "laya-shadow-v1"
|
||||
and rows[-1]["labels"] == {"csie": "d1:0", "selected": "d1:0"} and "SECRET" not in json.dumps(rows[-1]), rows[-1:] )
|
||||
|
||||
# --- assist
|
||||
os.environ["DECISION_MODE"] = "assist"
|
||||
res = L.attach_concrete(dict(RANK), OBS, CANDS, adv)
|
||||
ck("assist does NOT override a pick Forge tagged stops_immediate_win", res["selected_id"] == "d1:0" and "laya_override" not in res, res)
|
||||
free = [dict(CANDS[0], tags=["counter"]), CANDS[1], CANDS[2]]
|
||||
res = L.attach_concrete(dict(RANK), OBS, free, adv)
|
||||
ck("assist overrides an unprotected pick when sure, keeping what CSIE chose", res["selected_id"] == "d1:1" and res["csie_selected_id"] == "d1:0"
|
||||
and res["laya_override"] is True, res)
|
||||
B["conf"] = 0.4
|
||||
low = L.advise_concrete(OBS, free, RANK)
|
||||
res = L.attach_concrete(dict(RANK), OBS, free, low)
|
||||
ck("assist ignores a pick below DECISION_MIN_CONF", res["selected_id"] == "d1:0" and "laya_override" not in res, res)
|
||||
B["conf"] = 0.9
|
||||
B["bogus"] = True
|
||||
ck("an answer outside the offered ids is discarded", L.advise_concrete(OBS, free, RANK) is None)
|
||||
B["bogus"] = False
|
||||
same = dict(RANK)
|
||||
B["pick"] = "d1:0"
|
||||
res = L.attach_concrete(dict(same), OBS, free, L.advise_concrete(OBS, free, RANK))
|
||||
ck("agreement is reported", res["laya"]["agrees_with_selected"] is True and res["selected_id"] == "d1:0")
|
||||
ck("no advice: the result is returned as it was", L.attach_concrete(dict(RANK), OBS, CANDS, None) == RANK)
|
||||
ck("duplicate candidate ids are refused", L.advise_concrete(OBS, [CANDS[0], CANDS[0]], RANK) is None)
|
||||
|
||||
# --- slow server: Forge must not wait
|
||||
os.environ["DECISION_TIMEOUT_FORGE"] = "0.2"
|
||||
B["delay"] = 0.8
|
||||
t0 = time.time()
|
||||
ck("a slow server gives None within the Forge timeout", L.advise_concrete(OBS, CANDS, RANK) is None and time.time() - t0 < 0.7)
|
||||
B["delay"] = 0.0
|
||||
L._fail.update(n=0, until=0.0)
|
||||
|
||||
# --- capture switches
|
||||
n = len(captured())
|
||||
os.environ["LAYA_CAPTURE"] = "0"
|
||||
L.attach_concrete(dict(RANK), OBS, CANDS, adv)
|
||||
ck("LAYA_CAPTURE=0 writes nothing", len(captured()) == n)
|
||||
os.environ.pop("LAYA_CAPTURE")
|
||||
|
||||
# --- Farmhouse path through the existing client
|
||||
os.environ["DECISION_MODE"] = "shadow"
|
||||
B["pick"] = "cast_creature"
|
||||
snap = {"turn": 4, "my_life": 31, "opp_life": 20, "my_mana_total": 4, "my_hand": [{"name": "Forest", "type": "land"}],
|
||||
"strategic_advice": {"ranking": {"selected_id": "hold", "ranked": [{"id": "hold", "score": 1.0, "explanation": "x"}]}}}
|
||||
ans = D.ask(snap, actions=["play_land", "cast_creature", "hold"])
|
||||
sent = SEEN[-1][1]["questions"]
|
||||
ck("ask() sends the extras in the same request and returns them with the text and options",
|
||||
set(sent) == {"action", "threat", "must_answer"} and ans["extras"]["must_answer"] == 0.25 and ans["state_text"] and
|
||||
set(ans["options"]) == {"play_land", "cast_creature", "hold"} and ans["csie_selected"] == "hold", ans)
|
||||
n = len(captured())
|
||||
D.record(ans, "hold")
|
||||
last = captured()[-1]
|
||||
ck("record() writes the shadow record with the LLM and CSIE labels", len(captured()) == n + 1 and last["source"] == "farmhouse"
|
||||
and last["labels"] == {"llm": "hold", "csie": "hold"} and last["laya"]["choice"] == "cast_creature", last)
|
||||
|
||||
# --- fine-tuning rows
|
||||
row = L.training_row(last, "llm")
|
||||
ck("a training row is /v1/systemone-shaped with the options and the teacher's answer",
|
||||
row and row["answer"] == {"action": "hold"} and row["questions"]["action"]["criteria"] == last["options"]
|
||||
and row["meta"]["teacher"] == "llm" and row["state"]["body"] == last["state_text"], row)
|
||||
ck("a label that is not an offered option yields no row", L.training_row(dict(last, labels={"llm": "nonsense"}), "llm") is None
|
||||
and L.training_row(last, "selected") is None)
|
||||
|
||||
# --- roles: batched and cached
|
||||
L._role_cache.clear()
|
||||
B["pick"] = "removal"
|
||||
n_req = len(SEEN)
|
||||
cards = [{"name": "Swords to Plowshares", "type_line": "Instant", "oracle": "Exile target creature."},
|
||||
{"name": "Rampant Growth", "type_line": "Sorcery", "oracle": "Search for a basic land."}]
|
||||
roles = L.classify_roles(cards)
|
||||
req = SEEN[-1]
|
||||
ck("two unseen cards = ONE batch request with both states", len(SEEN) == n_req + 1 and req[0] == "/v1/systemone/batch" and len(req[1]["states"]) == 2)
|
||||
ck("the roles carry provenance", roles["Swords to Plowshares"]["role"] == "removal" and roles["Swords to Plowshares"]["source"].startswith("laya:"), roles)
|
||||
L.classify_roles(cards)
|
||||
ck("a second call is served from the cache", len(SEEN) == n_req + 1)
|
||||
print("\nFAILURES: %d" % FAILS)
|
||||
sys.exit(1 if FAILS else 0)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Run: python -I -X utf8 tests/farmhouse/test_farmhouse_laya_dataset.py (offline, temp directories only)"""
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _load import ROOT # noqa: E402
|
||||
|
||||
spec = importlib.util.spec_from_file_location("ds", os.path.join(ROOT, "scripts", "farmhouse_laya_dataset.py"))
|
||||
DS = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(DS)
|
||||
FAILS = 0
|
||||
|
||||
|
||||
def ck(name, cond, detail=""):
|
||||
global FAILS
|
||||
print(" %s %s%s" % ("ok " if cond else "FAIL", name, (" -- " + str(detail)[:240]) if detail and not cond else ""))
|
||||
if not cond:
|
||||
FAILS += 1
|
||||
|
||||
|
||||
OPTS = {"play_land": "land", "cast_creature": "creature", "hold": "pass"}
|
||||
|
||||
|
||||
def rec(i, game, llm, csie, laya, source="farmhouse", text=None):
|
||||
return {"schema": "laya-shadow-v1", "ts": 1.0 + i, "source": source, "game_id": game, "state_text": text or "state %d" % i,
|
||||
"options": OPTS, "laya": {"choice": laya}, "labels": {"llm": llm, "csie": csie}}
|
||||
|
||||
|
||||
recs = []
|
||||
for g in range(40): # 40 games x 5 decisions
|
||||
for k in range(5):
|
||||
i = g * 5 + k
|
||||
llm = ["play_land", "cast_creature", "hold", "cast_creature", "hold"][k]
|
||||
recs.append(rec(i, "g%d" % g, llm, "hold" if k % 2 else llm, "cast_creature"))
|
||||
recs.append(rec(900, "g0", "hold", "hold", "hold", text="state 0")) # same text+label as an existing one? different label -> kept
|
||||
recs.append(rec(901, "g1", "hold", "hold", "hold", text="state 5"))
|
||||
recs.append(dict(rec(902, "g2", "NOT_AN_OPTION", "hold", "hold"))) # label outside the options -> dropped
|
||||
recs.append(dict(rec(903, "g3", "hold", "hold", "hold"), schema="something-else")) # wrong schema -> ignored by the reader
|
||||
recs.append(rec(904, "g4", "hold", "hold", "hold", source="forge"))
|
||||
|
||||
d = tempfile.mkdtemp()
|
||||
with open(os.path.join(d, "laya-shadow-20261026.jsonl"), "w", encoding="utf-8") as f:
|
||||
for r in recs:
|
||||
f.write(json.dumps(r) + "\n")
|
||||
f.write("not json at all\n")
|
||||
back = list(DS.read_records(d))
|
||||
ck("the reader keeps only laya-shadow-v1 lines and skips junk", len(back) == len(recs) - 1, len(back))
|
||||
|
||||
train, valid = DS.build(back, "llm", "all", 0.25, 193)
|
||||
ck("rows outside the options are dropped, everything else becomes a row", len(train) + len(valid) == len(recs) - 2 - 0, (len(train), len(valid)))
|
||||
tg = {r["meta"]["game_id"] for r, _ in train}
|
||||
vg = {r["meta"]["game_id"] for r, _ in valid}
|
||||
ck("no game is on both sides of the split", not (tg & vg) and tg and vg, (len(tg), len(vg)))
|
||||
t2, v2 = DS.build(back, "llm", "all", 0.25, 193)
|
||||
ck("the split is reproducible", [r["meta"]["ts"] for r, _ in valid] == [r["meta"]["ts"] for r, _ in v2])
|
||||
ck("a different seed moves games", {r["meta"]["game_id"] for r, _ in DS.build(back, "llm", "all", 0.25, 7)[1]} != vg)
|
||||
only_forge_t, only_forge_v = DS.build(back, "llm", "forge", 0.25, 193)
|
||||
ck("--source filters", len(only_forge_t) + len(only_forge_v) == 1)
|
||||
dup = DS.build(back + [rec(1, "g0", "play_land", "play_land", "hold", text="state 0")], "llm", "all", 0.25, 193)
|
||||
ck("an exact duplicate (same text, label and options) is dropped", len(dup[0]) + len(dup[1]) == len(train) + len(valid))
|
||||
|
||||
row = train[0][0]
|
||||
ck("a row is /v1/systemone-shaped with options, the answer and provenance", set(row) == {"state", "questions", "answer", "meta"}
|
||||
and row["questions"]["action"]["criteria"] == OPTS and row["meta"]["teacher"] == "llm" and row["meta"]["schema"] == "laya-train-v1")
|
||||
|
||||
b = DS.baselines(valid, "llm")
|
||||
ck("baselines report the commonest action, CSIE and Laya zero-shot against the teacher",
|
||||
b["n"] == len(valid) and 0 < b["commonest_agreement"] <= 1 and b["csie_vs_teacher"]["n"] == len(valid)
|
||||
and "laya_zero_shot_vs_teacher" in b, b)
|
||||
ck("CSIE as the teacher has no csie-vs-teacher line", "csie_vs_teacher" not in DS.baselines(DS.build(back, "csie", "all", .25, 193)[1], "csie"))
|
||||
|
||||
out = os.path.join(d, "out")
|
||||
m = DS.write(out, train, valid, "llm", "all", 0.25, 193)
|
||||
files = sorted(os.listdir(out))
|
||||
lines = sum(1 for _ in open(os.path.join(out, "train.jsonl"), encoding="utf-8"))
|
||||
ck("train, valid and the manifest are written", files == ["manifest.json", "train.jsonl", "valid.jsonl"] and lines == len(train)
|
||||
and m["train"] == len(train) and m["valid"] == len(valid) and "validation_baselines" in m, files)
|
||||
ck("main() on an empty directory says so and fails", DS.main(["--in", tempfile.mkdtemp(), "--out", out]) == 1)
|
||||
ck("main() on the log succeeds", DS.main(["--in", d, "--out", os.path.join(d, "o2"), "--teacher", "csie"]) == 0)
|
||||
print("\nFAILURES: %d" % FAILS)
|
||||
sys.exit(1 if FAILS else 0)
|
||||
Reference in new issue
Block a user