mirror of
https://github.com/velocitatem/PHANTOM.git
synced 2026-07-15 17:43:36 +00:00
Compare commits
86 Commits
baseline-c
...
adf760162d
| Author | SHA1 | Date | |
|---|---|---|---|
| adf760162d | |||
|
|
d8907eb353 | ||
| d36a34ead9 | |||
| 03b4996bea | |||
| b69c3a87fd | |||
| 6427ae63ec | |||
| 5460f34426 | |||
| ece06a5a50 | |||
| f027ac1736 | |||
| 0fd1459011 | |||
| a3dc5125df | |||
| 3eea137f49 | |||
| 51de0cbdc5 | |||
| 895a004807 | |||
| 0ff0c0432c | |||
| 2ba5d6d6af | |||
| c0c375548c | |||
| e694d38bce | |||
| d5d8ea5870 | |||
| 840f80db39 | |||
| 8dac0905fc | |||
| 835e10d6ef | |||
| 02328b20f2 | |||
| eebd44db28 | |||
| ace52e8e14 | |||
| 47b07daa6c | |||
| 7e3bcf2520 | |||
| 97902f39a3 | |||
| 86c06176ae | |||
| 97a6bf3974 | |||
| e72e3c81c1 | |||
| cc823ec63c | |||
| 392f9b1549 | |||
| b287642ed0 | |||
| 5f0d3f4118 | |||
| e18a3e7363 | |||
| 291472295b | |||
| eab9203111 | |||
| 59b2b46f6e | |||
|
|
473342f103 | ||
| e77f037d62 | |||
| 9c464eaf3b | |||
| 58042ba4f2 | |||
| 18b41ff802 | |||
| 105b014976 | |||
| 220b6ce8c1 | |||
| 910dba0a7d | |||
| e62e842faa | |||
| 661a80b655 | |||
|
|
128911decc | ||
| ae2860a0ee | |||
| c87b800793 | |||
| 810d823710 | |||
| 8706072966 | |||
| f70c51f223 | |||
| 8aa4db1c9e | |||
| ee26954fae | |||
| fb09ea2b68 | |||
| 3439775fbd | |||
| 43b952cf2b | |||
| 2adb4f07b4 | |||
| e867c4d883 | |||
| a3e2a337ed | |||
| 63f1aad0b9 | |||
| 253364acae | |||
| 9642edd1b1 | |||
| c8df2e9cbd | |||
| 1393795359 | |||
| 375445f260 | |||
| 0521a63937 | |||
| a9c091050c | |||
| 52b4dcdce3 | |||
| 19b47aa699 | |||
| 88155d22a7 | |||
| b1f583be39 | |||
| 22e50aac4a | |||
| d748733231 | |||
| 9caad4de4e | |||
| 745792683e | |||
| 631b6d698c | |||
| d3a4febfde | |||
| fa2dde8307 | |||
| 0f708aab15 | |||
| 974498dab2 | |||
| 6d9613c0b6 | |||
|
|
ae6cffe825 |
10
.github/workflows/latex.yml
vendored
10
.github/workflows/latex.yml
vendored
@@ -9,6 +9,12 @@ on:
|
||||
paths:
|
||||
- 'paper/**'
|
||||
- '.github/**'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
skip_mirrors:
|
||||
description: Skip Codex mirror generation (avoids API quota use)
|
||||
type: boolean
|
||||
default: false
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -24,8 +30,10 @@ jobs:
|
||||
- name: Prepare appendix code snapshot
|
||||
run: bash paper/concat_code.sh
|
||||
|
||||
# Repo variable SKIP_CODEX_MIRRORS=true skips on push/PR; workflow_dispatch can set skip_mirrors.
|
||||
- name: Generate mirrors with Codex
|
||||
if: ${{ env.OPENAI_API_KEY != '' }}
|
||||
if: ${{ env.OPENAI_API_KEY != '' && vars.SKIP_CODEX_MIRRORS != 'true' && (github.event_name != 'workflow_dispatch' || github.event.inputs.skip_mirrors != 'true') }}
|
||||
continue-on-error: true
|
||||
uses: openai/codex-action@v1
|
||||
with:
|
||||
openai-api-key: ${{ env.OPENAI_API_KEY }}
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -3,6 +3,7 @@
|
||||
.env.*
|
||||
!.env.*.example
|
||||
**/.venv
|
||||
**/.venv-ray
|
||||
|
||||
# python build/cache artifacts
|
||||
**/__pycache__
|
||||
@@ -33,6 +34,9 @@ dist/
|
||||
**/*.parquet
|
||||
**/_build/
|
||||
|
||||
# mkdocs output (run make docs.platform locally or rely on CI)
|
||||
docs/documentation/
|
||||
|
||||
# paper build artifacts
|
||||
paper/src/bib/auto
|
||||
paper/src/auto/*
|
||||
|
||||
35
.rayignore
Normal file
35
.rayignore
Normal file
@@ -0,0 +1,35 @@
|
||||
# Virtual environments
|
||||
.venv
|
||||
.venv*
|
||||
venv
|
||||
venv*
|
||||
**/.venv
|
||||
**/venv
|
||||
**/node_modules
|
||||
node_modules/
|
||||
|
||||
# Python caches
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.ruff_cache/
|
||||
.pytest_cache/
|
||||
|
||||
# Git
|
||||
.git/
|
||||
|
||||
# Large data and logs
|
||||
data/
|
||||
experiments/
|
||||
wandb/
|
||||
dumplogs*
|
||||
*.zip
|
||||
*.pdf
|
||||
*.log
|
||||
*.dot
|
||||
|
||||
# Other large dirs
|
||||
PHANTOM_web/
|
||||
web/
|
||||
docs/
|
||||
paper/
|
||||
.nx/
|
||||
99
Makefile
99
Makefile
@@ -11,6 +11,7 @@ PYTEST := $(VENV)/bin/pytest
|
||||
NX := npx nx
|
||||
|
||||
SWEEP_ENV_FILE ?= .env.sweep
|
||||
TPU_CONF ?= tpu_orchestration/configs/v4_spot_us.conf
|
||||
|
||||
WANDB_ENTITY ?=
|
||||
WANDB_PROJECT ?= capstone
|
||||
@@ -21,6 +22,14 @@ SIMPLE_BENCHMARK_ARGS ?= --tiers qtable,ppo,dqn,a2c --alpha-values 0.0,0.15,0.3,
|
||||
BENCHMARK_AGENT_ARGS ?=
|
||||
AGENT_COUNT ?= 0
|
||||
|
||||
WHOCLICKED_REPO ?= velocitatem/whoclickedit
|
||||
WHOCLICKED_CSV ?= experiments/exports/whoclicked.csv
|
||||
WHOCLICKED_CARD ?= experiments/exports/whoclicked_dataset_card.md
|
||||
WHOCLICKED_CSV_PATH_IN_REPO ?= whoclicked.csv
|
||||
WHOCLICKED_CARD_PATH_IN_REPO ?= README.md
|
||||
WHOCLICKED_DATASET_MESSAGE ?= Update flattened whoclickedit dataset
|
||||
WHOCLICKED_CARD_MESSAGE ?= Update dataset card for whoclickedit
|
||||
|
||||
REPO_URL ?=
|
||||
BRANCH ?= main
|
||||
WORKDIR ?= $(HOME)/PHANTOM-agent
|
||||
@@ -35,8 +44,10 @@ SWEEP_ENV_LOAD = set -a; [ -f "$(SWEEP_ENV_FILE)" ] && . "$(SWEEP_ENV_FILE)" ||
|
||||
|
||||
.PHONY: help
|
||||
help:
|
||||
@echo "pdf.build pdf.watch pdf.clean pdf.genpop pdf.genpop.watch pdf.arxiv | test.backend test.e2e test.all | web.dev | install | train | benchmark | benchmark.simple | benchmark.agent | train.agent | train.bootstrap | stats.lines"
|
||||
@echo "pdf.build pdf.watch pdf.clean pdf.genpop pdf.genpop.watch pdf.summary pdf.summary.watch pdf.arxiv | test.backend test.e2e test.all | web.dev | install | train | benchmark | benchmark.simple | benchmark.agent | train.agent | train.bootstrap | stats.lines | docs.platform | manim.defense manim.defense.hq manim.render manim.render.full manim.render.poster manim.render.appendix manim.render.all"
|
||||
@echo "backend.server backend.provider backend.worker | platform.up platform.down platform.logs | docker.train.publish"
|
||||
@echo "data.pull data.push data.whoclicked.publish | study.margin-erosion study.margin-erosion.quick study.margin-erosion.plot"
|
||||
@echo "tpu.ray.bootstrap tpu.ray.deps tpu.ray.verify tpu.ray.teardown"
|
||||
@echo ""
|
||||
@echo "Build general public version:"
|
||||
@echo " make pdf.genpop"
|
||||
@@ -56,6 +67,12 @@ help:
|
||||
@echo "Bootstrap private repo worker from anywhere:"
|
||||
@echo " make train.bootstrap REPO_URL=https://github.com/org/repo.git BRANCH=main SWEEP_ID=entity/project/id"
|
||||
@echo ""
|
||||
@echo "Bootstrap Ray on TPU slice from config:"
|
||||
@echo " make tpu.ray.bootstrap TPU_CONF=tpu_orchestration/configs/v4_spot_us.conf"
|
||||
@echo ""
|
||||
@echo "Publish whoclickedit dataset + card:"
|
||||
@echo " make data.whoclicked.publish HF_TOKEN=... WHOCLICKED_REPO=velocitatem/whoclickedit"
|
||||
@echo ""
|
||||
@echo "Config source: $(SWEEP_ENV_FILE) (auto-loaded)"
|
||||
|
||||
$(BUILDDIR):
|
||||
@@ -85,6 +102,14 @@ pdf.genpop.watch:
|
||||
pdf.arxiv:
|
||||
@bash scripts/nx_paper.sh build-arxiv
|
||||
|
||||
.PHONY: pdf.summary
|
||||
pdf.summary:
|
||||
@bash scripts/nx_paper.sh build-summary
|
||||
|
||||
.PHONY: pdf.summary.watch
|
||||
pdf.summary.watch:
|
||||
@bash scripts/nx_paper.sh watch-summary
|
||||
|
||||
.PHONY: test.backend
|
||||
test.backend:
|
||||
@$(NX) run research:test
|
||||
@@ -133,10 +158,55 @@ train.agent:
|
||||
train.bootstrap:
|
||||
@WANDB_ENTITY="$(WANDB_ENTITY)" WANDB_PROJECT="$(WANDB_PROJECT)" SWEEP_ENV_FILE="$(SWEEP_ENV_FILE)" REPO_URL="$(REPO_URL)" BRANCH="$(BRANCH)" WORKDIR="$(WORKDIR)" SWEEP_ID="$(SWEEP_ID)" AGENT_COUNT="$(AGENT_COUNT)" AGENT_LOOP="$(AGENT_LOOP)" RETRY_SECONDS="$(RETRY_SECONDS)" $(NX) run research:train-bootstrap
|
||||
|
||||
.PHONY: tpu.ray.bootstrap tpu.ray.deps tpu.ray.verify tpu.ray.teardown
|
||||
tpu.ray.bootstrap:
|
||||
@TPU_CONF="$(TPU_CONF)" SWEEP_ENV_FILE="$(SWEEP_ENV_FILE)" $(NX) run research:tpu-ray-bootstrap
|
||||
|
||||
tpu.ray.deps:
|
||||
@TPU_CONF="$(TPU_CONF)" SWEEP_ENV_FILE="$(SWEEP_ENV_FILE)" $(NX) run research:tpu-ray-deps
|
||||
|
||||
tpu.ray.verify:
|
||||
@TPU_CONF="$(TPU_CONF)" SWEEP_ENV_FILE="$(SWEEP_ENV_FILE)" $(NX) run research:tpu-ray-verify
|
||||
|
||||
tpu.ray.teardown:
|
||||
@TPU_CONF="$(TPU_CONF)" SWEEP_ENV_FILE="$(SWEEP_ENV_FILE)" $(NX) run research:tpu-ray-teardown
|
||||
|
||||
.PHONY: data.pull data.push
|
||||
data.pull:
|
||||
python scripts/hf_data.py pull
|
||||
|
||||
data.push:
|
||||
python scripts/hf_data.py push
|
||||
|
||||
.PHONY: data.whoclicked.publish
|
||||
data.whoclicked.publish:
|
||||
@HF_TOKEN="$(HF_TOKEN)" WHOCLICKED_REPO="$(WHOCLICKED_REPO)" WHOCLICKED_CSV="$(WHOCLICKED_CSV)" WHOCLICKED_CARD="$(WHOCLICKED_CARD)" WHOCLICKED_CSV_PATH_IN_REPO="$(WHOCLICKED_CSV_PATH_IN_REPO)" WHOCLICKED_CARD_PATH_IN_REPO="$(WHOCLICKED_CARD_PATH_IN_REPO)" WHOCLICKED_DATASET_MESSAGE="$(WHOCLICKED_DATASET_MESSAGE)" WHOCLICKED_CARD_MESSAGE="$(WHOCLICKED_CARD_MESSAGE)" $(NX) run research:whoclicked-publish
|
||||
|
||||
.PHONY: stats.lines
|
||||
stats.lines:
|
||||
@$(NX) run research:stats
|
||||
|
||||
.PHONY: study.margin-erosion
|
||||
study.margin-erosion:
|
||||
python -m engine.studies.margin_erosion_alpha
|
||||
|
||||
.PHONY: study.margin-erosion.quick
|
||||
study.margin-erosion.quick:
|
||||
python -m engine.studies.margin_erosion_alpha --quick
|
||||
|
||||
DOCS_VENV ?= docs/.venv
|
||||
DOCS_MKDOCS := $(DOCS_VENV)/bin/mkdocs
|
||||
DOCS_PIP := $(DOCS_VENV)/bin/pip
|
||||
|
||||
.PHONY: docs.platform
|
||||
docs.platform: $(DOCS_VENV)
|
||||
$(DOCS_MKDOCS) build -f docs/mkdocs.yml
|
||||
|
||||
$(DOCS_VENV):
|
||||
python3 -m venv $(DOCS_VENV)
|
||||
$(DOCS_PIP) install --upgrade pip
|
||||
$(DOCS_PIP) install -r docs/requirements.txt
|
||||
|
||||
.PHONY: wordcount
|
||||
wordcount:
|
||||
@$(NX) run paper:wordcount
|
||||
@@ -183,5 +253,28 @@ test:
|
||||
count-lines:
|
||||
@$(NX) run research:stats
|
||||
|
||||
all:
|
||||
@$(NX) run paper:build
|
||||
# Default artifact set for this repo: thesis PDF (same as pdf).
|
||||
all: pdf
|
||||
|
||||
.PHONY: manim.defense manim.defense.hq manim.render manim.render.full manim.render.poster manim.render.appendix manim.render.all
|
||||
# Main defense reel (paper/defense/manim/render_defense); uses paper/defense/.venv when present
|
||||
manim.defense:
|
||||
@cd paper/defense/manim && ./render_defense full
|
||||
|
||||
manim.defense.hq:
|
||||
@cd paper/defense/manim && ./render_defense full --quality qh
|
||||
|
||||
manim.render:
|
||||
@$(NX) run manim:render
|
||||
|
||||
manim.render.full:
|
||||
@$(NX) run manim:render-full
|
||||
|
||||
manim.render.poster:
|
||||
@$(NX) run manim:render-poster
|
||||
|
||||
manim.render.appendix:
|
||||
@$(NX) run manim:render-appendix
|
||||
|
||||
manim.render.all:
|
||||
@$(NX) run manim:render-all
|
||||
|
||||
250
README.md
250
README.md
@@ -1,94 +1,170 @@
|
||||
<img width="200" align="left" src="https://github.com/user-attachments/assets/d148b00d-e9f9-4280-89cc-0cc866e17251" />
|
||||
<p align="center">
|
||||
<img width="180" src="https://github.com/user-attachments/assets/d148b00d-e9f9-4280-89cc-0cc866e17251" alt="PHANTOM logo" />
|
||||
</p>
|
||||
|
||||
### PHANTOM
|
||||
# PHANTOM
|
||||
|
||||
[](https://github.com/velocitatem/PHANTOM/actions/workflows/latex.yml)
|
||||
[](https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf)
|
||||
[](https://sites.research.google/trc/faq/)
|
||||
[](https://phantom-hotel.vercel.app)
|
||||
[](https://phantom-airline.vercel.app)
|
||||
Agent-aware dynamic pricing research platform for studying how automated transaction orchestration changes pricing power, and for testing defenses that recover margin while protecting legitimate user experience.
|
||||
|
||||
<p>
|
||||
<a href="https://github.com/velocitatem/PHANTOM/actions/workflows/latex.yml"><img src="https://github.com/velocitatem/PHANTOM/actions/workflows/latex.yml/badge.svg" alt="Build PDF" style="vertical-align: middle;" /></a>
|
||||
<a href="https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf"><img src="https://img.shields.io/badge/Paper-PDF-red?logo=adobe-acrobat-reader" alt="Paper PDF" style="vertical-align: middle;" /></a>
|
||||
<a href="https://huggingface.co/datasets/velocitatem/whoclickedit"><img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/dataset-on-hf-sm.svg" alt="Dataset on Hugging Face" style="vertical-align: middle; position: relative; top: 1px;" /></a>
|
||||
<a href="https://sites.research.google/trc/faq/"><img src="https://img.shields.io/badge/TPU%20Research%20Cloud-TRC%20supported-4285F4?logo=googlecloud&logoColor=white" alt="TPU Research Cloud" style="vertical-align: middle;" /></a>
|
||||
</p>
|
||||
|
||||
**Live demos:** [Hotel](https://phantom-hotel.vercel.app) | [Airline](https://phantom-airline.vercel.app) | [Academic page](https://velocitatem.github.io/PHANTOM/)
|
||||
|
||||
## What this repository includes
|
||||
|
||||
PHANTOM is a mixed research + engineering monorepo with:
|
||||
|
||||
- a thesis (LaTeX) formalizing Cost of Information (COI) erosion under agentic reconnaissance,
|
||||
- a mode-switching web storefront (`hotel` and `airline`) for controlled human/agent interaction collection,
|
||||
- backend services for event ingestion and pricing,
|
||||
- an experimentation stack for benchmarks, contamination studies, and robust policy training.
|
||||
|
||||
## Why this matters
|
||||
|
||||
Dynamic pricing relies on demand signals collected during browsing. LLM-driven agents can split reconnaissance and execution into separate sessions, which weakens those signals and can collapse extractable price premium. PHANTOM exists to measure that mechanism directly and evaluate practical defenses in a controlled environment.
|
||||
|
||||
## Quick start (local platform)
|
||||
|
||||
### 1) Prerequisites
|
||||
|
||||
- Docker + Docker Compose
|
||||
- Node.js + npm
|
||||
- Python 3.8+
|
||||
- `latexmk` (only if you want to build the paper locally)
|
||||
|
||||
### 2) Install workspace tooling and create env files
|
||||
|
||||
```bash
|
||||
npm install
|
||||
cp .env.example .env
|
||||
cp .env.sweep.example .env.sweep
|
||||
```
|
||||
|
||||
### 3) Fill required values in `.env`
|
||||
|
||||
At minimum, set these before starting services:
|
||||
|
||||
```bash
|
||||
NEXT_PUBLIC_SUPABASE_URL=...
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=...
|
||||
AIRFLOW_FERNET_KEY=...
|
||||
AIRFLOW_SECRET_KEY=...
|
||||
```
|
||||
|
||||
### 4) Start the platform and web app
|
||||
|
||||
```bash
|
||||
make platform.up
|
||||
make web.dev
|
||||
```
|
||||
|
||||
### 5) Verify
|
||||
|
||||
- Web app: `http://localhost:3000`
|
||||
- Backend health: `http://localhost:5000/health`
|
||||
- Pricing provider health: `http://localhost:5001/health`
|
||||
- Airflow UI: `http://localhost:8085`
|
||||
- Kafka console (Redpanda): `http://localhost:8084` (using `.env.example` defaults)
|
||||
|
||||
## Common commands
|
||||
|
||||
| Goal | Command |
|
||||
| --- | --- |
|
||||
| Show all available workflows | `make help` |
|
||||
| Start/stop platform services | `make platform.up` / `make platform.down` |
|
||||
| Stream docker logs | `make platform.logs` |
|
||||
| Run backend tests | `make test.backend` |
|
||||
| Run end-to-end tests | `make test.e2e` |
|
||||
| Build thesis PDF | `make pdf.build` |
|
||||
| Watch thesis while editing | `make pdf.watch` |
|
||||
| Build general-public thesis variant | `make pdf.genpop` |
|
||||
| Run quick margin-erosion study | `make study.margin-erosion.quick` |
|
||||
| Run benchmark without W&B logging | `make benchmark LOCAL_BENCHMARK_ARGS='--tiers static,surge,linear --alpha-values 0.0,0.3 --episodes 3 --no-wandb'` |
|
||||
|
||||
## System map
|
||||
|
||||
```mermaid
|
||||
mindmap
|
||||
PHANTOM((PHANTOM Project))
|
||||
North Star
|
||||
Study how automated actors change markets
|
||||
Build an experimentation platform for real-world-like commerce
|
||||
Two-loop learning system
|
||||
Online observation loop
|
||||
Offline "defense gym" loop
|
||||
Core Economic Questions
|
||||
Price Discovery
|
||||
How prices respond to demand signals
|
||||
How signal quality changes with bots/agents
|
||||
Demand & Elasticity
|
||||
Shifts in willingness-to-pay
|
||||
Short-run vs long-run elasticity
|
||||
Market Efficiency & Welfare
|
||||
Consumer surplus vs producer surplus
|
||||
Deadweight loss from frictions/manipulation
|
||||
Price Discrimination & Segmentation
|
||||
Behavioral feature-based segmentation
|
||||
Fairness vs profitability tradeoffs
|
||||
Information Asymmetry
|
||||
Agents amplify search and arbitrage
|
||||
Sellers infer more about buyers; buyers infer more about sellers
|
||||
Strategic Interaction
|
||||
Consumers vs firms vs agents
|
||||
Feedback loops: policy ↔ behavior ↔ price
|
||||
Market Power & Competition
|
||||
Algorithmic pricing as competitive tool
|
||||
Risks: tacit coordination / "algorithmic collusion"
|
||||
Externalities
|
||||
Congestion and attention costs
|
||||
Spillovers: one segment’s behavior affects others’ prices
|
||||
System-Level View
|
||||
Participants
|
||||
Humans
|
||||
Agents (automated buyers/actors)
|
||||
Firms (pricing decision-makers)
|
||||
Platform (measurement + control layer)
|
||||
Markets Simulated
|
||||
Repeated transactions
|
||||
Limited inventory / capacity constraints (conceptually)
|
||||
Time dynamics (learning over time)
|
||||
Interventions
|
||||
Pricing policies
|
||||
Experiment assignment / randomized exposure
|
||||
Agent behavioral policies (task-driven)
|
||||
Measurement & Causal Inference
|
||||
What is observed
|
||||
Actions (search, click, purchase intent)
|
||||
Context (product attributes, time, exposure)
|
||||
Outcomes (conversion, revenue, churn proxies)
|
||||
Identification strategy
|
||||
A/B tests and randomization
|
||||
Counterfactual baselines
|
||||
Robustness checks (offline replay)
|
||||
Key metrics
|
||||
Revenue / profit proxies
|
||||
Conversion & bounce
|
||||
Price volatility / stability
|
||||
Welfare proxies (e.g., dispersion, access)
|
||||
Risk, Governance, and Ethics
|
||||
Manipulation & Integrity
|
||||
Bot-driven demand distortion
|
||||
Measurement contamination
|
||||
Fairness & Transparency
|
||||
Differential pricing concerns
|
||||
Explainability and auditability
|
||||
Safety Constraints
|
||||
Guardrails on price moves
|
||||
Monitoring for runaway feedback loops
|
||||
Outputs
|
||||
Insights
|
||||
When do agents raise/lower prices via behavior shifts?
|
||||
Which market designs are robust to automation?
|
||||
Defenses
|
||||
Agent-aware pricing policies (robust control)
|
||||
Detection + mitigation strategies (feature-level separability)
|
||||
Platform Value
|
||||
Reusable testbed for market + AI-agent research
|
||||
flowchart LR
|
||||
U[Human / Agent Browser] --> W[Next.js Web App]
|
||||
W -->|Price requests| P[Pricing Provider]
|
||||
W -->|Interaction events| B[Backend Ingest API]
|
||||
B --> K[Kafka]
|
||||
K --> A[Airflow + Worker Jobs]
|
||||
A --> R[Redis Model Registry]
|
||||
P -->|Session/global prices| W
|
||||
E[Research Engine + Experiments] --> A
|
||||
E --> R
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Core runtime (`.env`)
|
||||
|
||||
| Variable | Purpose | Typical value |
|
||||
| --- | --- | --- |
|
||||
| `STORE_MODE` | Web mode switch (`hotel` or `airline`) | `hotel` |
|
||||
| `BACKEND_PORT` | Backend API port | `5000` |
|
||||
| `PROVIDER_PORT` | Pricing provider port | `5001` |
|
||||
| `KAFKA_HOST` | Kafka host for local runtime | `localhost` |
|
||||
| `KAFKA_PORT` | Kafka external port | `9092` |
|
||||
| `REDIS_PORT` | Redis exposed port | `6377` |
|
||||
| `REDPANDA_CONSOLE_PORT` | Kafka console UI port | `8084` |
|
||||
| `NEXT_PUBLIC_SUPABASE_URL` | Product catalog/data source URL | required |
|
||||
| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Product catalog/data source key | required |
|
||||
| `AIRFLOW_FERNET_KEY` | Airflow crypto key | required |
|
||||
| `AIRFLOW_SECRET_KEY` | Airflow webserver secret | required |
|
||||
|
||||
### Training and sweep settings (`.env.sweep`)
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `WANDB_API_KEY` | Required for training/benchmark runs that log to Weights & Biases |
|
||||
| `WANDB_ENTITY` | Optional W&B entity override |
|
||||
| `WANDB_PROJECT` | W&B project name (default: `capstone`) |
|
||||
| `GITHUB_TOKEN` | Required for `make train.bootstrap` |
|
||||
| `SWEEP_ID` | Required for sweep-agent workflows (`train.agent`, `benchmark.agent`) |
|
||||
|
||||
## Repository layout
|
||||
|
||||
| Path | Role |
|
||||
| --- | --- |
|
||||
| `paper/` | Thesis source, bibliography, and build artifacts |
|
||||
| `web/` | Next.js storefront and experiment interaction surface |
|
||||
| `backend/server/` | FastAPI ingestion API and product retrieval endpoints |
|
||||
| `backend/provider/` | FastAPI pricing service backed by model registry data |
|
||||
| `backend/worker/` | Celery worker for asynchronous jobs |
|
||||
| `engine/` | Training and benchmarking entrypoints |
|
||||
| `experiments/` | Data processing, ETL ideas, and analysis assets |
|
||||
| `docker/` | Dockerfiles for platform services |
|
||||
| `tests/e2e/` | Playwright end-to-end tests |
|
||||
| `docs/` | Academic project page (GitHub Pages root) + MkDocs config |
|
||||
| `docs/src/` | Markdown sources for the operator documentation site |
|
||||
| `docs/documentation/` | MkDocs build output (gitignored; run `make docs.platform`; served at `/documentation/` on Pages) |
|
||||
| `SETUP.md` | Unified operator guide: stack, kernels, RL training, thesis refs by chapter |
|
||||
|
||||
## Operational notes
|
||||
|
||||
- `make platform.up` starts the dockerized backend stack; the Next.js app is run separately with `make web.dev`.
|
||||
- `make test.e2e` expects backend (`5000`), web (`3000`), and Airflow (`8085`) to be up.
|
||||
- Research commands (`make train`, `make benchmark*`, `make train.agent`) auto-load `.env.sweep`.
|
||||
- Paper builds call `paper/concat_code.sh` before compilation to flatten code into the appendix.
|
||||
|
||||
## Operator documentation
|
||||
|
||||
- Full setup guide (platform + research): [`SETUP.md`](SETUP.md)
|
||||
- Hosted operator docs (after `make docs.platform`): […/PHANTOM/documentation/](https://velocitatem.github.io/PHANTOM/documentation/) on GitHub Pages
|
||||
|
||||
## Research artifacts
|
||||
|
||||
- Thesis PDF: `thesis-latest.pdf` or [hosted PDF](https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf)
|
||||
- Public dataset: [velocitatem/whoclickedit](https://huggingface.co/datasets/velocitatem/whoclickedit)
|
||||
- Project page: [velocitatem.github.io/PHANTOM](https://velocitatem.github.io/PHANTOM/)
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
This work is supported by Google TPU Research Cloud resources.
|
||||
|
||||
300
SETUP.md
Normal file
300
SETUP.md
Normal file
@@ -0,0 +1,300 @@
|
||||
# PHANTOM: setup for operators and partners
|
||||
|
||||
This guide walks a team from **business context** (what you sell, how you price, what traffic you worry about) through a **running PHANTOM stack**, **behavioral kernels and contamination**, and **RL training / benchmarking**. The math lives in the thesis PDF; here we tie operations to that math without re-deriving it. References to the thesis use **chapter numbers** only (build the PDF locally if you need line-level citations).
|
||||
|
||||
**Thesis (PDF):** [thesis-latest.pdf](https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf)
|
||||
|
||||
---
|
||||
|
||||
## 1. Who this is for / prerequisites
|
||||
|
||||
**Audience:** Engineers and researchers who run Docker, a Next.js app, and Python tooling; product or risk stakeholders who define experiment goals and acceptable UX tradeoffs.
|
||||
|
||||
**Skills:** Docker Compose, Node/npm, Python 3.8+, basic Kafka/Redis mental model.
|
||||
|
||||
**Decide up front:**
|
||||
|
||||
- **Vertical vs demo:** The repo ships `hotel` and `airline` storefront modes (`STORE_MODE`). Anything beyond that is custom integration work.
|
||||
- **Data residency:** Event streams and training artifacts default to paths under the repo (overridable via `PHANTOM_`* env vars in `lib/config.py`). Decide where logs and models may live before you point production-like traffic at the stack.
|
||||
- **Experiment governance:** Who may run human vs agent sessions, how sessions are labeled or weak-labeled for research, and retention policy for interaction logs.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
The formal model assumes each session is generated by a latent **actor class** $Y \in H,A$ (human vs agent). Your deployment choices implicitly assert **which sessions are valid for estimating human vs agent behavior** and whether experimental conditions are stable. If you mix exploratory QA traffic with labeled experiments without recording that fact, you blur the empirical partitions $D_H$ and $D_A$ that the methodology needs for transition kernels and contamination studies. See the **Introduction** (research questions) and **Methodology**, Problem Formalization, in the thesis PDF.
|
||||
|
||||
---
|
||||
|
||||
## 2. Business fit framing
|
||||
|
||||
**The problem PHANTOM addresses:** Session-based pricing accumulates demand signals across a user's browsing history and raises quoted prices accordingly—the **Cost of Information (COI)** premium. LLM agents undercut this by separating reconnaissance (many isolated sessions, no signal accumulation) from execution (a clean session that quotes a floor price). The thesis proves that as the number of independent querying agents grows, the realizable price collapses to a minimum order statistic and COI approaches zero.
|
||||
|
||||
**What PHANTOM gives you:** A controlled platform to measure how much COI is at risk under real agent traffic, simulate that risk across contamination levels $\alpha \in [0,1]$, and train pricing policies that remain robust. The pipeline runs from raw interaction logs through behavioral kernel estimation and a contamination generator to a DR-RL gym.
|
||||
|
||||
**What you must supply:**
|
||||
|
||||
- A **product catalog** path: defaults assume Supabase-backed product data (`NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`).
|
||||
- A plan for **interaction and price events** reaching the ingestion path (backend → Kafka) or an adapter you maintain.
|
||||
- Clear **experiment goals:** e.g. compare human vs agent KPIs under the same task, measure margin under varying contamination $\alpha$.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Aggregate demand in the thesis is a **mixture** over human and agent types with contamination $\alpha$ plus noise $\epsilon_t$; see the mixture demand discussion in **Chapter 3 (Methodology)**. COI is defined as $\mathbb{E}[P]-\underline{p}$; the **COI framework** and theorem in the same chapter explain why saturated agent querying collapses extractable premium. Your business scenario determines which **actions** enter $\hat{q}$ and how interpretable $\alpha$ is for your traffic.
|
||||
|
||||
---
|
||||
|
||||
## 3. Environment and secrets
|
||||
|
||||
**Bootstrap files (from repo root):**
|
||||
|
||||
```bash
|
||||
npm install
|
||||
cp .env.example .env
|
||||
cp .env.sweep.example .env.sweep
|
||||
```
|
||||
|
||||
**Core `.env` (platform + web + docker):** See `[.env.example](.env.example)`. You must also set the variables called out in `[README.md](README.md)` for a full stack: `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `AIRFLOW_FERNET_KEY`, `AIRFLOW_SECRET_KEY` (and provider ports per your compose file).
|
||||
|
||||
**Training / sweeps (`.env.sweep`):** Used by `make train`, `make benchmark`, sweep agents. Typically `WANDB_API_KEY`, optional `WANDB_ENTITY` / `WANDB_PROJECT`, `GITHUB_TOKEN` for bootstrap flows, `SWEEP_ID` for W&B sweep workers. See `[.env.sweep.example](.env.sweep.example)`.
|
||||
|
||||
**Security:** Never commit real `.env` or `.env.sweep` files. Rotate keys if they leak.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Splitting **online platform credentials** (ingestion, catalog, Kafka) from **offline training credentials** (W&B, cloud TPUs, GitHub tokens for workers) mirrors the **hybrid Kappa–Lambda** data loop in the thesis: streaming observation vs batch / long-running training jobs. That split is named in the **Terminology** appendix of the thesis PDF.
|
||||
|
||||
---
|
||||
|
||||
## 4. Bring-up (commands)
|
||||
|
||||
Aligned with `[README.md](README.md)`:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
cp .env.example .env
|
||||
cp .env.sweep.example .env.sweep
|
||||
# edit .env: Supabase, Airflow keys, etc.
|
||||
|
||||
make platform.up
|
||||
make web.dev
|
||||
```
|
||||
|
||||
**Sanity checks:**
|
||||
|
||||
|
||||
| Endpoint | Role |
|
||||
| ------------------------------------------------------------- | --------------------------------- |
|
||||
| `http://localhost:3000` | Next.js storefront |
|
||||
| `http://localhost:5000/health` | Backend ingest API |
|
||||
| `http://localhost:5001/health` | Pricing provider |
|
||||
| `http://localhost:8085` | Airflow UI (default compose port) |
|
||||
| `http://localhost:8084` or configured `REDPANDA_CONSOLE_PORT` | Kafka console (see your `.env`) |
|
||||
|
||||
|
||||
**Optional tests:** `make test.backend` (with venv/tooling as in Makefile); `make test.e2e` requires backend, web, and Airflow up per README.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
A correctly wired stack logs **trajectories** $\tau_s$ (sequences of events) and **price exposure** together. **Chapter 3** defines events $e_{s,k}=(a,i,t)$ and proxies $\hat{q}$ from weighted actions—without joint logging of behavior and quotes, you cannot recover the objects the theory reasons about (Problem Formalization).
|
||||
|
||||
---
|
||||
|
||||
## 5. Service map
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
U[Human / Agent Browser] --> W[Next.js Web App]
|
||||
W -->|Price requests| P[Pricing Provider]
|
||||
W -->|Interaction events| B[Backend Ingest API]
|
||||
B --> K[Kafka]
|
||||
K --> A[Airflow + Worker Jobs]
|
||||
A --> R[Redis Model Registry]
|
||||
P -->|Session/global prices| W
|
||||
E[Research Engine + Experiments] --> A
|
||||
E --> R
|
||||
```
|
||||
|
||||
|
||||
|
||||
**Ports (typical; confirm in `docker-compose` and `.env`):** `BACKEND_PORT` (5000), `PROVIDER_PORT` (5001), `KAFKA_PORT`, `REDIS_PORT`, Airflow `AIRFLOW_WEBSERVER_PORT` (8085 default), Redpanda console.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
The platform **observes** behavioral proxies and quoted prices, not the latent demand curve $d(p\mid\theta)$. The distinction between $\hat{q}$ and true demand is explicit in **Chapter 3**. Misattributing proxy noise to “true” elasticity breaks both estimation and any causal story about COI.
|
||||
|
||||
---
|
||||
|
||||
## 6. Tailoring to your business
|
||||
|
||||
**Storefront mode:** `STORE_MODE=hotel` or `airline` (see `[web/src/lib/config.ts](web/src/lib/config.ts)` and env). This switches catalog and UI, not the core ingestion pattern.
|
||||
|
||||
**API base / environment:** `NEXT_PUBLIC_API_BASE`, `NEXT_PUBLIC_APP_ENV` (validated in `config.ts`).
|
||||
|
||||
**Paths for data and runs:** Override with `PHANTOM_DATA_DIR`, `PHANTOM_SIM_RUNS_DIR`, `PHANTOM_MODEL_REGISTRY_DIR`, `PHANTOM_COLLECTED_DATA_DIR`, etc. (`[lib/config.py](lib/config.py)`).
|
||||
|
||||
**Scope:** A new vertical (custom product ontology, checkout rules, pricing rules) means **new UI, events, and possibly new reward features** in the engine. Budget engineering time; the repo is a research platform, not a turnkey SaaS skin for arbitrary catalogs without code changes.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Transition kernels $\hat{\mathcal{T}}_H,\hat{\mathcal{T}}_A$ are estimated on a **finite action / state space** derived from your instrumentation. Changing catalog depth or event taxonomy changes the MDP state space; old kernel estimates are not portable. See the transition kernel discussion in **Chapter 3**.
|
||||
|
||||
---
|
||||
|
||||
## 7. Data collection and experiments
|
||||
|
||||
**Flow:** Browser → backend → **Kafka** → downstream consumers (Airflow DAGs, notebooks, ETL under `experiments/`). Ensure **session identity**, **item identifiers**, and **action types** are consistent enough to build trajectories.
|
||||
|
||||
**Weak labels:** The thesis discusses partitioning data into human vs agent subsets for MLE transition counts. In production you may only have heuristic labels—document bias explicitly.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Distinguishability (sub-question SQ1 in the **Introduction**) asks whether $H$ vs $A$ is identifiable from behavior alone. Your labeling and experimental design determine whether $\Delta_H,\Delta_A$ and $f(\tau)$ are meaningful or dominated by noise. Symbols appear in the **Terminology** appendix ($\Delta_H,\Delta_A$, $f(\tau)$, contamination generator $\mathcal{G}(\alpha)$).
|
||||
|
||||
---
|
||||
|
||||
## 8. Transition kernels and agent scoring (theory → practice)
|
||||
|
||||
**Theory:** Sessions yield trajectories $\tau_s$. For each actor class $y\inH,A$, the thesis estimates a **Markov transition kernel** by counting transitions and normalizing (MLE):
|
||||
|
||||
$$
|
||||
\hat{P}(s' \mid s) = \frac{N(s,s')}{\sum_k N(s,k)}
|
||||
$$
|
||||
|
||||
Human and agent prototypes $\hat{\mathcal{T}}_H,\hat{\mathcal{T}}_A$ support comparing an empirical kernel from a partial trajectory to prototypes (e.g. KL-style divergences $\Delta_H,\Delta_A$) and mapping to a **weak agent probability** $f(\tau)$. See **Chapter 3** and the **Terminology** appendix.
|
||||
|
||||
**Code:** `[engine/lib/coi.py](engine/lib/coi.py)` (`compute_agent_probability`: empirical transition counts vs human/agent reference dicts, KL-style terms, mapped via `[lib/agent_probability.py](lib/agent_probability.py)`).
|
||||
|
||||
**Optional narrative:** `[blog/02-behavioral-fingerprinting.md](blog/02-behavioral-fingerprinting.md)` walks a concrete study design (not required for operators).
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
If reference kernels are fit on **stale** or **mislabeled** partitions, $\Delta_H-\Delta_A$ is not interpretable as distinguishability. Ground claims in SQ1 (**Introduction**) and the kernel subsection of **Chapter 3**.
|
||||
|
||||
---
|
||||
|
||||
## 9. Contamination generator $\mathcal{G}(\alpha)$
|
||||
|
||||
**Theory:** Given clean trajectories, $\mathcal{G}(\alpha)$ injects synthetic agent trajectories until the effective mixture reaches contamination $\alpha\in[0,1]$, defining training scenarios for robust policies (**Chapter 3**). Catalog-scale block expansion of kernels is discussed there with validation caveats—treat large product spaces as **research-grade** until your team signs off.
|
||||
|
||||
**Code:** `[engine/engine.py](engine/engine.py)` — `MarketEngine` mixes human/agent demand, uses `get_adjusted_transitions` / `sample_behavior_from_transitions`, and `alpha` when combining actor types and building demand proxies (`estimate_demand`). This is the **simulator** path, not a drop-in replacement for your production database.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
$\alpha$ in mixture $Q(p)$ is **agentic demand contribution** in the formal model, not necessarily “bot share of page views” unless your instrumentation equates them. Mismeasuring $\alpha$ biases robust objectives tied to a fixed contamination level.
|
||||
|
||||
---
|
||||
|
||||
## 10. Training and evaluation — local workflow
|
||||
|
||||
**Environment:** Python venv via Nx (`make install` / `nx run research:install`). Training commands load `.env.sweep`.
|
||||
|
||||
```bash
|
||||
make train LOCAL_TRAIN_ARGS='--algo ppo --total-timesteps 50000'
|
||||
make benchmark LOCAL_BENCHMARK_ARGS='--tiers static,surge,linear,qtable,ppo --alpha-values 0.0,0.3 --episodes 3 --no-wandb'
|
||||
make benchmark.simple
|
||||
```
|
||||
|
||||
Entrypoints: `[engine/train.py](engine/train.py)`, `[engine/benchmark.py](engine/benchmark.py)`, `[engine/spec.py](engine/spec.py)` (Nx wraps these—see `project.json` / research targets).
|
||||
|
||||
**Artifacts:** `[lib/config.py](lib/config.py)` — `PHANTOM_SIM_RUNS_DIR` (default `sim/rl/runs`), `PHANTOM_MODEL_REGISTRY_DIR`, etc.
|
||||
|
||||
**TensorBoard (optional):** `[docker-compose.yml](docker-compose.yml)` includes `tensorboard-rl` on host port **6007** (`./sim/rl/runs`) and `tensorboard-ml` on **6006** (`./experiments/ml/runs`).
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Local runs instantiate the **offline defense gym**: policies trained on simulator-induced distributions approximate the DR-RL narrative in **Chapter 3**, but hyperparameters ($\lambda$ on COI leakage, $\eta$ on UX, robust radius) change the effective ambiguity set. Cross-check `engine/` against the thesis before claiming figure-for-figure replication.
|
||||
|
||||
---
|
||||
|
||||
## 11. Training and evaluation — remote / scaled deployment
|
||||
|
||||
For **research at scale** (cloud quota and secrets required):
|
||||
|
||||
|
||||
| Mechanism | Role |
|
||||
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `[submit_ray_job.sh](submit_ray_job.sh)` | Ray jobs with `.env` injected; `RAY_MODE=single|distributed|benchmark|sweep`. Set the script’s `ROOT` to your clone path. |
|
||||
| `make tpu.ray.bootstrap` / `tpu.ray.`* | TPU Ray bootstrap (`TPU_CONF`, e.g. `tpu_orchestration/configs/v4_spot_us.conf`). |
|
||||
| `make train.agent` / `make benchmark.agent` | W&B sweeps: `SWEEP_ID` in `.env.sweep`. |
|
||||
| `make train.bootstrap` | Worker bootstrap: `REPO_URL`, `SWEEP_ID`, `GITHUB_TOKEN`. |
|
||||
| `make docker.train.publish` | Trainer image (`TRAIN_IMAGE_REF` in Makefile). |
|
||||
|
||||
|
||||
See `submit_ray_job.sh` for env vars (`WANDB_*`, `PHANTOM_*` TPU toggles).
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Distributed training does not change the **definitions** of the Stackelberg game or Wasserstein ambiguity; it changes compute and variance of empirical estimates. Align random seeds and data protocol across nodes or split results explicitly—otherwise you mix distributions in a way a single empirical law $\hat{P}_N$ in the thesis does not describe.
|
||||
|
||||
---
|
||||
|
||||
## 12. Evaluation, artifacts, and audit trail
|
||||
|
||||
**Benchmarks:** `make benchmark`* sweeps tiers and $\alpha$; CLI includes robustness knobs (see default `BENCHMARK_ARGS` in `submit_ray_job.sh`: `--robust-radius`, `--lambda-coi`, `--eta-ux`, etc.).
|
||||
|
||||
**Audit trail:** Store `git` SHA, CLI argv, non-secret `.env.sweep` keys, and W&B run IDs with published tables. For scientific claims, cite **Chapters 4–5 (Results, Discussion)** in the thesis PDF.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Evaluation quality equals **simulator fidelity** plus **contamination modeling**. Separate theorem statements (assumption-based) from empirical curves (`engine`-dependent).
|
||||
|
||||
---
|
||||
|
||||
## 13. Operational suggestions
|
||||
|
||||
- **Staging:** Non-production namespaces; separate Kafka topics and Supabase projects where possible.
|
||||
- **Rate limits / abuse:** Protect ingest endpoints; respect participant privacy.
|
||||
- **Human vs agent sessions:** Comparable cohorts; record experimental condition in metadata.
|
||||
- **Contracts:** `tests/e2e/` encodes minimal flows—use when APIs change.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Non-stationary noise $\epsilon_t$ and drifting $\alpha$ confound benchmark interpretation. **Chapter 3** discusses mixture identification: isolate treatments when possible and document confounders when not.
|
||||
|
||||
---
|
||||
|
||||
## 14. Roadmap and gaps
|
||||
|
||||
**In repo:** Local dockerized stack, demo verticals, engine benchmarks, documented env and paths.
|
||||
|
||||
**Usually custom:** Production catalog without Supabase, identity/fraud layers, legal review of logging, Kafka/Airflow SLAs, hardening the pricing provider for real money.
|
||||
|
||||
**Thesis vs code:** The PDF is the **spec**; not every robustness term or large-catalog kernel construction is production-verified—see caveats in **Chapter 3**.
|
||||
|
||||
### Theoretical implications
|
||||
|
||||
Theorems in the thesis can be **stronger** than what observational firm logs support. The COI result assumes a clean experimental reading of the pricing policy; live market data may only support weaker claims.
|
||||
|
||||
---
|
||||
|
||||
## 15. Theory and thesis cross-references (quick index)
|
||||
|
||||
Use the **PDF table of contents** with these anchors:
|
||||
|
||||
|
||||
| Topic | Thesis location |
|
||||
| -------------------------------------------------------------------------- | ----------------------------------------------------- |
|
||||
| Research questions (margin, distinguishability, contamination, mitigation) | **Introduction** |
|
||||
| Sessions, events, $\hat{q}$, mixture $Q(p)$, $\alpha$ | **Chapter 3** — Problem Formalization, mixture demand |
|
||||
| COI definition and erosion theorem | **Chapter 3** — COI framework |
|
||||
| Transition kernels, MLE, $\mathcal{G}(\alpha)$ | **Chapter 3** |
|
||||
| DR-RL, ambiguity sets, Stackelberg | **Chapter 3** |
|
||||
| Symbol glossary (COI leakage, $f(\tau)$, UX, surrogates) | **Appendix — Terminology** |
|
||||
| Empirical results and limitations | **Chapters 4–5** |
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 16. Quick file index (code)
|
||||
|
||||
|
||||
| File | Role |
|
||||
| ---------------------------------------------------------------------------------- | -------------------------------------------------- |
|
||||
| `[engine/lib/coi.py](engine/lib/coi.py)` | KL-style trajectory comparison; agent probability. |
|
||||
| `[engine/engine.py](engine/engine.py)` | `MarketEngine`, mixture, demand proxy path. |
|
||||
| `[lib/agent_probability.py](lib/agent_probability.py)` | Divergence → probability score. |
|
||||
| `[lib/config.py](lib/config.py)` | Paths and ports for artifacts. |
|
||||
| `[engine/train.py](engine/train.py)`, `[engine/benchmark.py](engine/benchmark.py)` | CLI entrypoints. |
|
||||
| `[tpu_orchestration/](tpu_orchestration/)` | TPU configs and helpers. |
|
||||
|
||||
|
||||
Many offline benchmarks run without a storefront once the research Python environment is installed; connecting production trajectories to kernel estimation still requires aligned instrumentation.
|
||||
@@ -1,6 +0,0 @@
|
||||
64 spot Cloud TPU v6e chips in zone europe-west4-a
|
||||
32 spot Cloud TPU v4 chips in zone us-central2-b
|
||||
64 spot Cloud TPU v5e chips in zone us-central1-a
|
||||
64 spot Cloud TPU v6e chips in zone us-east1-d
|
||||
32 on-demand Cloud TPU v4 chips in zone us-central2-b
|
||||
64 spot Cloud TPU v5e chips in zone europe-west4-b
|
||||
@@ -1,22 +0,0 @@
|
||||
# 32 spot Cloud TPU v4 chips in zone us-central2-b
|
||||
export PROJECT_ID=phantom-trc
|
||||
export QR_NAME=TPUv4s32spotUC2B
|
||||
export TPU_NAME=tpu-v4-32-uc2b-spot
|
||||
export ZONE=us-central2-b
|
||||
export ACCELERATOR_TYPE=v4-32
|
||||
export RUNTIME_VERSION=v2-alpha-tpuv4
|
||||
|
||||
gcloud compute tpus tpu-vm create ${TPU_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--version=${RUNTIME_VERSION} \
|
||||
--spot \
|
||||
|| \
|
||||
gcloud compute tpus queued-resources create ${QR_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--node-id=${TPU_NAME} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--runtime-version=${RUNTIME_VERSION} \
|
||||
--spot
|
||||
@@ -1,13 +0,0 @@
|
||||
# 32 on-demand Cloud TPU v4 chips in zone us-central2-b
|
||||
export PROJECT_ID=phantom-trc
|
||||
export QR_NAME=TPUlong
|
||||
export ZONE=us-central2-b
|
||||
export ACCELERATOR_TYPE=v4-32
|
||||
export RUNTIME_VERSION=v2-alpha-tpuv4
|
||||
#gcloud compute tpus tpu-vm create ${TPU_NAME} --zone=${ZONE} --project=${PROJECT_ID} --accelerator-type=${ACCELERATOR_TYPE} --version=${RUNTIME_VERSION}
|
||||
gcloud compute tpus queued-resources create ${QR_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--node-id=${TPU_NAME} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--runtime-version=${RUNTIME_VERSION}
|
||||
@@ -1,22 +0,0 @@
|
||||
# 64 spot Cloud TPU v5e chips in zone europe-west4-b
|
||||
export PROJECT_ID=phantom-trc
|
||||
export QR_NAME=TPUv5e64spotEW4B
|
||||
export TPU_NAME=tpu-v5e-64-ew4b
|
||||
export ZONE=europe-west4-b
|
||||
export ACCELERATOR_TYPE=v5e-64
|
||||
export RUNTIME_VERSION=v2-alpha-tpuv5-lite
|
||||
|
||||
gcloud compute tpus tpu-vm create ${TPU_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--version=${RUNTIME_VERSION} \
|
||||
--spot \
|
||||
|| \
|
||||
gcloud compute tpus queued-resources create ${QR_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--node-id=${TPU_NAME} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--runtime-version=${RUNTIME_VERSION} \
|
||||
--spot
|
||||
@@ -1,22 +0,0 @@
|
||||
# 64 spot Cloud TPU v5e chips in zone us-central1-a
|
||||
export PROJECT_ID=phantom-trc
|
||||
export QR_NAME=TPUv5e64spotUC1A
|
||||
export TPU_NAME=tpu-v5e-64-uc1a
|
||||
export ZONE=us-central1-a
|
||||
export ACCELERATOR_TYPE=v5e-64
|
||||
export RUNTIME_VERSION=v2-alpha-tpuv5-lite
|
||||
|
||||
gcloud compute tpus tpu-vm create ${TPU_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--version=${RUNTIME_VERSION} \
|
||||
--spot \
|
||||
|| \
|
||||
gcloud compute tpus queued-resources create ${QR_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--node-id=${TPU_NAME} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--runtime-version=${RUNTIME_VERSION} \
|
||||
--spot
|
||||
@@ -1,22 +0,0 @@
|
||||
# 64 spot Cloud TPU v6e chips in zone europe-west4-a
|
||||
export PROJECT_ID=phantom-trc
|
||||
export QR_NAME=TPUv6e64spotEW4A
|
||||
export TPU_NAME=tpu-v6e-64-ew4a
|
||||
export ZONE=europe-west4-a
|
||||
export ACCELERATOR_TYPE=v6e-64
|
||||
export RUNTIME_VERSION=v2-alpha-tpuv6e
|
||||
|
||||
gcloud compute tpus tpu-vm create ${TPU_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--version=${RUNTIME_VERSION} \
|
||||
--spot \
|
||||
|| \
|
||||
gcloud compute tpus queued-resources create ${QR_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--node-id=${TPU_NAME} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--runtime-version=${RUNTIME_VERSION} \
|
||||
--spot
|
||||
@@ -1,22 +0,0 @@
|
||||
# 64 spot Cloud TPU v6e chips in zone us-east1-d
|
||||
export PROJECT_ID=phantom-trc
|
||||
export QR_NAME=TPUv6e64spotUE1D
|
||||
export TPU_NAME=tpu-v6e-64-ue1d
|
||||
export ZONE=us-east1-d
|
||||
export ACCELERATOR_TYPE=v6e-64
|
||||
export RUNTIME_VERSION=v2-alpha-tpuv6e
|
||||
|
||||
gcloud compute tpus tpu-vm create ${TPU_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--version=${RUNTIME_VERSION} \
|
||||
--spot \
|
||||
|| \
|
||||
gcloud compute tpus queued-resources create ${QR_NAME} \
|
||||
--project=${PROJECT_ID} \
|
||||
--zone=${ZONE} \
|
||||
--node-id=${TPU_NAME} \
|
||||
--accelerator-type=${ACCELERATOR_TYPE} \
|
||||
--runtime-version=${RUNTIME_VERSION} \
|
||||
--spot
|
||||
@@ -1,4 +1,23 @@
|
||||
services:
|
||||
tpu-watchdogs:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/TPUWatchdog.dockerfile
|
||||
container_name: "PHANTOM-tpu-watchdogs"
|
||||
restart: unless-stopped
|
||||
user: "${UID:-1000}:${GID:-1000}"
|
||||
environment:
|
||||
- HF_TOKEN=${HF_TOKEN}
|
||||
- WANDB_API_KEY=${WANDB_API_KEY}
|
||||
- GITHUB_TOKEN=${GITHUB_TOKEN}
|
||||
- GOOGLE_APPLICATION_CREDENTIALS=/secrets/gcp-sa.json
|
||||
- GCP_ACCOUNT=${GCP_ACCOUNT:-}
|
||||
- WATCHDOG_CONFIG_PATTERN=${WATCHDOG_CONFIG_PATTERN:-v[46]*.conf}
|
||||
- CLOUDSDK_CONFIG=/.config/gcloud
|
||||
volumes:
|
||||
- ~/.config/gcloud:/.config/gcloud:rw
|
||||
- ./secrets/gcp-sa.json:/secrets/gcp-sa.json:ro
|
||||
|
||||
tensorboard-rl:
|
||||
image: tensorflow/tensorflow:latest
|
||||
container_name: "PHANTOM-tensorboard-rl"
|
||||
|
||||
112
docker/TPUWatchdog.dockerfile
Normal file
112
docker/TPUWatchdog.dockerfile
Normal file
@@ -0,0 +1,112 @@
|
||||
FROM google/cloud-sdk:slim
|
||||
|
||||
# Install tmux to manage multiple watchdogs and jq for json parsing
|
||||
RUN apt-get update && \
|
||||
apt-get install -y tmux jq && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy the orchestration scripts and configs
|
||||
COPY tpu_orchestration/ /app/tpu_orchestration/
|
||||
|
||||
# Make sure scripts are executable
|
||||
RUN chmod +x /app/tpu_orchestration/watchdog.sh
|
||||
RUN chmod +x /app/tpu_orchestration/tpu_startup.sh
|
||||
|
||||
# Create an entrypoint script that launches a watchdog for each config
|
||||
COPY <<-'EOF' /app/entrypoint.sh
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Make sure required variables are set
|
||||
if [ -z "$HF_TOKEN" ]; then
|
||||
echo "Error: HF_TOKEN environment variable is required."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$WANDB_API_KEY" ]; then
|
||||
echo "Warning: WANDB_API_KEY environment variable is not set. Wandb logging may fail on TPUs."
|
||||
fi
|
||||
|
||||
# Authenticate gcloud if credentials are provided
|
||||
if [ -n "$GOOGLE_APPLICATION_CREDENTIALS" ] && [ -f "$GOOGLE_APPLICATION_CREDENTIALS" ]; then
|
||||
CRED_TYPE=$(jq -r '.type' "$GOOGLE_APPLICATION_CREDENTIALS" 2>/dev/null || echo "unknown")
|
||||
if [ "$CRED_TYPE" = "service_account" ]; then
|
||||
echo "Authenticating gcloud using service account key..."
|
||||
gcloud auth activate-service-account --key-file="$GOOGLE_APPLICATION_CREDENTIALS"
|
||||
|
||||
if [ -z "$PROJECT_ID" ]; then
|
||||
PROJECT_ID=$(jq -r '.project_id // empty' "$GOOGLE_APPLICATION_CREDENTIALS")
|
||||
fi
|
||||
elif [ "$CRED_TYPE" = "authorized_user" ]; then
|
||||
echo "Using authorized_user credentials via credential file override..."
|
||||
export CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE="$GOOGLE_APPLICATION_CREDENTIALS"
|
||||
|
||||
if gcloud auth print-access-token >/dev/null 2>&1; then
|
||||
ACTIVE_ACCOUNT=$(gcloud config get-value account 2>/dev/null || true)
|
||||
if [ -z "$ACTIVE_ACCOUNT" ] || [ "$ACTIVE_ACCOUNT" = "(unset)" ]; then
|
||||
ACTIVE_ACCOUNT=$(jq -r '.account // empty' "$GOOGLE_APPLICATION_CREDENTIALS")
|
||||
fi
|
||||
|
||||
if [ -n "$ACTIVE_ACCOUNT" ] && [ "$ACTIVE_ACCOUNT" != "(unset)" ]; then
|
||||
echo "Using gcloud account: $ACTIVE_ACCOUNT"
|
||||
else
|
||||
echo "Using gcloud credential override from $GOOGLE_APPLICATION_CREDENTIALS"
|
||||
fi
|
||||
else
|
||||
echo "Warning: credential file override token check failed. Falling back to mounted gcloud config."
|
||||
unset CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE
|
||||
|
||||
if [ -n "$GCP_ACCOUNT" ]; then
|
||||
gcloud config set account "$GCP_ACCOUNT" >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
ACTIVE_ACCOUNT=$(gcloud config get-value account 2>/dev/null || true)
|
||||
if [ -z "$ACTIVE_ACCOUNT" ] || [ "$ACTIVE_ACCOUNT" = "(unset)" ]; then
|
||||
echo "Error: no active gcloud account available. Run 'gcloud auth login' on host and mount ~/.config/gcloud, or use a service account key."
|
||||
exit 1
|
||||
fi
|
||||
echo "Using gcloud account: $ACTIVE_ACCOUNT"
|
||||
fi
|
||||
else
|
||||
echo "Warning: unsupported credential file type '$CRED_TYPE'. Falling back to mounted gcloud config."
|
||||
fi
|
||||
else
|
||||
echo "Note: Assuming gcloud config is mounted from host."
|
||||
fi
|
||||
|
||||
if [ -n "$PROJECT_ID" ]; then
|
||||
gcloud config set project "$PROJECT_ID"
|
||||
echo "Set project to $PROJECT_ID"
|
||||
fi
|
||||
|
||||
# Run the watchdogs in the background using bash instead of tmux
|
||||
# Tmux needs a TTY to attach properly which we might not have in docker
|
||||
# Stagger startups by 15s to prevent simultaneous TPU creation quota hits
|
||||
CONFIG_PATTERN=${WATCHDOG_CONFIG_PATTERN:-"*.conf"}
|
||||
shopt -s nullglob
|
||||
CONFIGS=(/app/tpu_orchestration/configs/$CONFIG_PATTERN)
|
||||
|
||||
if [ ${#CONFIGS[@]} -eq 0 ]; then
|
||||
echo "Error: no watchdog configs matched pattern '$CONFIG_PATTERN'."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Using watchdog config pattern: $CONFIG_PATTERN"
|
||||
DELAY=0
|
||||
for conf in "${CONFIGS[@]}"; do
|
||||
echo "Starting watchdog for $(basename "$conf" .conf) (delay: ${DELAY}s)"
|
||||
(sleep $DELAY && /app/tpu_orchestration/watchdog.sh "$conf") &
|
||||
DELAY=$((DELAY + 15))
|
||||
done
|
||||
|
||||
echo "All watchdogs queued with staggered startup."
|
||||
|
||||
# Keep the container running
|
||||
wait
|
||||
EOF
|
||||
|
||||
RUN chmod +x /app/entrypoint.sh
|
||||
|
||||
CMD ["/app/entrypoint.sh"]
|
||||
@@ -45,14 +45,12 @@
|
||||
<meta name="citation_pdf_url" content="https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf">
|
||||
|
||||
<!-- Additional SEO -->
|
||||
<meta name="theme-color" content="#2563eb">
|
||||
<meta name="msapplication-TileColor" content="#2563eb">
|
||||
<meta name="theme-color" content="#303030">
|
||||
<meta name="msapplication-TileColor" content="#303030">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default">
|
||||
|
||||
<!-- Preconnect for performance -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="preconnect" href="https://ajax.googleapis.com">
|
||||
<link rel="preconnect" href="https://documentcloud.adobe.com">
|
||||
<link rel="preconnect" href="https://cdn.jsdelivr.net">
|
||||
@@ -82,9 +80,6 @@
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/jpswalsh/academicons@1/css/academicons.min.css">
|
||||
</noscript>
|
||||
|
||||
<!-- Fonts - Optimized loading -->
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
|
||||
<!-- Defer non-critical JavaScript -->
|
||||
<script defer src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
|
||||
<script defer src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
|
||||
@@ -188,6 +183,14 @@
|
||||
</div>
|
||||
<i class="fas fa-external-link-alt"></i>
|
||||
</a>
|
||||
<a href="documentation/" class="work-item">
|
||||
<div class="work-info">
|
||||
<h5>Documentation</h5>
|
||||
<p>Operator setup, configuration, architecture, and research pipeline (MkDocs).</p>
|
||||
<span class="work-venue">Platform</span>
|
||||
</div>
|
||||
<i class="fas fa-book"></i>
|
||||
</a>
|
||||
<a href="https://github.com/velocitatem/p4p" class="work-item" target="_blank">
|
||||
<div class="work-info">
|
||||
<h5>P4P Interaction Layer</h5>
|
||||
@@ -239,14 +242,14 @@
|
||||
<div class="columns is-centered">
|
||||
<div class="column has-text-centered">
|
||||
<h1 class="title is-1 publication-title">Pricing Heuristics Against Non-human Transaction Orchestration Mechanisms</h1>
|
||||
<div class="is-size-5 publication-authors">
|
||||
<div class="is-size-5 publication-authors author-names">
|
||||
<span class="author-block">
|
||||
<a href="https://alves.world" target="_blank">Daniel Rösel</a></span>
|
||||
</div>
|
||||
|
||||
<div class="is-size-5 publication-authors">
|
||||
<div class="is-size-5 publication-authors author-meta">
|
||||
<span class="author-block">IE University<br>Bachelor's Thesis 2025</span>
|
||||
<span class="eql-cntrb"><small><br>Advisor: Alberto Martín Izquierdo</small></span>
|
||||
<span class="eql-cntrb">Advisor: Alberto Martín Izquierdo</span>
|
||||
</div>
|
||||
|
||||
<div class="column has-text-centered">
|
||||
@@ -272,12 +275,12 @@
|
||||
</span>
|
||||
|
||||
<span class="link-block">
|
||||
<a href="goals/goals.csv" target="_blank"
|
||||
<a href="https://huggingface.co/datasets/velocitatem/whoclickedit" target="_blank"
|
||||
class="external-link button is-normal is-rounded is-dark">
|
||||
<span class="icon">
|
||||
<i class="fas fa-list"></i>
|
||||
<i class="fas fa-database"></i>
|
||||
</span>
|
||||
<span>Goal Set</span>
|
||||
<span>Dataset</span>
|
||||
</a>
|
||||
</span>
|
||||
|
||||
@@ -337,10 +340,13 @@
|
||||
<h2 class="title is-3">Abstract</h2>
|
||||
<div class="content has-text-justified">
|
||||
<p>
|
||||
When you shop online, prices often change based on how much interest you show — the more you browse, the more the site learns about your intent and may raise prices accordingly. This works because stores assume that a curious, engaged shopper is more likely to buy. But AI assistants are now doing the shopping research on behalf of users: they browse in one session to gather price information and then let the user purchase in a fresh session at the lower, unadjusted price. The store never sees the connection between the two, so it never gets to factor in that genuine intent — and loses the revenue it would have earned.
|
||||
Dynamic pricing extracts margin by exploiting the gap between what a platform knows and what a buyer knows. A user who browses a hotel across several sessions signals intent; the platform raises the price accordingly. That information asymmetry — the <em>Cost of Information</em> — is the economic engine behind session-based pricing in travel, hospitality, and e-commerce.
|
||||
</p>
|
||||
<p>
|
||||
PHANTOM studies this problem and builds defenses against it. We created a realistic fake store (in hotel and airline modes) where both real people and AI agents were given shopping tasks, and we recorded every click, scroll, and page visit. By comparing how humans and AI agents move through a site, we found clear patterns that tell them apart. We then used those patterns to build a smarter pricing system that can recognize when it is likely talking to an AI scout and adjust its strategy accordingly — protecting the store's margins without making things worse for genuine shoppers.
|
||||
LLM agents break the engine. An agent conducting reconnaissance in isolated sessions accumulates zero demand signal, then routes the purchase through a clean session at the floor price. As the number of independent querying agents grows, the realizable price converges to its minimum order statistic and COI collapses to zero. This is not a future risk; it is a structural failure mode in any pricing system that treats sessions independently.
|
||||
</p>
|
||||
<p>
|
||||
PHANTOM formalizes the failure, measures it on real human and agent interaction data, and builds a defense. We prove the COI erosion theorem, collect 29 labeled sessions (13 human, 16 agent) across hotel and airline storefronts under goal-driven tasks, learn class-specific Markov transition kernels, and train a Distributionally Robust RL pricing policy over a Wasserstein ambiguity set. Behavioral separability is statistically significant (Mann–Whitney <em>U</em> = 2.0, <em>p</em> = 0.0006). The per-session agent probability signal <em>f</em>(τ) feeds directly into the robust policy reward as a COI-leakage penalty.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -352,18 +358,30 @@
|
||||
<section class="section">
|
||||
<div class="container is-max-desktop">
|
||||
<div class="content has-text-justified">
|
||||
<h2 class="title is-3 has-text-centered">Project Scope</h2>
|
||||
<h2 class="title is-3 has-text-centered">How it works</h2>
|
||||
<p>
|
||||
The current thesis revision extends both theory and implementation. The main research question is how a pricing system can preserve margin integrity when browsing and purchasing are increasingly orchestrated by AI agents.
|
||||
The methodology runs in three stages: observe, distinguish, defend.
|
||||
</p>
|
||||
<ul>
|
||||
<li>Formal contribution: a Cost of Information erosion theorem showing why price-query saturation can collapse dynamic pricing power.</li>
|
||||
<li>System contribution: a hybrid online/offline stack (Next.js storefront, pricing provider, Kafka event streams, Airflow ETL, Redis serving layer).</li>
|
||||
<li>Modeling contribution: class-specific transition kernels for human and agent behavior, with KL-divergence based separability scores.</li>
|
||||
<li>Control contribution: a contamination-aware DR-RL pricing policy trained under distributional uncertainty using Wasserstein-style robustness.</li>
|
||||
</ul>
|
||||
|
||||
<h3 class="title is-4">Stage 1 — Observe</h3>
|
||||
<p>
|
||||
Controlled trials currently include balanced human and agent sessions with goal-driven tasks across hotel and airline interfaces. Early separability results are strong (Mann-Whitney U=2.0, p=0.0006), while robust pricing gains remain regime-dependent and are being calibrated in larger sweeps.
|
||||
Both human participants and LLM agents are assigned goal-driven tasks on a live instrumented storefront (hotel or airline mode). Every interaction is logged as a timestamped event tuple <code>(action, item, timestamp)</code>. Actions are partitioned into four semantic categories — cart, dwell, navigation, filter — with decreasing signal weights (4.0, 2.0, 1.0, 0.5) calibrated by the KL divergence between human and agent transition rows. Price quotes are streamed to a separate Kafka topic, enabling joint analysis of behavior and pricing exposure. The platform runs a surge-discount heuristic during collection to expose participants to state-dependent prices.
|
||||
</p>
|
||||
|
||||
<h3 class="title is-4">Stage 2 — Distinguish</h3>
|
||||
<p>
|
||||
From the labeled session trajectories, we estimate class-specific Markov transition kernels <em>T̂<sub>H</sub></em> and <em>T̂<sub>A</sub></em> by maximum likelihood. For any new partial trajectory τ', we compute KL divergence to each prototype:
|
||||
</p>
|
||||
<p style="text-align:center; font-style:italic; margin: 1rem 0;">
|
||||
Δ<sub>H</sub> = D<sub>KL</sub>(T̂' ∥ T̄<sub>H</sub>), Δ<sub>A</sub> = D<sub>KL</sub>(T̂' ∥ T̄<sub>A</sub>)
|
||||
</p>
|
||||
<p>
|
||||
The gap score <em>g</em>(τ') = Δ<sub>H</sub> − Δ<sub>A</sub> maps to a weak agent probability via a temperature-controlled logistic function: <em>f</em>(τ') = σ((Δ<sub>H</sub> − Δ<sub>A</sub>) / T). This is a continuous signal, not a binary bot flag. The Mann–Whitney test on gap scores between the 13-human and 16-agent cohorts yields U = 2.0, p = 0.0006 — the behavioral distributions are well separated.
|
||||
</p>
|
||||
|
||||
<h3 class="title is-4">Stage 3 — Defend</h3>
|
||||
<p>
|
||||
A contamination generator G(α) mixes real human trajectories with synthetic agent trajectories drawn from <em>T̂<sub>A</sub></em> to produce training distributions at any contamination level α ∈ [0, 1]. The pricing policy is trained as a Stackelberg leader against a Wasserstein ambiguity set around the generator's empirical distribution, minimizing worst-case regret over plausible demand shifts. The per-step reward penalizes COI leakage — weighted by <em>f</em>(τ') — while a UX index bounds harm to legitimate users. Sweeps ran across 384 TPU chips (v4, v5e, v6e Trillium) covering six contamination levels and multiple algorithm variants (PPO, A2C, DQN, Q-table).
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
53
docs/mkdocs.yml
Normal file
53
docs/mkdocs.yml
Normal file
@@ -0,0 +1,53 @@
|
||||
site_name: PHANTOM Platform
|
||||
site_description: Operator and research documentation for the PHANTOM dynamic pricing research platform.
|
||||
site_url: https://velocitatem.github.io/PHANTOM/documentation/
|
||||
site_author: Daniel Rösel
|
||||
|
||||
repo_url: https://github.com/velocitatem/PHANTOM
|
||||
repo_name: velocitatem/PHANTOM
|
||||
|
||||
docs_dir: src
|
||||
site_dir: documentation
|
||||
strict: true
|
||||
|
||||
theme:
|
||||
name: material
|
||||
palette:
|
||||
- scheme: default
|
||||
primary: indigo
|
||||
toggle:
|
||||
icon: material/brightness-7
|
||||
name: Switch to dark mode
|
||||
- scheme: slate
|
||||
primary: indigo
|
||||
toggle:
|
||||
icon: material/brightness-4
|
||||
name: Switch to light mode
|
||||
features:
|
||||
- navigation.instant
|
||||
- navigation.tracking
|
||||
- content.code.copy
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
|
||||
nav:
|
||||
- Home: index.md
|
||||
- Setup: platform-setup.md
|
||||
- Business overview: business.md
|
||||
- Architecture: architecture.md
|
||||
- Configuration: configuration.md
|
||||
- Glossary: glossary.md
|
||||
- Roadmap & implementation notes: roadmap.md
|
||||
|
||||
markdown_extensions:
|
||||
- pymdownx.snippets:
|
||||
base_path:
|
||||
- ..
|
||||
- pymdownx.superfences
|
||||
- admonition
|
||||
- tables
|
||||
- toc:
|
||||
permalink: true
|
||||
|
||||
plugins:
|
||||
- search
|
||||
1
docs/requirements.txt
Normal file
1
docs/requirements.txt
Normal file
@@ -0,0 +1 @@
|
||||
mkdocs-material>=9.5,<10
|
||||
30
docs/src/architecture.md
Normal file
30
docs/src/architecture.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Architecture
|
||||
|
||||
## System map
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
U[Human / Agent Browser] --> W[Next.js Web App]
|
||||
W -->|Price requests| P[Pricing Provider]
|
||||
W -->|Interaction events| B[Backend Ingest API]
|
||||
B --> K[Kafka]
|
||||
K --> A[Airflow + Worker Jobs]
|
||||
A --> R[Redis Model Registry]
|
||||
P -->|Session/global prices| W
|
||||
E[Research Engine + Experiments] --> A
|
||||
E --> R
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Event and training path (conceptual)
|
||||
|
||||
1. **Online:** The browser emits events; the backend publishes to **Kafka**; schedulers and workers consume for ETL and model registry updates.
|
||||
2. **Offline:** Notebooks and scripts under `experiments/` transform logs; `**engine/`** runs simulations, training, and benchmarks; artifacts land under paths from `[lib/config.py](https://github.com/velocitatem/PHANTOM/blob/main/lib/config.py)`.
|
||||
3. **Feedback:** Trained or rule-based policies surface through the **pricing provider** to the web app.
|
||||
|
||||
## Where to read more
|
||||
|
||||
- Ports and health checks: [README](https://github.com/velocitatem/PHANTOM/blob/main/README.md) and [Configuration](configuration.md).
|
||||
- Formal notation for sessions, $\hat{q}$, and mixture demand: **Chapter 3 (Methodology)** in the thesis PDF.
|
||||
|
||||
39
docs/src/business.md
Normal file
39
docs/src/business.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Business overview
|
||||
|
||||
Dynamic pricing extracts margin by exploiting the information asymmetry between buyer and seller. When a user browses a flight or hotel across multiple sessions, each interaction accumulates demand signals that push the quoted price upward. That is the mechanism working as intended.
|
||||
|
||||
LLM agents break it. An agent can conduct reconnaissance—across dozens of isolated sessions, at machine speed—and then execute a purchase through a clean session that looks like a first-time visitor. The platform sees a low-engagement session and quotes a floor price. The margin that should have been captured, the **Cost of Information (COI)**, vanishes. At scale this is not a theoretical concern; it is a structural leak in any session-based pricing system.
|
||||
|
||||
**PHANTOM is a research platform for studying and defending against that leak.**
|
||||
|
||||
## Who it is for
|
||||
|
||||
| Role | What they get |
|
||||
|---|---|
|
||||
| Pricing and revenue researchers | A controlled lab with instrumented human and agent sessions, behavioral kernel estimation, and contamination simulation at configurable levels |
|
||||
| Platform engineers evaluating agent risk | A concrete pipeline from behavioral event logs to a per-session agent-probability signal, ready to feed into an existing pricing provider |
|
||||
| RL practitioners | A Distributionally Robust RL gym built on a Wasserstein ambiguity set, with benchmark tiers and sweep tooling out of the box |
|
||||
|
||||
## Core capabilities
|
||||
|
||||
**Behavioral fingerprinting.** PHANTOM logs interaction trajectories at the event level (action, item, timestamp) and fits separate Markov transition kernels for human and agent sessions via MLE. Per-session divergence scores (Δ_H, Δ_A) and a learned agent-probability signal f(τ) are computed on partial trajectories in real time, giving the pricing layer a continuous signal rather than a binary bot flag.
|
||||
|
||||
**Contamination simulation.** The contamination generator G(α) mixes real human trajectories with synthetic agent trajectories at a configurable ratio α. This lets you evaluate pricing robustness across the full spectrum from purely human traffic to fully automated demand, without needing live agent traffic in production.
|
||||
|
||||
**Robust policy training.** The defense gym trains pricing policies against the worst-case demand distribution within a Wasserstein ball around the generator's empirical distribution. The reward function penalizes COI leakage (weighted by agent probability) while bounding UX degradation for legitimate users.
|
||||
|
||||
## The path from logs to defense
|
||||
|
||||
A team: connects their catalog and ingest path → streams interaction events through Kafka → labels or weak-labels sessions → estimates behavioral kernels → varies α in simulation → trains and benchmarks robust policies. The full walkthrough is in [Setup](platform-setup.md).
|
||||
|
||||
## Scope and honest caveats
|
||||
|
||||
This is a **research stack**, not a hosted service:
|
||||
|
||||
- It ships two demo verticals (`hotel`, `airline`); a new catalog requires engineering work on events and reward features.
|
||||
- Kernel estimates are research-grade until validated on your traffic distribution.
|
||||
- There is no built-in compliance layer for regulated pricing markets.
|
||||
|
||||
The thesis PDF contains the formal proofs, the COI erosion theorem, and the full DR-RL formulation. The code operationalizes those constructs—every term in the reward function maps to something computed from your logs.
|
||||
|
||||
**Thesis PDF:** [thesis-latest.pdf](https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf) — Introduction and Chapter 3 cover the problem statement, contributions, and formal model.
|
||||
63
docs/src/configuration.md
Normal file
63
docs/src/configuration.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Configuration reference
|
||||
|
||||
This page condenses tables from `[README.md](https://github.com/velocitatem/PHANTOM/blob/main/README.md)` and points to code. Authoritative env templates: `[.env.example](https://github.com/velocitatem/PHANTOM/blob/main/.env.example)`, `[.env.sweep.example](https://github.com/velocitatem/PHANTOM/blob/main/.env.sweep.example)`.
|
||||
|
||||
## Core runtime (`.env`)
|
||||
|
||||
|
||||
| Variable | Purpose | Typical value |
|
||||
| ------------------------------- | ------------------------------ | ----------------------- |
|
||||
| `STORE_MODE` | Web mode (`hotel` / `airline`) | `hotel` |
|
||||
| `BACKEND_PORT` | Backend API | `5000` |
|
||||
| `PROVIDER_PORT` | Pricing provider | `5001` |
|
||||
| `KAFKA_HOST` | Kafka broker host | `localhost` |
|
||||
| `KAFKA_PORT` | Kafka port | `9092` |
|
||||
| `REDIS_PORT` | Redis port | `6377` |
|
||||
| `REDPANDA_CONSOLE_PORT` | Kafka UI | `8084` (see compose) |
|
||||
| `NEXT_PUBLIC_SUPABASE_URL` | Catalog / data | required for full stack |
|
||||
| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Catalog / data | required |
|
||||
| `AIRFLOW_FERNET_KEY` | Airflow | required |
|
||||
| `AIRFLOW_SECRET_KEY` | Airflow web | required |
|
||||
|
||||
|
||||
Web client validation: `[web/src/lib/config.ts](https://github.com/velocitatem/PHANTOM/blob/main/web/src/lib/config.ts)`.
|
||||
|
||||
## Training / sweeps (`.env.sweep`)
|
||||
|
||||
|
||||
| Variable | Purpose |
|
||||
| --------------- | ----------------------------------------------- |
|
||||
| `WANDB_API_KEY` | Weights & Biases |
|
||||
| `WANDB_ENTITY` | Optional override |
|
||||
| `WANDB_PROJECT` | Project name (default `capstone`) |
|
||||
| `GITHUB_TOKEN` | Bootstrap / workers |
|
||||
| `SWEEP_ID` | Sweep agents (`train.agent`, `benchmark.agent`) |
|
||||
|
||||
|
||||
## Path overrides (`PHANTOM_*`)
|
||||
|
||||
Defined in `[lib/config.py](https://github.com/velocitatem/PHANTOM/blob/main/lib/config.py)`:
|
||||
|
||||
|
||||
| Variable | Default (conceptual) |
|
||||
| ---------------------------- | ----------------------------------- |
|
||||
| `PHANTOM_DATA_DIR` | `data/` |
|
||||
| `PHANTOM_EXPERIMENTS_DIR` | `experiments/` |
|
||||
| `PHANTOM_SIM_RUNS_DIR` | `sim/rl/runs` |
|
||||
| `PHANTOM_MODEL_REGISTRY_DIR` | `data/models` |
|
||||
| `PHANTOM_COLLECTED_DATA_DIR` | `experiments/agents/collected_data` |
|
||||
|
||||
|
||||
## Makefile entrypoints
|
||||
|
||||
|
||||
| Goal | Command |
|
||||
| ---------------- | ------------------------------------------- |
|
||||
| Platform up/down | `make platform.up` / `make platform.down` |
|
||||
| Web dev | `make web.dev` |
|
||||
| Train | `make train` (+ `LOCAL_TRAIN_ARGS`) |
|
||||
| Benchmark | `make benchmark` (+ `LOCAL_BENCHMARK_ARGS`) |
|
||||
| Docs site | `make docs.platform` |
|
||||
|
||||
|
||||
See `make help` for the full list.
|
||||
17
docs/src/glossary.md
Normal file
17
docs/src/glossary.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Glossary
|
||||
|
||||
Short definitions point to the thesis **Terminology** appendix in the [PDF](https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf) for full precision.
|
||||
|
||||
| Term | Meaning (operational) |
|
||||
| --- | --- |
|
||||
| **COI (Cost of Information)** | Expected price premium above a floor under the platform’s policy; thesis KPI for pricing power. |
|
||||
| **Trajectory \(\tau_s\)** | Ordered session events used as the behavioral record. |
|
||||
| **Demand proxy \(\hat{q}\)** | Weighted aggregation of actions—what the platform observes instead of true demand. |
|
||||
| **Contamination \(\alpha\)** | Agent share in the mixture demand model (thesis); not automatically “% of bots” in raw logs. |
|
||||
| **Transition kernel \(\hat{\mathcal{T}}\)** | MLE Markov model over behavioral states / events for class \(H\) or \(A\). |
|
||||
| **\(\Delta_H,\Delta_A\)** | Divergence scores vs human/agent prototypes (thesis notation). |
|
||||
| **\(f(\tau)\)** | Weak agent probability from trajectory (implementation: `engine/lib/coi.py`). |
|
||||
| **\(\mathcal{G}(\alpha)\)** | Contamination generator: synthetic agent trajectories to reach mixture level \(\alpha\). |
|
||||
| **DR-RL** | Distributionally robust reinforcement learning training narrative in the thesis. |
|
||||
| **Ambiguity set / Wasserstein** | Robust optimization neighborhood around an empirical demand law. |
|
||||
| **Kappa–Lambda architecture** | Thesis term for streaming (online) vs batch/offline learning loops. |
|
||||
23
docs/src/index.md
Normal file
23
docs/src/index.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# PHANTOM
|
||||
|
||||
LLM agents are quietly eroding the pricing power of dynamic pricing systems. They conduct reconnaissance across isolated sessions at machine speed and execute purchases through clean sessions that quote floor prices. The margin that should have accumulated never does.
|
||||
|
||||
PHANTOM is a research platform for measuring, simulating, and defending against that erosion. It provides behavioral fingerprinting of human vs agent sessions, a contamination generator for controlled experiments, and a Distributionally Robust RL gym for training pricing policies that hold up under automated demand.
|
||||
|
||||
---
|
||||
|
||||
## Where to start
|
||||
|
||||
| Document | What it covers |
|
||||
| --- | --- |
|
||||
| [Business overview](business.md) | The problem, capabilities, and who this is for |
|
||||
| [Setup](platform-setup.md) | Full bring-up: Docker stack, ingest, behavioral kernels, contamination, RL training |
|
||||
| [Architecture](architecture.md) | Service map and data flow |
|
||||
| [Configuration reference](configuration.md) | Env vars, paths, and Makefile targets |
|
||||
| [Roadmap & notes](roadmap.md) | What is turnkey vs research-grade |
|
||||
|
||||
## Key references
|
||||
|
||||
- **Thesis PDF:** [thesis-latest.pdf](https://pub-d5b94a3c29fd40c6b3881946e463fdb7.r2.dev/thesis-latest.pdf) — formal model, COI erosion proof, DR-RL formulation
|
||||
- **Repo root:** [`SETUP.md`](https://github.com/velocitatem/PHANTOM/blob/main/SETUP.md) | [`README.md`](https://github.com/velocitatem/PHANTOM/blob/main/README.md)
|
||||
- **Academic landing page:** [velocitatem.github.io/PHANTOM/](https://velocitatem.github.io/PHANTOM/)
|
||||
5
docs/src/platform-setup.md
Normal file
5
docs/src/platform-setup.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Setup
|
||||
|
||||
The content below is included from the repository root file `SETUP.md` (single source of truth: platform bring-up, kernels, contamination, RL training, and thesis pointers by chapter).
|
||||
|
||||
--8<-- "SETUP.md"
|
||||
26
docs/src/roadmap.md
Normal file
26
docs/src/roadmap.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# Roadmap & implementation notes
|
||||
|
||||
This page is the **honesty pass** from the documentation plan: what clients can expect today versus what remains research-heavy.
|
||||
|
||||
## Turnkey in this repository
|
||||
|
||||
- **Local stack:** Docker Compose services for backend, Kafka, Redis, Airflow, pricing provider, etc.; Next.js via `make web.dev` (see [Platform setup](platform-setup.md)).
|
||||
- **Demo verticals:** `hotel` and `airline` storefront modes.
|
||||
- **Engine:** Benchmarks and training entrypoints (`make train`, `make benchmark`), KL-based agent scoring in `[engine/lib/coi.py](https://github.com/velocitatem/PHANTOM/blob/main/engine/lib/coi.py)`, simulator mixing in `[engine/engine.py](https://github.com/velocitatem/PHANTOM/blob/main/engine/engine.py)`.
|
||||
- **Orchestration hooks:** Ray/TPU scripts (`submit_ray_job.sh`, `make tpu.ray.`*), W&B sweep agents, Docker trainer publish target.
|
||||
|
||||
## Usually requires custom engineering
|
||||
|
||||
- **Non-Supabase catalog** or checkout flows without adapting the web + backend contracts.
|
||||
- **Production SLAs** on Kafka, schema registry, or PII boundaries for your jurisdiction.
|
||||
- **Tight coupling** to a legacy pricing engine without mapping its API to the provider abstraction.
|
||||
|
||||
## Thesis vs code
|
||||
|
||||
- The **thesis** states theorems and constructions (COI erosion, kernels, \mathcal{G}(\alpha), DR-RL).
|
||||
- The **codebase** implements a **subset** of that story for experiments: verify CLI flags and simulator assumptions before claiming 1:1 equivalence with every equation.
|
||||
- **Catalog-scale kernel expansion** is discussed in **Chapter 3** with explicit validation caveats—do not assume row-stochasticity and Markov structure are automatically preserved at full product cardinality without review.
|
||||
|
||||
## Suggested client messaging
|
||||
|
||||
Position PHANTOM as a **reproducible research and evaluation stack** for agent-aware pricing, with a path to custom integration—not as a black-box “turn on anti-agent pricing” product without data and engineering investment.
|
||||
1015
docs/static/css/index.css
vendored
1015
docs/static/css/index.css
vendored
File diff suppressed because it is too large
Load Diff
4
docs/static/images/banner.svg
vendored
4
docs/static/images/banner.svg
vendored
@@ -41,7 +41,7 @@
|
||||
|
||||
<!-- Markers p and E[P] -->
|
||||
<line x1="150" y1="340" x2="150" y2="160" stroke="#E37862" stroke-width="2" stroke-dasharray="6,4"/>
|
||||
<text x="150" y="375" font-family="Georgia" font-style="italic" font-size="22" fill="#E37862" text-anchor="middle">p</text>
|
||||
<text x="150" y="375" font-family="Georgia" font-style="italic" font-size="22" fill="#E37862" text-anchor="middle"><tspan text-decoration="underline">p</tspan></text>
|
||||
|
||||
<line x1="260" y1="340" x2="260" y2="160" stroke="#85B589" stroke-width="2" stroke-dasharray="6,4"/>
|
||||
<text x="260" y="375" font-family="Georgia" font-style="italic" font-size="22" fill="#85B589" text-anchor="middle">E[P]</text>
|
||||
@@ -49,7 +49,7 @@
|
||||
<!-- COI Annotation -->
|
||||
<line x1="150" y1="150" x2="260" y2="150" stroke="#E37862" stroke-width="2" marker-start="url(#arrow)" marker-end="url(#arrow)"/>
|
||||
<text x="310" y="138" font-size="16" fill="#E37862" text-anchor="middle">average information rent</text>
|
||||
<text x="310" y="118" font-family="Georgia" font-style="italic" font-size="22" fill="#E37862" font-weight="bold" text-anchor="middle">COI := E[P] - p</text>
|
||||
<text x="310" y="118" font-family="Georgia" font-style="italic" font-size="22" fill="#E37862" font-weight="bold" text-anchor="middle">COI = E[P] - <tspan text-decoration="underline">p</tspan></text>
|
||||
</g>
|
||||
|
||||
<!-- Bottom: Agent Saturation -->
|
||||
|
||||
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
0
engine/__init__.py
Normal file
0
engine/__init__.py
Normal file
@@ -15,6 +15,10 @@ def make_env(cfg: Mapping[str, Any]):
|
||||
n_products=int(cfg["n_products"]),
|
||||
alpha=float(cfg["alpha"]),
|
||||
N=int(cfg["N"]),
|
||||
agent_params=(
|
||||
float(cfg.get("agent_mu", 45.0)),
|
||||
float(cfg.get("agent_std", 15.0)),
|
||||
),
|
||||
price_bounds=(float(cfg["price_low"]), float(cfg["price_high"])),
|
||||
lambda_coi=float(cfg["lambda_coi"]),
|
||||
robust_radius=float(cfg["robust_radius"]),
|
||||
@@ -50,6 +54,9 @@ def _evaluate_env(agent: Any, env: Any, episodes: int) -> dict[str, float]:
|
||||
coi_levels: list[float] = []
|
||||
coi_leakages: list[float] = []
|
||||
volatilities: list[float] = []
|
||||
upward_volatilities: list[float] = []
|
||||
supra_shares: list[float] = []
|
||||
supra_penalties: list[float] = []
|
||||
agent_probs: list[float] = []
|
||||
|
||||
for _ in range(int(episodes)):
|
||||
@@ -61,6 +68,9 @@ def _evaluate_env(agent: Any, env: Any, episodes: int) -> dict[str, float]:
|
||||
ep_coi = 0.0
|
||||
ep_coi_leakage = 0.0
|
||||
ep_volatility = 0.0
|
||||
ep_upward_volatility = 0.0
|
||||
ep_supra_share = 0.0
|
||||
ep_supra_penalty = 0.0
|
||||
ep_agent_prob = 0.0
|
||||
steps = 0
|
||||
|
||||
@@ -74,6 +84,15 @@ def _evaluate_env(agent: Any, env: Any, episodes: int) -> dict[str, float]:
|
||||
ep_coi += float(econ.get("coi_level", 0.0))
|
||||
ep_coi_leakage += float(econ.get("coi_leakage", 0.0))
|
||||
ep_volatility += float(econ.get("volatility", 0.0))
|
||||
ep_upward_volatility += float(
|
||||
info.get("upward_volatility", econ.get("upward_volatility", 0.0))
|
||||
)
|
||||
ep_supra_share += float(
|
||||
info.get("supra_share", econ.get("supra_share", 0.0))
|
||||
)
|
||||
ep_supra_penalty += float(
|
||||
info.get("supra_penalty", econ.get("supra_penalty", 0.0))
|
||||
)
|
||||
ep_agent_prob += float(econ.get("agent_prob", info.get("agent_prob", 0.0)))
|
||||
steps += 1
|
||||
|
||||
@@ -84,6 +103,9 @@ def _evaluate_env(agent: Any, env: Any, episodes: int) -> dict[str, float]:
|
||||
coi_levels.append(ep_coi / denom)
|
||||
coi_leakages.append(ep_coi_leakage / denom)
|
||||
volatilities.append(ep_volatility / denom)
|
||||
upward_volatilities.append(ep_upward_volatility / denom)
|
||||
supra_shares.append(ep_supra_share / denom)
|
||||
supra_penalties.append(ep_supra_penalty / denom)
|
||||
agent_probs.append(ep_agent_prob / denom)
|
||||
|
||||
return {
|
||||
@@ -95,6 +117,13 @@ def _evaluate_env(agent: Any, env: Any, episodes: int) -> dict[str, float]:
|
||||
"eval/coi_level_mean": float(np.mean(coi_levels)) if coi_levels else 0.0,
|
||||
"eval/coi_leakage_mean": float(np.mean(coi_leakages)) if coi_leakages else 0.0,
|
||||
"eval/volatility_mean": float(np.mean(volatilities)) if volatilities else 0.0,
|
||||
"eval/upward_volatility_mean": (
|
||||
float(np.mean(upward_volatilities)) if upward_volatilities else 0.0
|
||||
),
|
||||
"eval/supra_share_mean": float(np.mean(supra_shares)) if supra_shares else 0.0,
|
||||
"eval/supra_penalty_mean": (
|
||||
float(np.mean(supra_penalties)) if supra_penalties else 0.0
|
||||
),
|
||||
"eval/agent_prob_mean": float(np.mean(agent_probs)) if agent_probs else 0.0,
|
||||
}
|
||||
|
||||
@@ -128,15 +157,15 @@ def evaluate(
|
||||
shifted_env.close()
|
||||
shifted_rows.append((tag, alpha, shifted_metrics))
|
||||
|
||||
metrics["eval/robust_alpha_low"] = low_alpha
|
||||
metrics["eval/robust_alpha_high"] = high_alpha
|
||||
metrics["eval/robust_reward_worst"] = float(
|
||||
metrics["eval/stress_alpha_low"] = low_alpha
|
||||
metrics["eval/stress_alpha_high"] = high_alpha
|
||||
metrics["eval/stress_reward_worst"] = float(
|
||||
min(row[2]["eval/reward_mean"] for row in shifted_rows)
|
||||
)
|
||||
metrics["eval/robust_revenue_worst"] = float(
|
||||
metrics["eval/stress_revenue_worst"] = float(
|
||||
min(row[2]["eval/revenue_mean"] for row in shifted_rows)
|
||||
)
|
||||
metrics["eval/robust_coi_leakage_worst"] = float(
|
||||
metrics["eval/stress_coi_leakage_worst"] = float(
|
||||
max(row[2]["eval/coi_leakage_mean"] for row in shifted_rows)
|
||||
)
|
||||
for tag, alpha, shifted_metrics in shifted_rows:
|
||||
|
||||
@@ -80,7 +80,11 @@ def train_qtable(
|
||||
"train/global_step": int(steps),
|
||||
}
|
||||
if wandb_live:
|
||||
wandb.log(dict(event), step=step_offset + int(steps))
|
||||
try:
|
||||
wandb.log(dict(event), step=step_offset + int(steps))
|
||||
except Exception:
|
||||
wandb_live = False
|
||||
train_events.append(event)
|
||||
else:
|
||||
train_events.append(event)
|
||||
if console_progress:
|
||||
@@ -113,7 +117,11 @@ def train_qtable(
|
||||
"train/global_step": int(steps),
|
||||
}
|
||||
if wandb_live:
|
||||
wandb.log(dict(tail_event), step=step_offset + int(steps))
|
||||
try:
|
||||
wandb.log(dict(tail_event), step=step_offset + int(steps))
|
||||
except Exception:
|
||||
wandb_live = False
|
||||
train_events.append(tail_event)
|
||||
else:
|
||||
train_events.append(tail_event)
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from ..lib.callbacks import MetricsCallback
|
||||
from ..lib.callbacks import EvalMetricsCallback, MetricsCallback
|
||||
from ..wandb_checkpoint import checkpoint_artifact_name, log_checkpoint_file
|
||||
from .common import evaluate, make_env
|
||||
|
||||
|
||||
@@ -117,7 +119,6 @@ def build_model(cfg: Mapping[str, Any], env: Any):
|
||||
|
||||
def train_sb3(cfg: Mapping[str, Any]) -> tuple[object, dict[str, Any]]:
|
||||
try:
|
||||
from stable_baselines3.common.callbacks import EvalCallback
|
||||
from stable_baselines3.common.monitor import Monitor
|
||||
except ImportError as exc:
|
||||
raise ImportError("stable-baselines3 is required for SB3 models") from exc
|
||||
@@ -144,20 +145,20 @@ def train_sb3(cfg: Mapping[str, Any]) -> tuple[object, dict[str, Any]]:
|
||||
pass
|
||||
|
||||
metrics_callback = MetricsCallback(
|
||||
log_histograms=False,
|
||||
log_histograms=True,
|
||||
log_freq=int(cfg["log_freq"]),
|
||||
hist_freq=int(cfg.get("hist_freq", 500)),
|
||||
step_offset=int(cfg.get("wandb_step_offset", 0)),
|
||||
)
|
||||
callbacks = [metrics_callback]
|
||||
callbacks.append(
|
||||
EvalCallback(
|
||||
eval_env,
|
||||
eval_freq=int(cfg["eval_freq"]),
|
||||
n_eval_episodes=int(cfg["eval_episodes"]),
|
||||
deterministic=True,
|
||||
verbose=0,
|
||||
)
|
||||
eval_callback = EvalMetricsCallback(
|
||||
eval_env,
|
||||
eval_freq=int(cfg["eval_freq"]),
|
||||
n_eval_episodes=int(cfg["eval_episodes"]),
|
||||
step_offset=int(cfg.get("wandb_step_offset", 0)),
|
||||
deterministic=True,
|
||||
verbose=0,
|
||||
)
|
||||
callbacks = [metrics_callback, eval_callback]
|
||||
|
||||
target_steps = int(cfg["total_timesteps"])
|
||||
remaining_steps = max(0, target_steps - int(getattr(model, "num_timesteps", 0)))
|
||||
@@ -173,6 +174,29 @@ def train_sb3(cfg: Mapping[str, Any]) -> tuple[object, dict[str, Any]]:
|
||||
model_path = model_dir / f"phantom_{cfg['algo']}"
|
||||
model.save(str(model_path))
|
||||
|
||||
artifact_name = checkpoint_artifact_name(
|
||||
cfg,
|
||||
backend="sb3",
|
||||
sweep_id=os.getenv("WANDB_SWEEP_ID"),
|
||||
)
|
||||
artifact_logged = False
|
||||
try:
|
||||
artifact_logged = bool(
|
||||
log_checkpoint_file(
|
||||
artifact_name,
|
||||
file_path=model_path.with_suffix(".zip"),
|
||||
artifact_file_name="model.zip",
|
||||
metadata={
|
||||
"algo": str(cfg.get("algo", "ppo")),
|
||||
"backend": "sb3",
|
||||
"seed": int(cfg.get("seed", 0)),
|
||||
"step": int(getattr(model, "num_timesteps", 0)),
|
||||
},
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
artifact_logged = False
|
||||
|
||||
metrics: dict[str, Any] = evaluate(
|
||||
model,
|
||||
eval_env,
|
||||
@@ -181,7 +205,12 @@ def train_sb3(cfg: Mapping[str, Any]) -> tuple[object, dict[str, Any]]:
|
||||
)
|
||||
metrics["train/global_step"] = int(model.num_timesteps)
|
||||
metrics["model/path"] = str(model_path.with_suffix(".zip"))
|
||||
metrics["_train_events"] = list(metrics_callback.events)
|
||||
metrics["model/artifact_name"] = str(artifact_name)
|
||||
metrics["model/artifact_logged"] = float(artifact_logged)
|
||||
metrics["_train_events"] = sorted(
|
||||
[*metrics_callback.events, *eval_callback.events],
|
||||
key=lambda event: int(event.get("train/global_step", 0)),
|
||||
)
|
||||
|
||||
env.close()
|
||||
eval_env.close()
|
||||
|
||||
@@ -1,12 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
# clear stale TPU locks on startup
|
||||
if os.path.exists("/dev/accel0"):
|
||||
try:
|
||||
subprocess.run(
|
||||
["rm", "-f", "/tmp/.libtpu_lockfile", "/tmp/libtpu_lockfile"],
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
import jax
|
||||
|
||||
jax.config.update("jax_threefry_partitionable", True)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
@@ -25,6 +45,10 @@ def _log(message: str) -> None:
|
||||
logger.info(message)
|
||||
|
||||
|
||||
def _wandb_run_active() -> bool:
|
||||
return bool(HAS_WANDB and getattr(wandb, "run", None) is not None)
|
||||
|
||||
|
||||
def _parse_list(raw: str) -> list[str]:
|
||||
return [x.strip().lower() for x in str(raw).split(",") if x.strip()]
|
||||
|
||||
@@ -41,6 +65,10 @@ def _truthy(value: str | bool | None) -> bool:
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _mode_label_from_baseline(is_baseline: bool) -> str:
|
||||
return "baseline" if bool(is_baseline) else "defended"
|
||||
|
||||
|
||||
def _action(policy, obs: np.ndarray):
|
||||
out = policy.predict(obs, deterministic=True)
|
||||
action = out[0] if isinstance(out, tuple) else out
|
||||
@@ -146,7 +174,7 @@ def _log_train_events(
|
||||
alpha: float,
|
||||
step_offset: int,
|
||||
) -> int:
|
||||
if not (HAS_WANDB and wandb.run is not None):
|
||||
if not _wandb_run_active():
|
||||
return int(step_offset)
|
||||
if not events:
|
||||
return int(step_offset)
|
||||
@@ -167,11 +195,14 @@ def _log_train_events(
|
||||
"run.kind": "benchmark",
|
||||
"runtime/backend": tier_name,
|
||||
"study/mode": mode_label,
|
||||
"study/no_robust": float(mode_label == "no_robust"),
|
||||
"study/baseline_mode": float(mode_label == "baseline"),
|
||||
"study/alpha": float(alpha),
|
||||
}
|
||||
)
|
||||
wandb.log(payload, step=cursor + rel_step)
|
||||
try:
|
||||
wandb.log(payload, step=cursor + rel_step)
|
||||
except Exception:
|
||||
return int(step_offset)
|
||||
max_rel = max(max(1, int(evt.get("train/global_step", 0))) for evt in ordered)
|
||||
return cursor + max_rel + 1
|
||||
|
||||
@@ -183,6 +214,7 @@ def run_benchmark(
|
||||
n_episodes: int,
|
||||
mode_label: str,
|
||||
step_cursor_start: int = 0,
|
||||
eval_alpha_values: list[float] | None = None,
|
||||
):
|
||||
from .backends.common import make_env
|
||||
|
||||
@@ -219,62 +251,80 @@ def run_benchmark(
|
||||
"dqn",
|
||||
}:
|
||||
wandb_step_cursor += max(1, int(cfg.get("total_timesteps", 1))) + 1
|
||||
env = make_env({**cfg, "alpha": float(alpha)})
|
||||
eps = [_run_eval_episode(env, policy) for _ in range(int(n_episodes))]
|
||||
env.close()
|
||||
|
||||
row = {
|
||||
"tier": tier_name,
|
||||
"mode": mode_label,
|
||||
"alpha": float(alpha),
|
||||
"episodes": int(n_episodes),
|
||||
"mean_reward": float(np.mean([e["reward"] for e in eps])),
|
||||
"mean_revenue": float(np.mean([e["revenue"] for e in eps])),
|
||||
"mean_margin": float(np.mean([e["mean_margin"] for e in eps])),
|
||||
"mean_coi": float(np.mean([e["mean_coi"] for e in eps])),
|
||||
"std_revenue": float(np.std([e["revenue"] for e in eps])),
|
||||
}
|
||||
row["objective_score"] = row["mean_reward"]
|
||||
rows.append(row)
|
||||
_log(
|
||||
f"[{run_index}/{total_runs}] alpha={float(alpha):.2f} tier={tier_name}: "
|
||||
f"reward={row['mean_reward']:.3f} revenue={row['mean_revenue']:.3f} "
|
||||
f"coi={row['mean_coi']:.4f} score={row['objective_score']:.3f}"
|
||||
eval_targets = (
|
||||
[float(value) for value in eval_alpha_values]
|
||||
if eval_alpha_values
|
||||
else [float(alpha)]
|
||||
)
|
||||
for eval_alpha in eval_targets:
|
||||
env = make_env({**cfg, "alpha": float(eval_alpha)})
|
||||
eps = [_run_eval_episode(env, policy) for _ in range(int(n_episodes))]
|
||||
env.close()
|
||||
|
||||
max_len = max((len(e["price_trace"]) for e in eps), default=0)
|
||||
step_means = []
|
||||
for step in range(max_len):
|
||||
vals = [
|
||||
e["price_trace"][step] for e in eps if step < len(e["price_trace"])
|
||||
]
|
||||
step_means.append(float(np.mean(vals)) if vals else np.nan)
|
||||
traces.append(
|
||||
{
|
||||
row = {
|
||||
"tier": tier_name,
|
||||
"alpha": float(alpha),
|
||||
"mean_price_trace": step_means,
|
||||
"mode": mode_label,
|
||||
"alpha": float(eval_alpha),
|
||||
"train_alpha": float(alpha),
|
||||
"eval_alpha": float(eval_alpha),
|
||||
"episodes": int(n_episodes),
|
||||
"mean_reward": float(np.mean([e["reward"] for e in eps])),
|
||||
"mean_revenue": float(np.mean([e["revenue"] for e in eps])),
|
||||
"mean_margin": float(np.mean([e["mean_margin"] for e in eps])),
|
||||
"mean_coi": float(np.mean([e["mean_coi"] for e in eps])),
|
||||
"std_revenue": float(np.std([e["revenue"] for e in eps])),
|
||||
}
|
||||
)
|
||||
|
||||
if HAS_WANDB and wandb.run is not None:
|
||||
wandb.log(
|
||||
{
|
||||
"run.kind": "benchmark",
|
||||
"runtime/backend": tier_name,
|
||||
"study/mode": mode_label,
|
||||
"study/no_robust": float(mode_label == "no_robust"),
|
||||
"study/alpha": float(alpha),
|
||||
"eval/reward_mean": row["mean_reward"],
|
||||
"eval/revenue_mean": row["mean_revenue"],
|
||||
"eval/margin_mean": row["mean_margin"],
|
||||
"eval/coi_level_mean": row["mean_coi"],
|
||||
"objective/score": row["objective_score"],
|
||||
"objective/coi_preserved": row["mean_coi"],
|
||||
},
|
||||
step=wandb_step_cursor,
|
||||
row["objective_score"] = row["mean_reward"]
|
||||
rows.append(row)
|
||||
_log(
|
||||
f"[{run_index}/{total_runs}] train_alpha={float(alpha):.2f} "
|
||||
f"eval_alpha={float(eval_alpha):.2f} tier={tier_name}: "
|
||||
f"reward={row['mean_reward']:.3f} revenue={row['mean_revenue']:.3f} "
|
||||
f"coi={row['mean_coi']:.4f} score={row['objective_score']:.3f}"
|
||||
)
|
||||
wandb_step_cursor += 1
|
||||
|
||||
max_len = max((len(e["price_trace"]) for e in eps), default=0)
|
||||
step_means = []
|
||||
for step in range(max_len):
|
||||
vals = [
|
||||
e["price_trace"][step]
|
||||
for e in eps
|
||||
if step < len(e["price_trace"])
|
||||
]
|
||||
step_means.append(float(np.mean(vals)) if vals else np.nan)
|
||||
traces.append(
|
||||
{
|
||||
"tier": tier_name,
|
||||
"alpha": float(eval_alpha),
|
||||
"train_alpha": float(alpha),
|
||||
"eval_alpha": float(eval_alpha),
|
||||
"mean_price_trace": step_means,
|
||||
}
|
||||
)
|
||||
|
||||
if _wandb_run_active():
|
||||
try:
|
||||
wandb.log(
|
||||
{
|
||||
"run.kind": "benchmark",
|
||||
"runtime/backend": tier_name,
|
||||
"study/mode": mode_label,
|
||||
"study/baseline_mode": float(mode_label == "baseline"),
|
||||
"study/alpha": float(eval_alpha),
|
||||
"study/train_alpha": float(alpha),
|
||||
"study/eval_alpha": float(eval_alpha),
|
||||
"eval/reward_mean": row["mean_reward"],
|
||||
"eval/revenue_mean": row["mean_revenue"],
|
||||
"eval/margin_mean": row["mean_margin"],
|
||||
"eval/coi_level_mean": row["mean_coi"],
|
||||
"objective/score": row["objective_score"],
|
||||
"objective/coi_preserved": row["mean_coi"],
|
||||
},
|
||||
step=wandb_step_cursor,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
wandb_step_cursor += 1
|
||||
|
||||
return pd.DataFrame(rows), traces, int(wandb_step_cursor)
|
||||
|
||||
@@ -358,7 +408,7 @@ def _run_with_args(args, compare_robust_override: bool | None = None):
|
||||
if compare_robust_override is not None
|
||||
else _truthy(os.environ.get("PHANTOM_BENCHMARK_COMPARE_ROBUST"))
|
||||
)
|
||||
robust_modes = [False, True] if compare_robust else [bool(args.no_robust)]
|
||||
baseline_modes = [False, True] if compare_robust else [bool(args.no_robust)]
|
||||
|
||||
base_overrides = {
|
||||
"seed": args.seed,
|
||||
@@ -369,6 +419,7 @@ def _run_with_args(args, compare_robust_override: bool | None = None):
|
||||
"robust_radius": args.robust_radius,
|
||||
"robust_points": args.robust_points,
|
||||
"robust_rollouts": args.robust_rollouts,
|
||||
"margin_floor": args.margin_floor,
|
||||
"eta_ux": args.eta_ux,
|
||||
"reward_profit_weight": args.reward_profit_weight,
|
||||
"price_low": args.price_low,
|
||||
@@ -385,12 +436,20 @@ def _run_with_args(args, compare_robust_override: bool | None = None):
|
||||
}
|
||||
tiers = _parse_list(args.tiers)
|
||||
alpha_values = _parse_float_list(args.alpha_values)
|
||||
eval_alpha_values = (
|
||||
_parse_float_list(args.eval_alpha_values)
|
||||
if str(getattr(args, "eval_alpha_values", "")).strip()
|
||||
else []
|
||||
)
|
||||
_log(
|
||||
"starting run "
|
||||
+ json.dumps(
|
||||
{
|
||||
"tiers": tiers,
|
||||
"alpha_values": alpha_values,
|
||||
"eval_alpha_values": (
|
||||
eval_alpha_values if eval_alpha_values else alpha_values
|
||||
),
|
||||
"episodes": int(args.episodes),
|
||||
"total_timesteps": int(args.total_timesteps),
|
||||
"device": str(args.device),
|
||||
@@ -401,14 +460,14 @@ def _run_with_args(args, compare_robust_override: bool | None = None):
|
||||
all_frames: list[pd.DataFrame] = []
|
||||
all_traces: list[dict] = []
|
||||
wandb_step_cursor = 0
|
||||
for no_robust in robust_modes:
|
||||
for baseline_mode in baseline_modes:
|
||||
overrides = dict(base_overrides)
|
||||
overrides["no_robust"] = bool(no_robust)
|
||||
overrides["baseline_mode"] = bool(baseline_mode)
|
||||
cfg = TrainSpec.from_flat(
|
||||
{k: v for k, v in overrides.items() if v is not None}
|
||||
).to_flat_dict()
|
||||
cfg["linear_warmup_steps"] = int(args.linear_warmup_steps)
|
||||
mode_label = "no_robust" if no_robust else "robust"
|
||||
mode_label = _mode_label_from_baseline(bool(baseline_mode))
|
||||
_log(f"mode={mode_label}: begin")
|
||||
df_mode, traces_mode, wandb_step_cursor = run_benchmark(
|
||||
cfg,
|
||||
@@ -417,6 +476,7 @@ def _run_with_args(args, compare_robust_override: bool | None = None):
|
||||
args.episodes,
|
||||
mode_label=mode_label,
|
||||
step_cursor_start=wandb_step_cursor,
|
||||
eval_alpha_values=eval_alpha_values,
|
||||
)
|
||||
_log(f"mode={mode_label}: complete ({len(df_mode)} rows)")
|
||||
for trace in traces_mode:
|
||||
@@ -429,7 +489,7 @@ def _run_with_args(args, compare_robust_override: bool | None = None):
|
||||
|
||||
out_dir = Path(args.output_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
|
||||
csv_path = out_dir / f"benchmark_{stamp}.csv"
|
||||
trace_path = out_dir / f"benchmark_traces_{stamp}.json"
|
||||
df.to_csv(csv_path, index=False)
|
||||
@@ -445,7 +505,7 @@ def _run_with_args(args, compare_robust_override: bool | None = None):
|
||||
+ json.dumps(
|
||||
{
|
||||
"tier": best["tier"],
|
||||
"mode": best.get("mode", "robust"),
|
||||
"mode": best.get("mode", "defended"),
|
||||
"alpha": float(best["alpha"]),
|
||||
"objective_score": float(best["objective_score"]),
|
||||
"mean_revenue": float(best["mean_revenue"]),
|
||||
@@ -466,6 +526,7 @@ def run_cli(raw_args: list[str] | None = None):
|
||||
parser.add_argument("--project", default="capstone")
|
||||
parser.add_argument("--tiers", default="static,surge,linear,qtable,ppo")
|
||||
parser.add_argument("--alpha-values", default="0.0,0.3,0.6")
|
||||
parser.add_argument("--eval-alpha-values", default="")
|
||||
parser.add_argument("--episodes", type=int, default=10)
|
||||
parser.add_argument("--output-dir", default="engine/studies/results")
|
||||
parser.add_argument("--seed", type=int, default=42)
|
||||
@@ -476,6 +537,7 @@ def run_cli(raw_args: list[str] | None = None):
|
||||
parser.add_argument("--robust-radius", type=float, default=0.15)
|
||||
parser.add_argument("--robust-points", type=int, default=5)
|
||||
parser.add_argument("--robust-rollouts", type=int, default=1)
|
||||
parser.add_argument("--margin-floor", type=float, default=0.85)
|
||||
parser.add_argument("--eta-ux", type=float, default=0.5)
|
||||
parser.add_argument("--reward-profit-weight", type=float, default=1.0)
|
||||
parser.add_argument("--price-low", type=float, default=10.0)
|
||||
@@ -509,35 +571,47 @@ def run_cli(raw_args: list[str] | None = None):
|
||||
key_to_attr = {
|
||||
"tiers": "tiers",
|
||||
"alpha_values": "alpha_values",
|
||||
"eval_alpha_values": "eval_alpha_values",
|
||||
"episodes": "episodes",
|
||||
"total_timesteps": "total_timesteps",
|
||||
"lambda_coi": "lambda_coi",
|
||||
"robust_radius": "robust_radius",
|
||||
"robust_points": "robust_points",
|
||||
"robust_rollouts": "robust_rollouts",
|
||||
"ambiguity_radius": "robust_radius",
|
||||
"ambiguity_points": "robust_points",
|
||||
"ambiguity_rollouts": "robust_rollouts",
|
||||
"eta_ux": "eta_ux",
|
||||
"reward_profit_weight": "reward_profit_weight",
|
||||
"learning_rate": "learning_rate",
|
||||
"batch_size": "batch_size",
|
||||
"n_steps": "n_steps",
|
||||
"baseline_mode": "no_robust",
|
||||
"no_robust": "no_robust",
|
||||
"margin_floor": "margin_floor",
|
||||
"device": "device",
|
||||
}
|
||||
for key in (
|
||||
"tiers",
|
||||
"alpha_values",
|
||||
"eval_alpha_values",
|
||||
"episodes",
|
||||
"total_timesteps",
|
||||
"lambda_coi",
|
||||
"robust_radius",
|
||||
"robust_points",
|
||||
"robust_rollouts",
|
||||
"ambiguity_radius",
|
||||
"ambiguity_points",
|
||||
"ambiguity_rollouts",
|
||||
"eta_ux",
|
||||
"reward_profit_weight",
|
||||
"learning_rate",
|
||||
"batch_size",
|
||||
"n_steps",
|
||||
"baseline_mode",
|
||||
"no_robust",
|
||||
"margin_floor",
|
||||
"device",
|
||||
):
|
||||
if key in wandb.config:
|
||||
@@ -560,18 +634,18 @@ def run_cli(raw_args: list[str] | None = None):
|
||||
|
||||
tiers = _parse_list(args.tiers)
|
||||
alpha_values = _parse_float_list(args.alpha_values)
|
||||
run_stamp = datetime.now(UTC).strftime("%m%d-%H%M%S")
|
||||
run_stamp = datetime.now(timezone.utc).strftime("%m%d-%H%M%S")
|
||||
compare_enabled = _truthy(os.environ.get("PHANTOM_BENCHMARK_COMPARE_ROBUST"))
|
||||
compare_tag = "robust-compare" if compare_enabled else "single-mode"
|
||||
compare_tag = "defended-compare" if compare_enabled else "single-mode"
|
||||
modes = (
|
||||
[("no_robust", True), ("robust", False)]
|
||||
[("baseline", True), ("defended", False)]
|
||||
if compare_enabled
|
||||
else [("no_robust" if bool(args.no_robust) else "robust", bool(args.no_robust))]
|
||||
else [(_mode_label_from_baseline(bool(args.no_robust)), bool(args.no_robust))]
|
||||
)
|
||||
|
||||
run_idx = 0
|
||||
for tier in tiers:
|
||||
for mode_label, no_robust in modes:
|
||||
for mode_label, baseline_mode in modes:
|
||||
for alpha in alpha_values:
|
||||
run_idx += 1
|
||||
alpha_token = (
|
||||
@@ -580,7 +654,7 @@ def run_cli(raw_args: list[str] | None = None):
|
||||
tier_args = argparse.Namespace(**vars(args))
|
||||
tier_args.tiers = tier
|
||||
tier_args.alpha_values = str(float(alpha))
|
||||
tier_args.no_robust = bool(no_robust)
|
||||
tier_args.no_robust = bool(baseline_mode)
|
||||
run = wandb.init(
|
||||
project=args.project,
|
||||
name=(
|
||||
@@ -597,16 +671,19 @@ def run_cli(raw_args: list[str] | None = None):
|
||||
"run.kind": "benchmark",
|
||||
"runtime/backend": tier,
|
||||
"study/mode": mode_label,
|
||||
"study/no_robust": float(no_robust),
|
||||
"study/baseline_mode": float(baseline_mode),
|
||||
"study/alpha": float(alpha),
|
||||
"tiers": tier,
|
||||
"alpha_values": str(float(alpha)),
|
||||
"eval_alpha_values": args.eval_alpha_values,
|
||||
"episodes": args.episodes,
|
||||
"total_timesteps": args.total_timesteps,
|
||||
"lambda_coi": args.lambda_coi,
|
||||
"robust_radius": args.robust_radius,
|
||||
"robust_points": args.robust_points,
|
||||
"robust_rollouts": args.robust_rollouts,
|
||||
"ambiguity_radius": args.robust_radius,
|
||||
"ambiguity_points": args.robust_points,
|
||||
"ambiguity_rollouts": args.robust_rollouts,
|
||||
"margin_floor": args.margin_floor,
|
||||
"baseline_mode": float(baseline_mode),
|
||||
"eta_ux": args.eta_ux,
|
||||
"reward_profit_weight": args.reward_profit_weight,
|
||||
"learning_rate": args.learning_rate,
|
||||
|
||||
@@ -48,7 +48,8 @@ class MarketEngine:
|
||||
)
|
||||
human_transitions = get_adjusted_transitions(demand_h, human=True)
|
||||
agent_transitions = get_adjusted_transitions(demand_a, human=False)
|
||||
# sample behavior trajectories from each demand distribution
|
||||
# sample N trajectories in parallel; each chain is independent so threads
|
||||
# do not share state and numpy's per-call RNG is thread-safe
|
||||
human_t = [
|
||||
sample_behavior_from_transitions(human_transitions)
|
||||
for _ in range(self.Nhumans)
|
||||
@@ -59,7 +60,25 @@ class MarketEngine:
|
||||
]
|
||||
# store trajectories for agent probability calculation
|
||||
self.last_trajectories = human_t + agent_t
|
||||
return estimate_demand(self.last_trajectories, self.action_weights)
|
||||
|
||||
demand_proxy = estimate_demand(
|
||||
self.last_trajectories,
|
||||
self.action_weights,
|
||||
normalize=True,
|
||||
per_session=False,
|
||||
)
|
||||
raw_mix = ((1.0 - float(self.alpha)) * demand_h) + (
|
||||
float(self.alpha) * demand_a
|
||||
)
|
||||
total_raw_demand = float(np.sum(raw_mix))
|
||||
if not demand_proxy:
|
||||
return {i: float(raw_mix[i]) for i in range(len(prices))}
|
||||
if total_raw_demand <= 0.0:
|
||||
return {i: 0.0 for i in range(len(prices))}
|
||||
return {
|
||||
i: total_raw_demand * float(demand_proxy.get(i, 0.0)) / 100.0
|
||||
for i in range(len(prices))
|
||||
}
|
||||
|
||||
def measure(self):
|
||||
pass
|
||||
|
||||
3
engine/jax/__init__.py
Normal file
3
engine/jax/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .robust import select_adversarial_alpha_jax, _JAX_OK
|
||||
|
||||
__all__ = ["select_adversarial_alpha_jax", "_JAX_OK"]
|
||||
197
engine/jax/robust.py
Normal file
197
engine/jax/robust.py
Normal file
@@ -0,0 +1,197 @@
|
||||
"""JAX-accelerated robust inner loop for PHANTOM.
|
||||
|
||||
provides a drop-in replacement for the sequential alpha-candidate evaluation in
|
||||
wrapper.py::_select_adversarial_alpha. the demand generation and reward
|
||||
computation are vmapped over the K candidate alpha values so all candidates are
|
||||
evaluated in a single vectorized pass instead of K sequential Python calls.
|
||||
|
||||
public surface:
|
||||
select_adversarial_alpha_jax(candidates, prices, human_params, agent_params,
|
||||
noise_std, n_sessions, n_products,
|
||||
baseline_prices, lambda_coi, info_value,
|
||||
reward_profit_weight, rng_key)
|
||||
-> (best_alpha: float, rewards: np.ndarray)
|
||||
|
||||
falls back gracefully when JAX is unavailable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import jax
|
||||
import jax.numpy as jnp
|
||||
from jax import vmap, jit
|
||||
|
||||
_JAX_OK = True
|
||||
except ImportError:
|
||||
_JAX_OK = False
|
||||
|
||||
_JAX_RUNTIME_OK = True
|
||||
|
||||
|
||||
def _demand_for_actor_jax(prices, mean, std, noise_std, key):
|
||||
"""d(p;theta) = max(0, val - price + noise), normalized to sum 100."""
|
||||
k1, k2 = jax.random.split(key)
|
||||
val = jax.random.normal(k1, shape=prices.shape) * std + mean
|
||||
noise = jax.random.normal(k2, shape=prices.shape) * noise_std
|
||||
demand = jnp.maximum(0.0, val - prices + noise)
|
||||
total = demand.sum()
|
||||
return jnp.where(total > 0, demand / total * 100.0, demand)
|
||||
|
||||
|
||||
def _reward_for_candidate(
|
||||
alpha,
|
||||
prices,
|
||||
human_mean,
|
||||
human_std,
|
||||
agent_mean,
|
||||
agent_std,
|
||||
noise_std,
|
||||
baseline_prices,
|
||||
lambda_coi,
|
||||
info_value,
|
||||
reward_profit_weight,
|
||||
key,
|
||||
):
|
||||
"""compute a scalar reward for a single alpha candidate (pure JAX, vmappable)."""
|
||||
k_h, k_a = jax.random.split(key)
|
||||
# mixed demand proxy: weighted sum of human and agent demand signals
|
||||
demand_h = _demand_for_actor_jax(prices, human_mean, human_std, noise_std, k_h)
|
||||
demand_a = _demand_for_actor_jax(prices, agent_mean, agent_std, noise_std, k_a)
|
||||
demand = (1.0 - alpha) * demand_h + alpha * demand_a
|
||||
|
||||
revenue = jnp.dot(prices, demand)
|
||||
floor_cost = jnp.dot(baseline_prices, demand)
|
||||
profit = revenue - floor_cost
|
||||
|
||||
# agent_prob proxy: use alpha directly (no trajectory available in vectorized path)
|
||||
coi_leakage = alpha * info_value
|
||||
info_budget = jnp.maximum(floor_cost, 1.0)
|
||||
coi_penalty = lambda_coi * coi_leakage * info_budget
|
||||
|
||||
return reward_profit_weight * profit - coi_penalty
|
||||
|
||||
|
||||
if _JAX_OK:
|
||||
# compile once; retracing only happens on shape/dtype changes
|
||||
# 12 args: alpha, prices, h_mean, h_std, a_mean, a_std, noise_std,
|
||||
# baseline_prices, lambda_coi, info_value, reward_profit_weight, key
|
||||
_reward_batched = jit(
|
||||
vmap(
|
||||
_reward_for_candidate,
|
||||
in_axes=(0, None, None, None, None, None, None, None, None, None, None, 0),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def select_adversarial_alpha_jax(
|
||||
candidates: np.ndarray,
|
||||
prices: np.ndarray,
|
||||
human_params: tuple,
|
||||
agent_params: tuple,
|
||||
noise_std: float,
|
||||
baseline_prices: np.ndarray,
|
||||
lambda_coi: float,
|
||||
info_value: float,
|
||||
reward_profit_weight: float,
|
||||
rng_seed: int = 0,
|
||||
) -> tuple[float, np.ndarray]:
|
||||
"""evaluate all alpha candidates in a single vmapped pass.
|
||||
|
||||
returns (best_alpha, rewards_array) where best_alpha minimizes reward
|
||||
(worst case for the platform, driving robust policy training).
|
||||
|
||||
falls back to a pure-numpy sequential loop when JAX is unavailable so the
|
||||
wrapper can call this function unconditionally.
|
||||
"""
|
||||
global _JAX_RUNTIME_OK
|
||||
|
||||
if not _JAX_OK or not _JAX_RUNTIME_OK:
|
||||
return _fallback(
|
||||
candidates,
|
||||
prices,
|
||||
human_params,
|
||||
agent_params,
|
||||
noise_std,
|
||||
baseline_prices,
|
||||
lambda_coi,
|
||||
info_value,
|
||||
reward_profit_weight,
|
||||
)
|
||||
|
||||
try:
|
||||
k = len(candidates)
|
||||
key = jax.random.PRNGKey(rng_seed)
|
||||
keys = jax.random.split(key, k)
|
||||
|
||||
rewards = np.asarray(
|
||||
_reward_batched(
|
||||
jnp.asarray(candidates, dtype=jnp.float32),
|
||||
jnp.asarray(prices, dtype=jnp.float32),
|
||||
float(human_params[0]),
|
||||
float(human_params[1]),
|
||||
float(agent_params[0]),
|
||||
float(agent_params[1]),
|
||||
float(noise_std),
|
||||
jnp.asarray(baseline_prices, dtype=jnp.float32),
|
||||
float(lambda_coi),
|
||||
float(info_value),
|
||||
float(reward_profit_weight),
|
||||
keys,
|
||||
)
|
||||
)
|
||||
best_idx = int(np.argmin(rewards))
|
||||
return float(candidates[best_idx]), rewards
|
||||
except Exception as exc:
|
||||
# TPU contention / backend init failures can happen in distributed schedulers.
|
||||
# Degrade to numpy path for the remainder of the process.
|
||||
_JAX_RUNTIME_OK = False
|
||||
print(f"PHANTOM_JAX_FALLBACK: {exc}")
|
||||
return _fallback(
|
||||
candidates,
|
||||
prices,
|
||||
human_params,
|
||||
agent_params,
|
||||
noise_std,
|
||||
baseline_prices,
|
||||
lambda_coi,
|
||||
info_value,
|
||||
reward_profit_weight,
|
||||
)
|
||||
|
||||
|
||||
def _fallback(
|
||||
candidates,
|
||||
prices,
|
||||
human_params,
|
||||
agent_params,
|
||||
noise_std,
|
||||
baseline_prices,
|
||||
lambda_coi,
|
||||
info_value,
|
||||
reward_profit_weight,
|
||||
):
|
||||
"""numpy fallback matching the reward formula above."""
|
||||
rewards = []
|
||||
for alpha in candidates:
|
||||
rng = np.random.default_rng()
|
||||
val_h = rng.normal(*human_params, size=len(prices))
|
||||
val_a = rng.normal(*agent_params, size=len(prices))
|
||||
noise_h = rng.normal(0, noise_std, len(prices))
|
||||
noise_a = rng.normal(0, noise_std, len(prices))
|
||||
d_h = np.maximum(0, val_h - prices + noise_h)
|
||||
d_a = np.maximum(0, val_a - prices + noise_a)
|
||||
s_h, s_a = d_h.sum(), d_a.sum()
|
||||
d_h = d_h / s_h * 100 if s_h > 0 else d_h
|
||||
d_a = d_a / s_a * 100 if s_a > 0 else d_a
|
||||
demand = (1.0 - alpha) * d_h + alpha * d_a
|
||||
revenue = float(np.dot(prices, demand))
|
||||
floor_cost = float(np.dot(baseline_prices, demand))
|
||||
profit = revenue - floor_cost
|
||||
coi_penalty = lambda_coi * alpha * info_value * max(floor_cost, 1.0)
|
||||
rewards.append(reward_profit_weight * profit - coi_penalty)
|
||||
rewards = np.array(rewards)
|
||||
best_idx = int(np.argmin(rewards))
|
||||
return float(candidates[best_idx]), rewards
|
||||
@@ -22,6 +22,9 @@ human_dir = str(base_dir / "collected_data")
|
||||
agent_dir = str(base_dir / "agents" / "collected_data")
|
||||
|
||||
_cache = {} # lazy cache for models and base pivots
|
||||
# cache keyed by (human: bool, condition_tuple) so we skip Kronecker re-expansion
|
||||
# for repeated calls with the same demand condition inside the robustness inner loop
|
||||
_transition_cache: dict = {}
|
||||
|
||||
|
||||
def _get_base_pivot(human: bool):
|
||||
@@ -68,22 +71,41 @@ def trajectory_to_events(trajectory: list) -> list:
|
||||
"""extract event names from trajectory for KL divergence calculation
|
||||
|
||||
trajectories are in format 'eventName_product0', extract just eventName
|
||||
|
||||
args:
|
||||
trajectory: list like ['view_product0', 'add_to_cart_product1', 'checkout_product1']
|
||||
|
||||
returns:
|
||||
list: event names like ['view', 'add_to_cart', 'checkout']
|
||||
"""
|
||||
events = []
|
||||
for state in trajectory:
|
||||
# state format from sample_behavior: 'eventName_productX'
|
||||
if "_product" in state:
|
||||
event = state.rsplit("_product", 1)[0]
|
||||
else:
|
||||
event = state
|
||||
events.append(event)
|
||||
return events
|
||||
return [s.rsplit("_product", 1)[0] if "_product" in s else s for s in trajectory]
|
||||
|
||||
|
||||
class _TransitionTable:
|
||||
"""numpy-backed transition table; replaces per-step pandas .loc[] indexing.
|
||||
|
||||
the profiling hotspot was DataFrame.xs called ~4-16k times per outer step.
|
||||
converting once to a dense float32 array with an int-keyed state index map
|
||||
reduces each row lookup to a single array slice with no pandas overhead.
|
||||
rows are pre-normalized so sampling requires no per-step division.
|
||||
"""
|
||||
|
||||
__slots__ = ("matrix", "states", "state_index", "n_states")
|
||||
|
||||
def __init__(self, df: pd.DataFrame):
|
||||
self.states: list[str] = df.index.tolist()
|
||||
self.state_index: dict[str, int] = {s: i for i, s in enumerate(self.states)}
|
||||
# float64 throughout: float32 row-sums can drift enough to break np.random.choice
|
||||
mat = np.nan_to_num(
|
||||
df.values.astype(np.float64), nan=0.0, posinf=0.0, neginf=0.0
|
||||
)
|
||||
mat = np.clip(mat, 0.0, None)
|
||||
row_sums = mat.sum(axis=1)
|
||||
# dead rows (all zero) get uniform distribution so sampling never receives NaN
|
||||
dead = row_sums <= 0
|
||||
mat[dead] = 1.0
|
||||
row_sums[dead] = float(mat.shape[1])
|
||||
mat = mat / row_sums[:, np.newaxis]
|
||||
# final nan guard in case fp still drifts
|
||||
np.nan_to_num(mat, nan=0.0, copy=False)
|
||||
row_sums2 = mat.sum(axis=1, keepdims=True)
|
||||
row_sums2[row_sums2 <= 0] = 1.0
|
||||
self.matrix: np.ndarray = mat / row_sums2
|
||||
self.n_states: int = len(self.states)
|
||||
|
||||
|
||||
def adjust_behavior_to_condition(condition, transition_matrix):
|
||||
@@ -92,46 +114,73 @@ def adjust_behavior_to_condition(condition, transition_matrix):
|
||||
condition = np.nan_to_num(condition, nan=0.0, posinf=0.0, neginf=0.0)
|
||||
condition = np.clip(condition, 0.0, None)
|
||||
s = float(np.sum(condition))
|
||||
if not np.isfinite(s) or s <= 0:
|
||||
cond_norm = np.full(len(condition), 1.0 / max(len(condition), 1), dtype=float)
|
||||
else:
|
||||
cond_norm = condition / s
|
||||
cond_norm = (
|
||||
condition / s
|
||||
if np.isfinite(s) and s > 0
|
||||
else np.full(len(condition), 1.0 / max(len(condition), 1), dtype=float)
|
||||
)
|
||||
n_products = len(condition)
|
||||
base_vals = transition_matrix.values
|
||||
base_cols, base_rows = (
|
||||
transition_matrix.columns.tolist(),
|
||||
transition_matrix.index.tolist(),
|
||||
)
|
||||
|
||||
# expand via kronecker-like tiling: each cell becomes a P*P block weighted by outer product of cond_norm
|
||||
expanded = np.kron(base_vals, np.outer(cond_norm, cond_norm))
|
||||
new_cols = [f"{c}_product{p}" for c in base_cols for p in range(n_products)]
|
||||
new_rows = [f"{r}_product{p}" for r in base_rows for p in range(n_products)]
|
||||
return pd.DataFrame(expanded, index=new_rows, columns=new_cols)
|
||||
|
||||
|
||||
def get_adjusted_transitions(condition, human=True):
|
||||
def get_adjusted_transitions(condition, human=True) -> _TransitionTable:
|
||||
"""return a _TransitionTable for the given demand condition.
|
||||
|
||||
results are cached by (human, rounded-condition) so that repeated calls with
|
||||
the same condition inside the robustness inner loop (K candidates, same prices)
|
||||
skip the Kronecker expansion entirely.
|
||||
"""
|
||||
condition = np.asarray(condition, dtype=float)
|
||||
# round to 4 significant digits for cache key stability
|
||||
cache_key = (human, tuple(np.round(condition, 4).tolist()))
|
||||
if cache_key in _transition_cache:
|
||||
return _transition_cache[cache_key]
|
||||
|
||||
# prevent OOM by capping cache size
|
||||
if len(_transition_cache) > 100:
|
||||
_transition_cache.clear()
|
||||
|
||||
base_pivot = _get_base_pivot(human)
|
||||
return adjust_behavior_to_condition(condition, base_pivot)
|
||||
df = adjust_behavior_to_condition(condition, base_pivot)
|
||||
table = _TransitionTable(df)
|
||||
_transition_cache[cache_key] = table
|
||||
return table
|
||||
|
||||
|
||||
def sample_behavior_from_transitions(adjusted_transitions, max_len=40):
|
||||
trajectory = [np.random.choice(adjusted_transitions.index)]
|
||||
def clear_transition_cache():
|
||||
"""drop cached transition tables; call between episodes if condition space is large."""
|
||||
_transition_cache.clear()
|
||||
|
||||
|
||||
def sample_behavior_from_transitions(table, max_len=40):
|
||||
"""sample a Markov trajectory.
|
||||
|
||||
accepts _TransitionTable (fast path) or a legacy pandas DataFrame so existing
|
||||
call sites that pass a DataFrame directly continue to work unchanged.
|
||||
"""
|
||||
if isinstance(table, pd.DataFrame):
|
||||
table = _TransitionTable(table)
|
||||
|
||||
idx = np.random.randint(table.n_states)
|
||||
trajectory = [table.states[idx]]
|
||||
while len(trajectory) < max_len and "checkout" not in trajectory[-1]:
|
||||
probs = np.asarray(adjusted_transitions.loc[trajectory[-1]].values, dtype=float)
|
||||
probs = np.nan_to_num(probs, nan=0.0, posinf=0.0, neginf=0.0)
|
||||
probs = np.clip(probs, 0.0, None)
|
||||
s = float(np.sum(probs))
|
||||
sample = np.random.choice(
|
||||
adjusted_transitions.columns, p=(probs / s) if s > 0 else None
|
||||
)
|
||||
trajectory.append(sample)
|
||||
row = table.matrix[table.state_index[trajectory[-1]]]
|
||||
idx = int(np.random.choice(table.n_states, p=row))
|
||||
trajectory.append(table.states[idx])
|
||||
return trajectory
|
||||
|
||||
|
||||
def sample_behavior(condition, human=True, max_len=40):
|
||||
adjusted_transitions = get_adjusted_transitions(condition, human=human)
|
||||
return sample_behavior_from_transitions(adjusted_transitions, max_len=max_len)
|
||||
table = get_adjusted_transitions(condition, human=human)
|
||||
return sample_behavior_from_transitions(table, max_len=max_len)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -15,15 +15,19 @@ class MetricsCallback(BaseCallback):
|
||||
self,
|
||||
log_histograms: bool = False,
|
||||
log_freq: int = 100,
|
||||
hist_freq: int = 500,
|
||||
step_offset: int = 0,
|
||||
verbose: int = 0,
|
||||
):
|
||||
super().__init__(verbose)
|
||||
self.log_histograms = log_histograms
|
||||
self.log_freq = max(1, int(log_freq))
|
||||
self.hist_freq = max(1, int(hist_freq))
|
||||
self.step_offset = max(0, int(step_offset))
|
||||
self._wandb = get_wandb_module()
|
||||
self._wandb_live = bool(self._wandb is not None and self._wandb.run is not None)
|
||||
self._price_samples: list[float] = []
|
||||
self._demand_samples: list[float] = []
|
||||
self._window_sums = {
|
||||
"train/revenue_mean": 0.0,
|
||||
"train/margin_mean": 0.0,
|
||||
@@ -74,35 +78,100 @@ class MetricsCallback(BaseCallback):
|
||||
)
|
||||
self._window_count += 1
|
||||
|
||||
def _flush(self, step: int) -> None:
|
||||
if self._window_count <= 0:
|
||||
def _accumulate_histograms(self, info: dict[str, Any]) -> None:
|
||||
if not self.log_histograms:
|
||||
return
|
||||
denom = float(self._window_count)
|
||||
payload = {
|
||||
key: (value / denom)
|
||||
for key, value in self._window_sums.items()
|
||||
if value != 0.0
|
||||
or key
|
||||
in {
|
||||
"train/revenue_mean",
|
||||
"train/margin_mean",
|
||||
"train/coi_level_mean",
|
||||
"train/regret_mean",
|
||||
|
||||
for key in ("effective_prices", "prices"):
|
||||
if key not in info:
|
||||
continue
|
||||
try:
|
||||
values = np.asarray(info.get(key), dtype=float).reshape(-1)
|
||||
except Exception:
|
||||
continue
|
||||
if values.size <= 0:
|
||||
continue
|
||||
finite_values = values[np.isfinite(values)]
|
||||
if finite_values.size > 0:
|
||||
self._price_samples.extend(finite_values.tolist())
|
||||
break
|
||||
|
||||
if "demand" in info:
|
||||
try:
|
||||
demand_values = np.asarray(info.get("demand"), dtype=float).reshape(-1)
|
||||
except Exception:
|
||||
demand_values = np.array([], dtype=float)
|
||||
if demand_values.size > 0:
|
||||
finite_demand = demand_values[np.isfinite(demand_values)]
|
||||
if finite_demand.size > 0:
|
||||
self._demand_samples.extend(finite_demand.tolist())
|
||||
|
||||
def _flush_histograms(self, step: int, force: bool = False) -> None:
|
||||
if not self.log_histograms:
|
||||
return
|
||||
if not force and step % self.hist_freq != 0:
|
||||
return
|
||||
if not self._price_samples and not self._demand_samples:
|
||||
return
|
||||
if self._wandb is None:
|
||||
self._price_samples.clear()
|
||||
self._demand_samples.clear()
|
||||
return
|
||||
|
||||
payload: dict[str, Any] = {}
|
||||
if self._price_samples:
|
||||
payload["train/price_dist"] = self._wandb.Histogram(
|
||||
np.asarray(self._price_samples, dtype=np.float32)
|
||||
)
|
||||
if self._demand_samples:
|
||||
payload["train/demand_dist"] = self._wandb.Histogram(
|
||||
np.asarray(self._demand_samples, dtype=np.float32)
|
||||
)
|
||||
|
||||
if payload and self._wandb_live:
|
||||
try:
|
||||
self._wandb.log(payload, step=self.step_offset + int(step))
|
||||
except Exception:
|
||||
self._wandb_live = False
|
||||
|
||||
self._price_samples.clear()
|
||||
self._demand_samples.clear()
|
||||
|
||||
def _flush(self, step: int, *, force_hist: bool = False) -> None:
|
||||
if self._window_count > 0:
|
||||
denom = float(self._window_count)
|
||||
payload = {
|
||||
key: (value / denom)
|
||||
for key, value in self._window_sums.items()
|
||||
if value != 0.0
|
||||
or key
|
||||
in {
|
||||
"train/revenue_mean",
|
||||
"train/margin_mean",
|
||||
"train/coi_level_mean",
|
||||
"train/regret_mean",
|
||||
}
|
||||
}
|
||||
}
|
||||
payload["train/global_step"] = int(step)
|
||||
if self._wandb_live:
|
||||
self._wandb.log(dict(payload), step=self.step_offset + int(step))
|
||||
else:
|
||||
self.events.append(payload)
|
||||
for key in self._window_sums:
|
||||
self._window_sums[key] = 0.0
|
||||
self._window_count = 0
|
||||
payload["train/global_step"] = int(step)
|
||||
if self._wandb_live:
|
||||
try:
|
||||
self._wandb.log(dict(payload), step=self.step_offset + int(step))
|
||||
except Exception:
|
||||
self._wandb_live = False
|
||||
self.events.append(payload)
|
||||
else:
|
||||
self.events.append(payload)
|
||||
for key in self._window_sums:
|
||||
self._window_sums[key] = 0.0
|
||||
self._window_count = 0
|
||||
|
||||
self._flush_histograms(step=step, force=force_hist)
|
||||
|
||||
def _on_step(self) -> bool:
|
||||
for info in self.locals.get("infos", []):
|
||||
if isinstance(info, dict):
|
||||
self._accumulate(info)
|
||||
self._accumulate_histograms(info)
|
||||
|
||||
if self.num_timesteps % self.log_freq == 0:
|
||||
self._flush(step=self.num_timesteps)
|
||||
@@ -110,39 +179,81 @@ class MetricsCallback(BaseCallback):
|
||||
return True
|
||||
|
||||
def _on_training_end(self) -> None:
|
||||
self._flush(step=self.num_timesteps)
|
||||
self._flush(step=self.num_timesteps, force_hist=True)
|
||||
|
||||
|
||||
class EvalMetricsCallback(EvalCallback):
|
||||
"""Deterministic evaluation collector detached from logging backends."""
|
||||
|
||||
def __init__(
|
||||
self, eval_env, eval_freq: int = 1000, n_eval_episodes: int = 5, **kwargs
|
||||
self,
|
||||
eval_env,
|
||||
eval_freq: int = 1000,
|
||||
n_eval_episodes: int = 5,
|
||||
step_offset: int = 0,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
eval_env, eval_freq=eval_freq, n_eval_episodes=n_eval_episodes, **kwargs
|
||||
)
|
||||
self._eval_revenues: list[float] = []
|
||||
self.step_offset = max(0, int(step_offset))
|
||||
self._wandb = get_wandb_module()
|
||||
self._wandb_live = bool(self._wandb is not None and self._wandb.run is not None)
|
||||
self._eval_stats: dict[str, list[float]] = {
|
||||
"eval/revenue_mean": [],
|
||||
"eval/margin_mean": [],
|
||||
"eval/coi_level_mean": [],
|
||||
"eval/coi_leakage_mean": [],
|
||||
"eval/volatility_mean": [],
|
||||
"eval/agent_prob_mean": [],
|
||||
}
|
||||
self.events: list[dict[str, float | int]] = []
|
||||
|
||||
def _on_step(self) -> bool:
|
||||
result = super()._on_step()
|
||||
if self.n_calls % self.eval_freq == 0 and hasattr(self, "last_mean_reward"):
|
||||
self.events.append(
|
||||
{
|
||||
"eval/reward_mean": float(self.last_mean_reward),
|
||||
"eval/revenue_mean": float(np.mean(self._eval_revenues))
|
||||
if self._eval_revenues
|
||||
else 0.0,
|
||||
"train/global_step": int(self.num_timesteps),
|
||||
}
|
||||
)
|
||||
self._eval_revenues = []
|
||||
payload: dict[str, float | int] = {
|
||||
"eval/reward_mean": float(self.last_mean_reward),
|
||||
"train/global_step": int(self.num_timesteps),
|
||||
}
|
||||
for key, values in self._eval_stats.items():
|
||||
payload[key] = float(np.mean(values)) if values else 0.0
|
||||
|
||||
if self._wandb_live:
|
||||
try:
|
||||
self._wandb.log(
|
||||
dict(payload),
|
||||
step=self.step_offset + int(self.num_timesteps),
|
||||
)
|
||||
except Exception:
|
||||
self._wandb_live = False
|
||||
self.events.append(payload)
|
||||
else:
|
||||
self.events.append(payload)
|
||||
|
||||
for values in self._eval_stats.values():
|
||||
values.clear()
|
||||
|
||||
return result
|
||||
|
||||
def _log_success_callback(self, locals_: dict, globals_: dict) -> None:
|
||||
# called after each eval episode
|
||||
info = locals_.get("info", {})
|
||||
if "economics" in info:
|
||||
self._eval_revenues.append(info["economics"]["revenue"])
|
||||
econ = info.get("economics") if isinstance(info, dict) else None
|
||||
if not isinstance(econ, dict):
|
||||
return
|
||||
|
||||
self._eval_stats["eval/revenue_mean"].append(float(econ.get("revenue", 0.0)))
|
||||
self._eval_stats["eval/margin_mean"].append(float(econ.get("margin", 0.0)))
|
||||
self._eval_stats["eval/coi_level_mean"].append(
|
||||
float(econ.get("coi_level", 0.0))
|
||||
)
|
||||
self._eval_stats["eval/coi_leakage_mean"].append(
|
||||
float(econ.get("coi_leakage", 0.0))
|
||||
)
|
||||
self._eval_stats["eval/volatility_mean"].append(
|
||||
float(econ.get("volatility", 0.0))
|
||||
)
|
||||
self._eval_stats["eval/agent_prob_mean"].append(
|
||||
float(econ.get("agent_prob", 0.0))
|
||||
)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import numpy as np
|
||||
from typing import Dict
|
||||
|
||||
from lib.agent_probability import DEFAULT_AGENT_PRIOR, estimate_agent_probability
|
||||
|
||||
|
||||
def compute_agent_probability(
|
||||
trajectory: list,
|
||||
human_transitions: Dict,
|
||||
agent_transitions: Dict,
|
||||
temperature: float = 1.0,
|
||||
prior_agent: float = DEFAULT_AGENT_PRIOR,
|
||||
) -> float:
|
||||
"""estimate agent probability via KL divergence between trajectory transitions and reference models
|
||||
|
||||
@@ -18,10 +21,10 @@ def compute_agent_probability(
|
||||
agent_transitions: reference transition dict from agent MDP (event->event->prob)
|
||||
|
||||
returns:
|
||||
agent probability in [0, 1] via softmax over KL divergences
|
||||
agent probability in [0, 1] via sigma((delta_h - delta_a) / T)
|
||||
"""
|
||||
if len(trajectory) < 2:
|
||||
return 0.0 # insufficient data, assume human
|
||||
return float(prior_agent)
|
||||
|
||||
# build empirical transition distribution from trajectory
|
||||
trans_counts = {}
|
||||
@@ -54,11 +57,12 @@ def compute_agent_probability(
|
||||
kl_human = kl_div(empirical, human_transitions)
|
||||
kl_agent = kl_div(empirical, agent_transitions)
|
||||
|
||||
# convert to probability via softmax (lower KL = higher prob)
|
||||
t = float(max(temperature, 1e-6))
|
||||
exp_h = np.exp(-kl_human / t)
|
||||
exp_a = np.exp(-kl_agent / t)
|
||||
return float(exp_a / (exp_h + exp_a + 1e-10))
|
||||
return estimate_agent_probability(
|
||||
delta_h=kl_human,
|
||||
delta_a=kl_agent,
|
||||
temperature=temperature,
|
||||
prior_agent=prior_agent,
|
||||
)
|
||||
|
||||
|
||||
def extract_purchases(trajectories: list) -> Dict[int, int]:
|
||||
|
||||
@@ -17,18 +17,32 @@ def generate_demand_for_actor(
|
||||
params: tuple,
|
||||
noise_std: float = 1.0,
|
||||
distribution_method=np.random.normal,
|
||||
normalize: bool = False,
|
||||
) -> np.ndarray:
|
||||
"""d(p;0) = max(0, valuation - price) + epsi for single actor type
|
||||
params: (mean, std) for valuation distribution D_H or D_A"""
|
||||
val = distribution_method(*params, size=len(prices))
|
||||
noise = distribution_method(0, noise_std, len(prices))
|
||||
demand = np.maximum(0, val - prices + noise)
|
||||
if not normalize:
|
||||
return demand
|
||||
total = np.sum(demand)
|
||||
return demand / total * 100 if total > 0 else demand
|
||||
|
||||
|
||||
def estimate_demand(trajectories, action_weights=None):
|
||||
return estimate_weighted_demand(trajectories, action_weights)
|
||||
def estimate_demand(
|
||||
trajectories,
|
||||
action_weights=None,
|
||||
*,
|
||||
normalize: bool = False,
|
||||
per_session: bool = True,
|
||||
):
|
||||
return estimate_weighted_demand(
|
||||
trajectories,
|
||||
action_weights,
|
||||
normalize=normalize,
|
||||
per_session=per_session,
|
||||
)
|
||||
|
||||
|
||||
def _parse_event_state(state: str):
|
||||
@@ -50,7 +64,13 @@ def _weight_for_action(action: str, action_weights: dict) -> float:
|
||||
return CATEGORY_WEIGHTS["nav"]
|
||||
|
||||
|
||||
def estimate_weighted_demand(trajectories, action_weights=None):
|
||||
def estimate_weighted_demand(
|
||||
trajectories,
|
||||
action_weights=None,
|
||||
*,
|
||||
normalize: bool = False,
|
||||
per_session: bool = True,
|
||||
):
|
||||
action_weights = (
|
||||
DEFAULT_ACTION_WEIGHTS if action_weights is None else action_weights
|
||||
)
|
||||
@@ -64,12 +84,20 @@ def estimate_weighted_demand(trajectories, action_weights=None):
|
||||
if w <= 0:
|
||||
continue
|
||||
scores[product_id] = scores.get(product_id, 0.0) + w
|
||||
total = sum(scores.values())
|
||||
return (
|
||||
{pid: (score / total) * 100 for pid, score in scores.items()}
|
||||
if total > 0
|
||||
else {}
|
||||
)
|
||||
if not scores:
|
||||
return {}
|
||||
|
||||
if per_session and len(trajectories) > 0:
|
||||
inv_n = 1.0 / float(len(trajectories))
|
||||
scores = {pid: score * inv_n for pid, score in scores.items()}
|
||||
|
||||
if not normalize:
|
||||
return scores
|
||||
|
||||
total = float(sum(scores.values()))
|
||||
if total <= 0:
|
||||
return {}
|
||||
return {pid: (score / total) * 100.0 for pid, score in scores.items()}
|
||||
|
||||
|
||||
# Example usage
|
||||
|
||||
@@ -156,14 +156,17 @@ class ProviderBenchmark:
|
||||
|
||||
# log to wandb if available
|
||||
if HAS_WANDB and wandb.run is not None:
|
||||
wandb.log(
|
||||
{
|
||||
f"benchmark/{name}/revenue": result.mean_revenue,
|
||||
f"benchmark/{name}/coi_preserved": result.coi_preserved_pct,
|
||||
f"benchmark/{name}/margin": result.margin_integrity,
|
||||
"benchmark/alpha": alpha,
|
||||
}
|
||||
)
|
||||
try:
|
||||
wandb.log(
|
||||
{
|
||||
f"benchmark/{name}/revenue": result.mean_revenue,
|
||||
f"benchmark/{name}/coi_preserved": result.coi_preserved_pct,
|
||||
f"benchmark/{name}/margin": result.margin_integrity,
|
||||
"benchmark/alpha": alpha,
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return self.results
|
||||
|
||||
|
||||
@@ -32,17 +32,23 @@ class EconomicMetricsWrapper(gym.Wrapper):
|
||||
obs, reward, terminated, truncated, info = self.env.step(action)
|
||||
|
||||
# extract from unwrapped env
|
||||
prices = self.env.unwrapped._prices
|
||||
quoted_prices = np.asarray(self.env.unwrapped._prices, dtype=float)
|
||||
effective_prices = np.asarray(
|
||||
info.get("effective_prices", quoted_prices), dtype=float
|
||||
)
|
||||
if effective_prices.shape != quoted_prices.shape:
|
||||
effective_prices = quoted_prices
|
||||
demand_dict = self.env.unwrapped._demand
|
||||
demand = np.array([demand_dict.get(i, 0.0) for i in range(len(prices))])
|
||||
demand = np.array([demand_dict.get(i, 0.0) for i in range(len(quoted_prices))])
|
||||
|
||||
# core calculations
|
||||
revenue = float(np.sum(prices * demand))
|
||||
avg_price = float(np.mean(prices))
|
||||
revenue = float(info.get("revenue", np.sum(effective_prices * demand)))
|
||||
quoted_revenue = float(np.sum(quoted_prices * demand))
|
||||
avg_price = float(np.mean(effective_prices))
|
||||
margin = (avg_price - self.p_min) / max(avg_price, 1e-6)
|
||||
coi_level = avg_price - self.p_min # E[P] - p_min per thesis Def 1
|
||||
|
||||
self._price_history.append(prices.copy())
|
||||
self._price_history.append(effective_prices.copy())
|
||||
self._revenue_history.append(revenue)
|
||||
|
||||
# regret vs baseline (golden path)
|
||||
@@ -53,6 +59,7 @@ class EconomicMetricsWrapper(gym.Wrapper):
|
||||
# inject structured metrics into info
|
||||
info["economics"] = {
|
||||
"revenue": revenue,
|
||||
"quoted_revenue": quoted_revenue,
|
||||
"margin": margin,
|
||||
"coi_level": coi_level,
|
||||
"regret": regret,
|
||||
@@ -64,6 +71,10 @@ class EconomicMetricsWrapper(gym.Wrapper):
|
||||
"coi_penalty",
|
||||
"ux_penalty",
|
||||
"volatility",
|
||||
"upward_volatility",
|
||||
"supra_penalty",
|
||||
"supra_share",
|
||||
"competitive_anchor",
|
||||
"profit",
|
||||
"cost_floor",
|
||||
"reward_revenue",
|
||||
@@ -71,10 +82,13 @@ class EconomicMetricsWrapper(gym.Wrapper):
|
||||
"agent_prob",
|
||||
"alpha_adv",
|
||||
"alpha_nominal",
|
||||
"erosion_share",
|
||||
"effective_price_mean",
|
||||
):
|
||||
if key in info:
|
||||
info["economics"][key] = info[key]
|
||||
info["prices"] = prices.copy()
|
||||
info["prices"] = quoted_prices.copy()
|
||||
info["effective_prices"] = effective_prices.copy()
|
||||
info["demand"] = demand.copy()
|
||||
|
||||
return obs, reward, terminated, truncated, info
|
||||
|
||||
@@ -9,6 +9,7 @@ from ..telemetry.wandb import (
|
||||
get_wandb_module,
|
||||
init_run,
|
||||
run_agent,
|
||||
update_summary,
|
||||
)
|
||||
from .train import run_with_active_sweep_run
|
||||
|
||||
@@ -43,13 +44,23 @@ def run_sweep_agent(
|
||||
spec = TrainSpec.from_flat(merged)
|
||||
if run is not None:
|
||||
run.name = run_name(spec, kind=kind, scenario=scenario)
|
||||
run_with_active_sweep_run(
|
||||
spec,
|
||||
kind=kind,
|
||||
scenario=scenario,
|
||||
group=group,
|
||||
extra_tags=extra_tags,
|
||||
)
|
||||
try:
|
||||
run_with_active_sweep_run(
|
||||
spec,
|
||||
kind=kind,
|
||||
scenario=scenario,
|
||||
group=group,
|
||||
extra_tags=extra_tags,
|
||||
)
|
||||
update_summary({"run/status": "finished"})
|
||||
except Exception as exc:
|
||||
update_summary(
|
||||
{
|
||||
"run/status": "crashed",
|
||||
"run/error": str(exc),
|
||||
}
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
finish_run()
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ def _tags_for_run(spec: TrainSpec, kind: str, extra_tags: Sequence[str]) -> list
|
||||
kind,
|
||||
spec.algorithm.name,
|
||||
spec.runtime.backend,
|
||||
"vanilla" if spec.study.no_robust else "robust",
|
||||
"baseline" if spec.study.no_robust else "defended",
|
||||
]
|
||||
tags.extend([tag for tag in extra_tags if tag])
|
||||
return tags
|
||||
|
||||
@@ -91,6 +91,44 @@
|
||||
"command": "bash scripts/nx_research.sh docker-train-publish",
|
||||
"cwd": "."
|
||||
}
|
||||
},
|
||||
"whoclicked-publish": {
|
||||
"executor": "nx:run-commands",
|
||||
"dependsOn": [
|
||||
"install"
|
||||
],
|
||||
"options": {
|
||||
"command": "bash scripts/nx_research.sh whoclicked-publish",
|
||||
"cwd": "."
|
||||
}
|
||||
},
|
||||
"tpu-ray-bootstrap": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "bash scripts/nx_research.sh tpu-ray-bootstrap",
|
||||
"cwd": "."
|
||||
}
|
||||
},
|
||||
"tpu-ray-deps": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "bash scripts/nx_research.sh tpu-ray-deps",
|
||||
"cwd": "."
|
||||
}
|
||||
},
|
||||
"tpu-ray-verify": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "bash scripts/nx_research.sh tpu-ray-verify",
|
||||
"cwd": "."
|
||||
}
|
||||
},
|
||||
"tpu-ray-teardown": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "bash scripts/nx_research.sh tpu-ray-teardown",
|
||||
"cwd": "."
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
|
||||
@@ -32,10 +32,17 @@ def _normalize_keys(raw: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"study.robust_radius": "robust_radius",
|
||||
"study.robust_points": "robust_points",
|
||||
"study.robust_rollouts": "robust_rollouts",
|
||||
"study.ambiguity_radius": "robust_radius",
|
||||
"study.ambiguity_points": "robust_points",
|
||||
"study.ambiguity_rollouts": "robust_rollouts",
|
||||
"study.info_value": "info_value",
|
||||
"study.eta_ux": "eta_ux",
|
||||
"study.reward_profit_weight": "reward_profit_weight",
|
||||
"study.revenue_weight": "revenue_weight",
|
||||
"ambiguity_radius": "robust_radius",
|
||||
"ambiguity_points": "robust_points",
|
||||
"ambiguity_rollouts": "robust_rollouts",
|
||||
"baseline_mode": "no_robust",
|
||||
"stress_eval_enabled": "robust_eval_enabled",
|
||||
"optimizer.learning_rate": "learning_rate",
|
||||
"optimizer.gamma": "gamma",
|
||||
"optimizer.batch_size": "batch_size",
|
||||
@@ -45,6 +52,7 @@ def _normalize_keys(raw: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"runtime.seed": "seed",
|
||||
"runtime.total_timesteps": "total_timesteps",
|
||||
"runtime.checkpoint_interval": "checkpoint_interval",
|
||||
"runtime.hist_freq": "hist_freq",
|
||||
"eval.eval_freq": "eval_freq",
|
||||
"eval.eval_episodes": "eval_episodes",
|
||||
}
|
||||
@@ -72,6 +80,8 @@ class EnvSpec:
|
||||
max_steps: int = 100
|
||||
margin_floor: float = 0.05
|
||||
margin_floor_patience: int = 5
|
||||
agent_mu: float = 45.0
|
||||
agent_std: float = 15.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -84,7 +94,6 @@ class StudySpec:
|
||||
info_value: float = 1.0
|
||||
eta_ux: float = 0.5
|
||||
reward_profit_weight: float = 1.0
|
||||
revenue_weight: float = 0.01
|
||||
no_robust: bool = False
|
||||
|
||||
|
||||
@@ -126,6 +135,7 @@ class RuntimeSpec:
|
||||
checkpoint_interval: int = 200_000
|
||||
model_dir: str = "engine/models"
|
||||
log_freq: int = 100
|
||||
hist_freq: int = 500
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -157,6 +167,7 @@ class TrainSpec:
|
||||
"backend": self.runtime.backend,
|
||||
"device": self.runtime.device,
|
||||
"checkpoint_interval": self.runtime.checkpoint_interval,
|
||||
"hist_freq": self.runtime.hist_freq,
|
||||
"n_products": self.env.n_products,
|
||||
"N": self.env.n_sessions,
|
||||
"price_low": self.env.price_low,
|
||||
@@ -167,6 +178,8 @@ class TrainSpec:
|
||||
"max_steps": self.env.max_steps,
|
||||
"margin_floor": self.env.margin_floor,
|
||||
"margin_floor_patience": self.env.margin_floor_patience,
|
||||
"agent_mu": self.env.agent_mu,
|
||||
"agent_std": self.env.agent_std,
|
||||
"alpha": self.study.alpha,
|
||||
"lambda_coi": self.study.lambda_coi,
|
||||
"robust_radius": self.study.robust_radius,
|
||||
@@ -175,7 +188,6 @@ class TrainSpec:
|
||||
"info_value": self.study.info_value,
|
||||
"eta_ux": self.study.eta_ux,
|
||||
"reward_profit_weight": self.study.reward_profit_weight,
|
||||
"revenue_weight": self.study.revenue_weight,
|
||||
"no_robust": self.study.no_robust,
|
||||
"learning_rate": self.optimizer.learning_rate,
|
||||
"gamma": self.optimizer.gamma,
|
||||
@@ -246,6 +258,8 @@ class TrainSpec:
|
||||
max_steps=int(base["max_steps"]),
|
||||
margin_floor=float(base["margin_floor"]),
|
||||
margin_floor_patience=int(base["margin_floor_patience"]),
|
||||
agent_mu=float(base.get("agent_mu", 45.0)),
|
||||
agent_std=float(base.get("agent_std", 15.0)),
|
||||
),
|
||||
study=StudySpec(
|
||||
alpha=float(base["alpha"]),
|
||||
@@ -256,7 +270,6 @@ class TrainSpec:
|
||||
info_value=float(base["info_value"]),
|
||||
eta_ux=float(base["eta_ux"]),
|
||||
reward_profit_weight=float(base["reward_profit_weight"]),
|
||||
revenue_weight=float(base["revenue_weight"]),
|
||||
no_robust=no_robust,
|
||||
),
|
||||
optimizer=OptimizerSpec(
|
||||
@@ -294,6 +307,7 @@ class TrainSpec:
|
||||
checkpoint_interval=int(base["checkpoint_interval"]),
|
||||
model_dir=str(base["model_dir"]),
|
||||
log_freq=int(base["log_freq"]),
|
||||
hist_freq=int(base["hist_freq"]),
|
||||
),
|
||||
eval=EvalSpec(
|
||||
eval_freq=int(base["eval_freq"]),
|
||||
@@ -304,9 +318,11 @@ class TrainSpec:
|
||||
|
||||
|
||||
def run_name(spec: TrainSpec, *, kind: str, scenario: str) -> str:
|
||||
alpha_token = f"{float(spec.study.alpha):.2f}".rstrip("0").rstrip(".")
|
||||
mode = "baseline" if bool(spec.study.no_robust) else "defended"
|
||||
return (
|
||||
f"{kind}/{spec.algorithm.name}/{spec.runtime.backend}/"
|
||||
f"{spec.runtime.device}/{scenario}/s{spec.runtime.seed}"
|
||||
f"{spec.runtime.device}/{scenario}/a{alpha_token}/{mode}/s{spec.runtime.seed}"
|
||||
)
|
||||
|
||||
|
||||
@@ -318,6 +334,7 @@ def run_metadata(
|
||||
group: str | None = None,
|
||||
tags: Sequence[str] = (),
|
||||
) -> dict[str, Any]:
|
||||
mode = "baseline" if bool(spec.study.no_robust) else "defended"
|
||||
metadata: dict[str, Any] = {
|
||||
"run.kind": str(kind),
|
||||
"run.algo": spec.algorithm.name,
|
||||
@@ -326,6 +343,10 @@ def run_metadata(
|
||||
"run.scenario": str(scenario),
|
||||
"run.seed": spec.runtime.seed,
|
||||
"run.tags": list(tags),
|
||||
"study/alpha": float(spec.study.alpha),
|
||||
"study/mode": mode,
|
||||
"study/baseline_mode": float(bool(spec.study.no_robust)),
|
||||
"tiers": spec.algorithm.name,
|
||||
}
|
||||
if group:
|
||||
metadata["run.group"] = group
|
||||
|
||||
133
engine/studies/margin_erosion_alpha.py
Normal file
133
engine/studies/margin_erosion_alpha.py
Normal file
@@ -0,0 +1,133 @@
|
||||
"""validate core thesis problem: margin erosion under agent contamination
|
||||
trains standard RL (no robust components) across α levels to demonstrate systematic failure
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import json, sys, time
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
from engine.spec import TrainSpec
|
||||
from engine.orchestrators import run_train_once
|
||||
|
||||
|
||||
def _run_baseline(alpha: float, algo: str, seed: int, steps: int) -> dict:
|
||||
spec = TrainSpec.from_flat(
|
||||
{
|
||||
"algo": algo,
|
||||
"seed": seed,
|
||||
"alpha": alpha,
|
||||
"total_timesteps": steps,
|
||||
"lambda_coi": 0.0,
|
||||
"robust_radius": 0.0,
|
||||
"robust_points": 1,
|
||||
"robust_rollouts": 1,
|
||||
"no_robust": True,
|
||||
"arch": "small",
|
||||
"n_products": 10,
|
||||
"N": 100,
|
||||
"max_steps": 50,
|
||||
"eval_freq": 5000,
|
||||
"eval_episodes": 10,
|
||||
"log_freq": 500,
|
||||
"robust_eval_enabled": False,
|
||||
"agent_mu": 12.0,
|
||||
"agent_std": 2.0,
|
||||
}
|
||||
)
|
||||
result = run_train_once(
|
||||
spec,
|
||||
project="phantom-margin-erosion",
|
||||
offline=True,
|
||||
no_wandb=True,
|
||||
kind="study",
|
||||
scenario=f"alpha{int(alpha * 100):02d}",
|
||||
group=f"baseline_{algo}",
|
||||
extra_tags=("margin_erosion", "baseline"),
|
||||
)
|
||||
return {
|
||||
"alpha": alpha,
|
||||
"algo": algo,
|
||||
"seed": seed,
|
||||
"eval_reward": result.get("eval/reward_mean", np.nan),
|
||||
"eval_revenue": result.get("eval/revenue_mean", np.nan),
|
||||
"eval_coi_level": result.get("eval/coi_level_mean", np.nan),
|
||||
"eval_margin": result.get("eval/margin_mean", np.nan),
|
||||
"eval_agent_prob": result.get("eval/agent_prob_mean", np.nan),
|
||||
}
|
||||
|
||||
|
||||
def run_margin_erosion_study(
|
||||
alphas: list[float] | None = None,
|
||||
algos: list[str] | None = None,
|
||||
seeds: int = 3,
|
||||
steps: int = 30_000,
|
||||
) -> dict:
|
||||
alphas = alphas or [0.1, 0.3, 0.5, 0.7, 0.9]
|
||||
algos = algos or ["ppo", "dqn", "qtable"]
|
||||
output_dir = Path(__file__).parent / "results"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
ts = time.strftime("%Y%m%d_%H%M%S")
|
||||
|
||||
results = []
|
||||
for α in alphas:
|
||||
for algo in algos:
|
||||
for si in range(seeds):
|
||||
seed = 42 + si
|
||||
print(f"α={α:.1f} {algo} seed={seed}")
|
||||
m = _run_baseline(α, algo, seed, steps)
|
||||
results.append(m)
|
||||
print(
|
||||
f" margin={m['eval_margin']:.3f} rev={m['eval_revenue']:.0f} coi={m['eval_coi_level']:.1f}"
|
||||
)
|
||||
|
||||
summary = {}
|
||||
for α in alphas:
|
||||
runs = [r for r in results if abs(r["alpha"] - α) < 0.01]
|
||||
if not runs:
|
||||
continue
|
||||
s = {}
|
||||
for metric in ["margin", "revenue", "coi_level", "agent_prob"]:
|
||||
vals = [r[f"eval_{metric}"] for r in runs]
|
||||
s[f"{metric}_mean"] = float(np.mean(vals))
|
||||
s[f"{metric}_std"] = float(np.std(vals))
|
||||
s["n_runs"] = len(runs)
|
||||
summary[f"alpha_{α:.1f}"] = s
|
||||
|
||||
output = {
|
||||
"timestamp": ts,
|
||||
"config": {"alphas": alphas, "algos": algos, "seeds": seeds, "steps": steps},
|
||||
"results": results,
|
||||
"summary": summary,
|
||||
}
|
||||
|
||||
path = output_dir / f"margin_erosion_alpha_{ts}.json"
|
||||
with open(path, "w") as f:
|
||||
json.dump(output, f, indent=2)
|
||||
|
||||
print(f"\n→ {path}")
|
||||
for α in alphas:
|
||||
k = f"alpha_{α:.1f}"
|
||||
if k in summary:
|
||||
s = summary[k]
|
||||
print(
|
||||
f" {k}: margin={s['margin_mean']:.3f}±{s['margin_std']:.3f} "
|
||||
f"coi={s['coi_level_mean']:.1f}±{s['coi_level_std']:.1f}"
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
p = argparse.ArgumentParser(description="margin erosion vs α")
|
||||
p.add_argument("--quick", action="store_true", help="fast test")
|
||||
args = p.parse_args()
|
||||
|
||||
run_margin_erosion_study(
|
||||
alphas=[0.1, 0.7] if args.quick else [0.1, 0.3, 0.5, 0.7, 0.9],
|
||||
algos=["qtable"] if args.quick else ["ppo", "dqn", "qtable"],
|
||||
seeds=1 if args.quick else 3,
|
||||
steps=5_000 if args.quick else 30_000,
|
||||
)
|
||||
60
engine/sweeps/final_thesis_proof.yaml
Normal file
60
engine/sweeps/final_thesis_proof.yaml
Normal file
@@ -0,0 +1,60 @@
|
||||
method: grid
|
||||
metric:
|
||||
name: eval/stress_reward_worst
|
||||
goal: maximize
|
||||
command:
|
||||
- ${env}
|
||||
- python
|
||||
- -m
|
||||
- engine.train
|
||||
parameters:
|
||||
algo:
|
||||
value: ppo
|
||||
backend:
|
||||
value: sb3
|
||||
device:
|
||||
value: cpu
|
||||
seed:
|
||||
values: [42, 1337, 7777]
|
||||
alpha:
|
||||
values: [0.1, 0.2, 0.3, 0.4, 0.6, 0.8]
|
||||
n_products:
|
||||
values: [25, 50, 100]
|
||||
N:
|
||||
value: 100
|
||||
no_robust:
|
||||
values: [false, true]
|
||||
lambda_coi:
|
||||
values: [0.15, 0.30]
|
||||
robust_radius:
|
||||
value: 0.2
|
||||
robust_points:
|
||||
value: 7
|
||||
robust_rollouts:
|
||||
value: 1
|
||||
eta_ux:
|
||||
value: 0.5
|
||||
reward_profit_weight:
|
||||
value: 1.0
|
||||
action_levels:
|
||||
value: 9
|
||||
action_scale_low:
|
||||
value: 0.8
|
||||
action_scale_high:
|
||||
value: 1.2
|
||||
total_timesteps:
|
||||
value: 100000
|
||||
eval_episodes:
|
||||
value: 12
|
||||
eval_freq:
|
||||
value: 1000
|
||||
log_freq:
|
||||
value: 100
|
||||
hist_freq:
|
||||
value: 500
|
||||
learning_rate:
|
||||
value: 0.0003
|
||||
batch_size:
|
||||
value: 256
|
||||
n_steps:
|
||||
value: 2048
|
||||
53
engine/sweeps/ppo_supra_guard.yaml
Normal file
53
engine/sweeps/ppo_supra_guard.yaml
Normal file
@@ -0,0 +1,53 @@
|
||||
method: random
|
||||
metric:
|
||||
name: eval/supra_share_mean
|
||||
goal: minimize
|
||||
run_cap: 256
|
||||
command:
|
||||
- ${env}
|
||||
- python
|
||||
- -m
|
||||
- engine.train
|
||||
parameters:
|
||||
algo:
|
||||
value: ppo
|
||||
seed:
|
||||
values: [42, 1337, 7777]
|
||||
alpha:
|
||||
values: [0.1, 0.2, 0.3, 0.4, 0.6]
|
||||
n_products:
|
||||
values: [25, 50]
|
||||
N:
|
||||
value: 100
|
||||
no_robust:
|
||||
values: [false, true]
|
||||
lambda_coi:
|
||||
values: [0.05, 0.15, 0.3]
|
||||
robust_radius:
|
||||
values: [0.1, 0.2, 0.3]
|
||||
robust_points:
|
||||
value: 7
|
||||
robust_rollouts:
|
||||
value: 1
|
||||
eta_ux:
|
||||
values: [0.05, 0.15, 0.3, 0.5, 0.75]
|
||||
reward_profit_weight:
|
||||
value: 1.0
|
||||
total_timesteps:
|
||||
value: 100000
|
||||
eval_episodes:
|
||||
value: 10
|
||||
eval_freq:
|
||||
value: 1000
|
||||
log_freq:
|
||||
value: 100
|
||||
hist_freq:
|
||||
value: 500
|
||||
learning_rate:
|
||||
value: 0.0003
|
||||
batch_size:
|
||||
value: 256
|
||||
n_steps:
|
||||
value: 2048
|
||||
device:
|
||||
value: cpu
|
||||
@@ -36,7 +36,12 @@ def canonicalize_metrics(raw: Mapping[str, Any], spec: TrainSpec) -> dict[str, A
|
||||
|
||||
eval_reward = (
|
||||
_as_float(
|
||||
metrics.get("eval/robust_reward_worst", metrics.get("eval/reward_mean")),
|
||||
metrics.get(
|
||||
"eval/stress_reward_worst",
|
||||
metrics.get(
|
||||
"eval/robust_reward_worst", metrics.get("eval/reward_mean")
|
||||
),
|
||||
),
|
||||
0.0,
|
||||
)
|
||||
or 0.0
|
||||
@@ -51,9 +56,12 @@ def canonicalize_metrics(raw: Mapping[str, Any], spec: TrainSpec) -> dict[str, A
|
||||
metrics["objective/coi_preserved"] = 0.0 if coi_level is None else coi_level
|
||||
|
||||
metrics["study/alpha"] = spec.study.alpha
|
||||
metrics["study/mode"] = "baseline" if bool(spec.study.no_robust) else "defended"
|
||||
metrics["study/baseline_mode"] = float(bool(spec.study.no_robust))
|
||||
metrics["study/lambda_coi"] = spec.study.lambda_coi
|
||||
metrics["study/robust_radius"] = spec.study.robust_radius
|
||||
metrics["study/ambiguity_radius"] = spec.study.robust_radius
|
||||
metrics["study/info_value"] = spec.study.info_value
|
||||
metrics["tiers"] = spec.algorithm.name
|
||||
|
||||
metrics["runtime/backend"] = spec.runtime.backend
|
||||
metrics["runtime/device"] = spec.runtime.device
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Iterable, Mapping
|
||||
|
||||
|
||||
@@ -19,6 +21,42 @@ def _require_wandb():
|
||||
return wandb
|
||||
|
||||
|
||||
def _warn(message: str) -> None:
|
||||
print(f"PHANTOM_WANDB_WARNING: {message}")
|
||||
|
||||
|
||||
def _sanitize_key(raw_key: str) -> str | None:
|
||||
key = str(raw_key)
|
||||
replacements = {
|
||||
"no_robust": "baseline_mode",
|
||||
"study/no_robust": "study/baseline_mode",
|
||||
"study/robust_radius": "study/ambiguity_radius",
|
||||
"robust_radius": "ambiguity_radius",
|
||||
"robust_points": "ambiguity_points",
|
||||
"robust_rollouts": "ambiguity_rollouts",
|
||||
"robust_eval_enabled": "stress_eval_enabled",
|
||||
"eval/robust_alpha_high": "eval/stress_alpha_high",
|
||||
"eval/robust_alpha_low": "eval/stress_alpha_low",
|
||||
"eval/robust_reward_worst": "eval/stress_reward_worst",
|
||||
"eval/robust_revenue_worst": "eval/stress_revenue_worst",
|
||||
"eval/robust_coi_leakage_worst": "eval/stress_coi_leakage_worst",
|
||||
}
|
||||
key = replacements.get(key, key)
|
||||
if "robust" in key.lower():
|
||||
return None
|
||||
return key
|
||||
|
||||
|
||||
def _sanitize_payload(payload: Mapping[str, Any]) -> dict[str, Any]:
|
||||
sanitized: dict[str, Any] = {}
|
||||
for key, value in payload.items():
|
||||
clean_key = _sanitize_key(str(key))
|
||||
if clean_key is None:
|
||||
continue
|
||||
sanitized[clean_key] = value
|
||||
return sanitized
|
||||
|
||||
|
||||
def init_run(
|
||||
*,
|
||||
mode: str,
|
||||
@@ -34,7 +72,11 @@ def init_run(
|
||||
if group:
|
||||
kwargs["group"] = group
|
||||
if sweep_mode:
|
||||
run = wandb.init(**kwargs)
|
||||
try:
|
||||
run = wandb.init(**kwargs)
|
||||
except Exception as exc:
|
||||
_warn(f"init failed in sweep mode ({exc})")
|
||||
return None
|
||||
if name and run is not None:
|
||||
run.name = name
|
||||
return run
|
||||
@@ -42,18 +84,25 @@ def init_run(
|
||||
init_kwargs = dict(kwargs)
|
||||
init_kwargs["project"] = project
|
||||
if config is not None:
|
||||
init_kwargs["config"] = dict(config)
|
||||
init_kwargs["config"] = _sanitize_payload(dict(config))
|
||||
if name:
|
||||
init_kwargs["name"] = name
|
||||
if tags:
|
||||
init_kwargs["tags"] = list(tags)
|
||||
return wandb.init(**init_kwargs)
|
||||
try:
|
||||
return wandb.init(**init_kwargs)
|
||||
except Exception as exc:
|
||||
_warn(f"init failed ({exc})")
|
||||
return None
|
||||
|
||||
|
||||
def finish_run() -> None:
|
||||
wandb = get_wandb_module()
|
||||
if wandb is not None and wandb.run is not None:
|
||||
wandb.finish()
|
||||
try:
|
||||
wandb.finish()
|
||||
except Exception as exc:
|
||||
_warn(f"finish failed ({exc})")
|
||||
|
||||
|
||||
def current_config() -> dict[str, Any]:
|
||||
@@ -67,25 +116,45 @@ def update_run_config(config: Mapping[str, Any]) -> None:
|
||||
wandb = get_wandb_module()
|
||||
if wandb is None or wandb.run is None:
|
||||
return
|
||||
payload = _sanitize_payload(dict(config))
|
||||
if not payload:
|
||||
return
|
||||
try:
|
||||
wandb.config.update(dict(config), allow_val_change=True)
|
||||
wandb.config.update(payload, allow_val_change=True)
|
||||
except TypeError:
|
||||
wandb.config.update(dict(config))
|
||||
try:
|
||||
wandb.config.update(payload)
|
||||
except Exception as exc:
|
||||
_warn(f"config update failed ({exc})")
|
||||
except Exception as exc:
|
||||
_warn(f"config update failed ({exc})")
|
||||
|
||||
|
||||
def log_metrics(metrics: Mapping[str, Any], *, step: int) -> None:
|
||||
wandb = get_wandb_module()
|
||||
if wandb is None or wandb.run is None:
|
||||
return
|
||||
wandb.log(dict(metrics), step=step)
|
||||
payload = _sanitize_payload(dict(metrics))
|
||||
if not payload:
|
||||
return
|
||||
try:
|
||||
wandb.log(payload, step=step)
|
||||
except Exception as exc:
|
||||
_warn(f"log failed at step {step} ({exc})")
|
||||
|
||||
|
||||
def update_summary(metrics: Mapping[str, Any]) -> None:
|
||||
wandb = get_wandb_module()
|
||||
if wandb is None or wandb.run is None:
|
||||
return
|
||||
for key, value in metrics.items():
|
||||
wandb.run.summary[key] = value
|
||||
payload = _sanitize_payload(dict(metrics))
|
||||
if not payload:
|
||||
return
|
||||
try:
|
||||
for key, value in payload.items():
|
||||
wandb.run.summary[key] = value
|
||||
except Exception as exc:
|
||||
_warn(f"summary update failed ({exc})")
|
||||
|
||||
|
||||
def run_agent(
|
||||
@@ -95,4 +164,39 @@ def run_agent(
|
||||
count: int | None = None,
|
||||
) -> None:
|
||||
wandb = _require_wandb()
|
||||
wandb.agent(sweep_id, function=fn, count=count)
|
||||
retry_max = max(0, int(os.getenv("PHANTOM_WANDB_AGENT_RETRIES", "8")))
|
||||
retry_delay = max(1.0, float(os.getenv("PHANTOM_WANDB_AGENT_RETRY_DELAY", "5")))
|
||||
retry_backoff = max(
|
||||
1.0, float(os.getenv("PHANTOM_WANDB_AGENT_RETRY_BACKOFF", "1.5"))
|
||||
)
|
||||
retry_max_delay = max(
|
||||
retry_delay,
|
||||
float(os.getenv("PHANTOM_WANDB_AGENT_MAX_RETRY_DELAY", "60")),
|
||||
)
|
||||
|
||||
target = None if count is None else max(0, int(count))
|
||||
completed = 0
|
||||
|
||||
def _wrapped() -> None:
|
||||
nonlocal completed
|
||||
fn()
|
||||
completed += 1
|
||||
|
||||
attempt = 0
|
||||
while True:
|
||||
remaining = None if target is None else max(0, int(target - completed))
|
||||
if target is not None and remaining == 0:
|
||||
return
|
||||
try:
|
||||
wandb.agent(sweep_id, function=_wrapped, count=remaining)
|
||||
return
|
||||
except Exception as exc:
|
||||
attempt += 1
|
||||
if attempt > retry_max:
|
||||
raise
|
||||
wait = min(retry_max_delay, retry_delay * (retry_backoff ** (attempt - 1)))
|
||||
_warn(
|
||||
f"agent disconnected (attempt {attempt}/{retry_max}, "
|
||||
f"completed={completed}, remaining={remaining}): {exc}"
|
||||
)
|
||||
time.sleep(wait)
|
||||
|
||||
@@ -54,6 +54,7 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
parser.add_argument("--total-timesteps", type=int)
|
||||
parser.add_argument("--model-dir", type=str)
|
||||
parser.add_argument("--log-freq", type=int)
|
||||
parser.add_argument("--hist-freq", type=int)
|
||||
parser.add_argument("--checkpoint-interval", type=int)
|
||||
parser.add_argument("--device", type=str)
|
||||
|
||||
@@ -68,7 +69,6 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
parser.add_argument("--no-robust", action="store_true")
|
||||
parser.add_argument("--eta-ux", type=float)
|
||||
parser.add_argument("--reward-profit-weight", type=float)
|
||||
parser.add_argument("--revenue-weight", type=float)
|
||||
|
||||
parser.add_argument("--price-low", type=float)
|
||||
parser.add_argument("--price-high", type=float)
|
||||
@@ -126,6 +126,7 @@ def _overrides_from_args(args: argparse.Namespace) -> dict[str, Any]:
|
||||
"total_timesteps": args.total_timesteps,
|
||||
"model_dir": args.model_dir,
|
||||
"log_freq": args.log_freq,
|
||||
"hist_freq": args.hist_freq,
|
||||
"checkpoint_interval": args.checkpoint_interval,
|
||||
"device": args.device,
|
||||
"alpha": args.alpha,
|
||||
@@ -139,7 +140,6 @@ def _overrides_from_args(args: argparse.Namespace) -> dict[str, Any]:
|
||||
"no_robust": args.no_robust,
|
||||
"eta_ux": args.eta_ux,
|
||||
"reward_profit_weight": args.reward_profit_weight,
|
||||
"revenue_weight": args.revenue_weight,
|
||||
"price_low": args.price_low,
|
||||
"price_high": args.price_high,
|
||||
"action_levels": args.action_levels,
|
||||
@@ -179,8 +179,29 @@ def _overrides_from_args(args: argparse.Namespace) -> dict[str, Any]:
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# Ensure data is downloaded
|
||||
from pathlib import Path
|
||||
|
||||
project_root = Path(__file__).parents[1]
|
||||
data_dir = project_root / "experiments" / "collected_data"
|
||||
needs_pull = (not data_dir.exists()) or (not any(data_dir.iterdir()))
|
||||
if needs_pull:
|
||||
try:
|
||||
subprocess.run(["make", "data.pull"], cwd=str(project_root), check=True)
|
||||
except (subprocess.SubprocessError, OSError) as exc:
|
||||
sys.path.insert(0, str(project_root))
|
||||
try:
|
||||
from scripts.hf_data import pull
|
||||
|
||||
pull()
|
||||
except (ImportError, OSError, RuntimeError, ValueError) as fallback_exc:
|
||||
print(
|
||||
f"Warning: data.pull failed ({exc}); fallback pull failed ({fallback_exc})"
|
||||
)
|
||||
|
||||
configure_logging()
|
||||
raw_args = list(sys.argv[1:] if argv is None else argv)
|
||||
run_kind = _probe_run_kind(raw_args)
|
||||
|
||||
@@ -10,6 +10,7 @@ from .lib.coi import (
|
||||
)
|
||||
from .lib.behavior import get_transition_models, trajectory_to_events
|
||||
from .lib.wrappers import EconomicMetricsWrapper
|
||||
from .jax.robust import select_adversarial_alpha_jax, _JAX_OK
|
||||
|
||||
|
||||
class _ActionPricingEngine(PricingEngine):
|
||||
@@ -121,6 +122,7 @@ class PHANTOM(gym.Env):
|
||||
self._prices = None
|
||||
self._demand = None
|
||||
self._step_count = 0
|
||||
self._global_step = 0 # monotonic; used as JAX RNG seed across resets
|
||||
self._demand_history = []
|
||||
self._price_history = []
|
||||
self._revenue_history = []
|
||||
@@ -128,6 +130,13 @@ class PHANTOM(gym.Env):
|
||||
self._initial_episode_prices = None
|
||||
self._trajectories = [] # session trajectories for agent prob calculation
|
||||
self.baseline_prices = np.full(self.n_products, self.price_bounds[0])
|
||||
self.anchor_prices = np.full(
|
||||
self.n_products,
|
||||
float(np.clip(float(self.human_params[0]), *self.price_bounds)),
|
||||
)
|
||||
self.competitive_cap = float(
|
||||
min(self.price_bounds[1], float(np.mean(self.anchor_prices)) * 1.15)
|
||||
)
|
||||
self._low_margin_streak = 0 # consecutive steps below margin_floor
|
||||
self._last_agent_prob = float(self.alpha)
|
||||
self._last_alpha_adv = float(self.alpha)
|
||||
@@ -167,19 +176,28 @@ class PHANTOM(gym.Env):
|
||||
self.market.Nhumans = self.N - n_agents
|
||||
|
||||
def _decode_action(self, action) -> np.ndarray:
|
||||
base = (
|
||||
self._prices
|
||||
if self._prices is not None
|
||||
else np.full(self.n_products, self.price_bounds[0], dtype=float)
|
||||
)
|
||||
prev = self._prices
|
||||
base = self.anchor_prices
|
||||
|
||||
def _blend(target: np.ndarray) -> np.ndarray:
|
||||
if prev is None:
|
||||
lower = float(self.price_bounds[0])
|
||||
return np.clip(target, lower, self.competitive_cap)
|
||||
blended = 0.75 * np.asarray(prev, dtype=float) + 0.25 * target
|
||||
lower = float(self.price_bounds[0])
|
||||
return np.clip(blended, lower, self.competitive_cap)
|
||||
|
||||
if np.isscalar(action):
|
||||
idx = int(np.clip(int(action), 0, self.action_levels - 1))
|
||||
return np.clip(base * self._action_scales[idx], *self.price_bounds)
|
||||
target = base * self._action_scales[idx]
|
||||
return _blend(target)
|
||||
a = np.asarray(action)
|
||||
if a.size == 1:
|
||||
idx = int(np.clip(int(a.reshape(-1)[0]), 0, self.action_levels - 1))
|
||||
return np.clip(base * self._action_scales[idx], *self.price_bounds)
|
||||
return np.clip(a.astype(float), *self.price_bounds)
|
||||
target = base * self._action_scales[idx]
|
||||
return _blend(target)
|
||||
lower = float(self.price_bounds[0])
|
||||
return np.clip(a.astype(float), lower, self.competitive_cap)
|
||||
|
||||
def _compute_agent_prob(self, trajectories=None) -> float:
|
||||
trajectories = (
|
||||
@@ -214,18 +232,23 @@ class PHANTOM(gym.Env):
|
||||
coi_penalty = self.lambda_coi * coi_leakage * info_budget
|
||||
|
||||
if len(self._price_history) > 0:
|
||||
volatility = float(
|
||||
np.mean(
|
||||
np.abs(prices - self._price_history[-1])
|
||||
/ np.maximum(self.baseline_prices, 1.0)
|
||||
)
|
||||
)
|
||||
prev_prices = np.asarray(self._price_history[-1], dtype=float)
|
||||
rel_change = (prices - prev_prices) / np.maximum(prev_prices, 1.0)
|
||||
volatility = float(np.mean(np.abs(rel_change)))
|
||||
upward_volatility = float(np.mean(np.clip(rel_change, 0.0, None)))
|
||||
else:
|
||||
volatility = 0.0
|
||||
ux_penalty = self.eta_ux * info_budget * volatility
|
||||
upward_volatility = 0.0
|
||||
ux_penalty = self.eta_ux * info_budget * (volatility + 0.5 * upward_volatility)
|
||||
|
||||
competitive_anchor = float(np.mean(self.anchor_prices))
|
||||
price_ratio = prices / max(competitive_anchor, 1.0)
|
||||
supra_excess = np.clip(price_ratio - 1.15, 0.0, None)
|
||||
supra_penalty = 4.0 * info_budget * float(np.mean(np.square(supra_excess)))
|
||||
supra_share = float(np.mean(supra_excess > 0.0))
|
||||
|
||||
reward_revenue = self.reward_profit_weight * profit
|
||||
reward = reward_revenue - coi_penalty - ux_penalty
|
||||
reward = reward_revenue - coi_penalty - ux_penalty - supra_penalty
|
||||
|
||||
return reward, {
|
||||
"revenue": revenue,
|
||||
@@ -238,6 +261,10 @@ class PHANTOM(gym.Env):
|
||||
"coi_info_budget": info_budget,
|
||||
"ux_penalty": ux_penalty,
|
||||
"volatility": volatility,
|
||||
"upward_volatility": upward_volatility,
|
||||
"supra_penalty": supra_penalty,
|
||||
"supra_share": supra_share,
|
||||
"competitive_anchor": competitive_anchor,
|
||||
"reward_revenue": reward_revenue,
|
||||
"reward_total": reward,
|
||||
}
|
||||
@@ -261,8 +288,37 @@ class PHANTOM(gym.Env):
|
||||
return float(np.mean(rewards)) if rewards else 0.0
|
||||
|
||||
def _select_adversarial_alpha(self, prices: np.ndarray) -> float:
|
||||
"""inner robust step: evaluate candidates and pick worst-case alpha"""
|
||||
"""inner robust step: pick worst-case alpha from the ambiguity interval.
|
||||
|
||||
when JAX is available and robust_rollouts==1 we use a vmapped pass over
|
||||
all K candidates in a single call (no Python loop, no market.act overhead).
|
||||
the JAX path approximates demand as the mixed closed-form d(p;theta) signal
|
||||
rather than running full trajectory sampling, which is accurate for the
|
||||
alpha-selection decision while being dramatically cheaper.
|
||||
|
||||
when robust_rollouts>1 or JAX is unavailable we fall back to the sequential
|
||||
market.act() loop so behavior is identical to the original implementation.
|
||||
"""
|
||||
candidates = self._alpha_candidates()
|
||||
if len(candidates) == 1:
|
||||
return float(candidates[0])
|
||||
|
||||
if _JAX_OK and self.robust_rollouts == 1:
|
||||
best_alpha, _ = select_adversarial_alpha_jax(
|
||||
candidates=candidates,
|
||||
prices=prices,
|
||||
human_params=self.market.human_params,
|
||||
agent_params=self.market.agent_params,
|
||||
noise_std=self.market.noise_std,
|
||||
baseline_prices=self.baseline_prices,
|
||||
lambda_coi=self.lambda_coi,
|
||||
info_value=self.info_value,
|
||||
reward_profit_weight=self.reward_profit_weight,
|
||||
rng_seed=self._global_step,
|
||||
)
|
||||
return best_alpha
|
||||
|
||||
# fallback: full trajectory-based sequential evaluation
|
||||
evaluations = [
|
||||
(float(alpha), self._evaluate_candidate(float(alpha), prices))
|
||||
for alpha in candidates
|
||||
@@ -299,6 +355,7 @@ class PHANTOM(gym.Env):
|
||||
def step(self, action):
|
||||
self._prices = self._decode_action(action)
|
||||
alpha_adv = self._select_adversarial_alpha(self._prices)
|
||||
self._global_step += 1 # always increment; JAX path may have already done so
|
||||
self._set_market_mix(alpha_adv)
|
||||
self._platform_stub.set_prices(self._prices)
|
||||
self._step_count += 1
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
All hardcoded paths should reference this module
|
||||
Paths can be overridden via environment variables
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
@@ -9,24 +10,34 @@ from pathlib import Path
|
||||
PROJECT_ROOT = Path(__file__).parent.parent.resolve()
|
||||
|
||||
# data directories
|
||||
DATA_DIR = Path(os.getenv('PHANTOM_DATA_DIR', PROJECT_ROOT / 'data'))
|
||||
EXPERIMENTS_DIR = Path(os.getenv('PHANTOM_EXPERIMENTS_DIR', PROJECT_ROOT / 'experiments'))
|
||||
DATA_DIR = Path(os.getenv("PHANTOM_DATA_DIR", PROJECT_ROOT / "data"))
|
||||
EXPERIMENTS_DIR = Path(
|
||||
os.getenv("PHANTOM_EXPERIMENTS_DIR", PROJECT_ROOT / "experiments")
|
||||
)
|
||||
|
||||
# agent/human interaction data
|
||||
AGENT_DATA_DIR = Path(os.getenv('PHANTOM_AGENT_DATA_DIR', DATA_DIR / 'agents'))
|
||||
HUMAN_DATA_DIR = Path(os.getenv('PHANTOM_HUMAN_DATA_DIR', DATA_DIR / 'humans'))
|
||||
AGENT_DATA_DIR = Path(os.getenv("PHANTOM_AGENT_DATA_DIR", DATA_DIR / "agents"))
|
||||
HUMAN_DATA_DIR = Path(os.getenv("PHANTOM_HUMAN_DATA_DIR", DATA_DIR / "humans"))
|
||||
|
||||
# RL simulation runs
|
||||
SIM_RUNS_DIR = Path(os.getenv('PHANTOM_SIM_RUNS_DIR', PROJECT_ROOT / 'sim' / 'rl' / 'runs'))
|
||||
SIM_RUNS_DIR = Path(
|
||||
os.getenv("PHANTOM_SIM_RUNS_DIR", PROJECT_ROOT / "sim" / "rl" / "runs")
|
||||
)
|
||||
|
||||
# model artifacts
|
||||
MODEL_REGISTRY_DIR = Path(os.getenv('PHANTOM_MODEL_REGISTRY_DIR', DATA_DIR / 'models'))
|
||||
MODEL_REGISTRY_DIR = Path(os.getenv("PHANTOM_MODEL_REGISTRY_DIR", DATA_DIR / "models"))
|
||||
|
||||
# collected experiment data
|
||||
COLLECTED_DATA_DIR = Path(os.getenv('PHANTOM_COLLECTED_DATA_DIR', EXPERIMENTS_DIR / 'agents' / 'collected_data'))
|
||||
COLLECTED_DATA_DIR = Path(
|
||||
os.getenv(
|
||||
"PHANTOM_COLLECTED_DATA_DIR", EXPERIMENTS_DIR / "agents" / "collected_data"
|
||||
)
|
||||
)
|
||||
|
||||
# notebook outputs
|
||||
NOTEBOOK_OUTPUT_DIR = Path(os.getenv('PHANTOM_NOTEBOOK_OUTPUT_DIR', EXPERIMENTS_DIR / 'notebooks' / 'outputs'))
|
||||
NOTEBOOK_OUTPUT_DIR = Path(
|
||||
os.getenv("PHANTOM_NOTEBOOK_OUTPUT_DIR", EXPERIMENTS_DIR / "notebooks" / "outputs")
|
||||
)
|
||||
|
||||
|
||||
def ensure_dir(path: Path) -> Path:
|
||||
@@ -51,15 +62,18 @@ def get_sim_path(*parts: str) -> Path:
|
||||
|
||||
|
||||
# service configuration (from .env)
|
||||
KAFKA_HOST = os.getenv('KAFKA_HOST', 'localhost')
|
||||
KAFKA_PORT = os.getenv('KAFKA_PORT', '9092')
|
||||
KAFKA_HOST = os.getenv("KAFKA_HOST", "localhost")
|
||||
KAFKA_PORT = os.getenv("KAFKA_PORT", "9092")
|
||||
KAFKA_BROKER = f"{KAFKA_HOST}:{KAFKA_PORT}"
|
||||
|
||||
REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')
|
||||
REDIS_PORT = int(os.getenv('REDIS_PORT', '6379'))
|
||||
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
|
||||
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
|
||||
|
||||
SUPABASE_URL = os.getenv('NEXT_PUBLIC_SUPABASE_URL', '')
|
||||
SUPABASE_ANON_KEY = os.getenv('NEXT_PUBLIC_SUPABASE_ANON_KEY', '')
|
||||
SUPABASE_URL = os.getenv("NEXT_PUBLIC_SUPABASE_URL", "")
|
||||
SUPABASE_ANON_KEY = os.getenv("NEXT_PUBLIC_SUPABASE_ANON_KEY", "")
|
||||
|
||||
BACKEND_PORT = int(os.getenv('BACKEND_PORT', '5000'))
|
||||
PROVIDER_PORT = int(os.getenv('PROVIDER_PORT', '5001'))
|
||||
BACKEND_PORT = int(os.getenv("BACKEND_PORT", "5000"))
|
||||
PROVIDER_PORT = int(os.getenv("PROVIDER_PORT", "5001"))
|
||||
|
||||
# huggingface dataset repo for collected behavioral data
|
||||
HF_DATASET_REPO = os.getenv("HF_DATASET_REPO", "velocitatem/phantom-collected-data")
|
||||
|
||||
@@ -7,10 +7,9 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, Sequence
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
|
||||
from experiments.ml.arch import featurize_trajectory
|
||||
from lib.agent_probability import DEFAULT_AGENT_PRIOR, estimate_agent_probability
|
||||
|
||||
|
||||
DEFAULT_ARTIFACT_DIR = Path("data/separability")
|
||||
@@ -18,11 +17,7 @@ DEFAULT_ARTIFACT_DIR = Path("data/separability")
|
||||
|
||||
@dataclass
|
||||
class SeparabilityArtifacts:
|
||||
scaler: object
|
||||
classifier: object
|
||||
states: List[str]
|
||||
event_transitions: Dict[str, Dict[str, float]]
|
||||
feature_dim: int
|
||||
|
||||
|
||||
def _normalize_events(raw_events: Sequence[object]) -> List[object]:
|
||||
@@ -36,7 +31,9 @@ def _normalize_events(raw_events: Sequence[object]) -> List[object]:
|
||||
return events
|
||||
|
||||
|
||||
def _event_transition_distribution(events: Sequence[object]) -> Dict[str, Dict[str, float]]:
|
||||
def _event_transition_distribution(
|
||||
events: Sequence[object],
|
||||
) -> Dict[str, Dict[str, float]]:
|
||||
counts: Dict[str, Dict[str, int]] = {}
|
||||
for src_evt, dst_evt in zip(events, events[1:]):
|
||||
src_name = getattr(src_evt, "eventName", "unknown")
|
||||
@@ -47,11 +44,15 @@ def _event_transition_distribution(events: Sequence[object]) -> Dict[str, Dict[s
|
||||
distribution: Dict[str, Dict[str, float]] = {}
|
||||
for src, dsts in counts.items():
|
||||
total = float(sum(dsts.values()))
|
||||
distribution[src] = {dst: val / total for dst, val in dsts.items()} if total else {}
|
||||
distribution[src] = (
|
||||
{dst: val / total for dst, val in dsts.items()} if total else {}
|
||||
)
|
||||
return distribution
|
||||
|
||||
|
||||
def _kl_divergence(p: Dict[str, Dict[str, float]], q: Dict[str, Dict[str, float]]) -> float:
|
||||
def _kl_divergence(
|
||||
p: Dict[str, Dict[str, float]], q: Dict[str, Dict[str, float]]
|
||||
) -> float:
|
||||
eps = 1e-10
|
||||
total = 0.0
|
||||
for src, dsts in p.items():
|
||||
@@ -61,28 +62,28 @@ def _kl_divergence(p: Dict[str, Dict[str, float]], q: Dict[str, Dict[str, float]
|
||||
return float(total)
|
||||
|
||||
|
||||
def load_artifacts(artifact_dir: Path | str = DEFAULT_ARTIFACT_DIR) -> SeparabilityArtifacts:
|
||||
def load_artifacts(
|
||||
artifact_dir: Path | str = DEFAULT_ARTIFACT_DIR,
|
||||
) -> SeparabilityArtifacts:
|
||||
artifact_dir = Path(artifact_dir)
|
||||
scaler_path = artifact_dir / "scaler.joblib"
|
||||
model_path = artifact_dir / "classifier.joblib"
|
||||
metadata_path = artifact_dir / "metadata.json"
|
||||
|
||||
if not (scaler_path.exists() and model_path.exists() and metadata_path.exists()):
|
||||
if not metadata_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Separability artifacts not found in {artifact_dir}. Run sim.strong_learner.train first."
|
||||
f"Separability metadata not found in {artifact_dir}. Provide metadata.json with event transitions."
|
||||
)
|
||||
|
||||
scaler = joblib.load(scaler_path)
|
||||
classifier = joblib.load(model_path)
|
||||
with open(metadata_path, "r", encoding="utf-8") as fin:
|
||||
metadata = json.load(fin)
|
||||
|
||||
transitions = metadata.get("event_transitions")
|
||||
if not isinstance(transitions, dict):
|
||||
raise ValueError(
|
||||
"metadata.json must contain an 'event_transitions' object with 'human' and 'agent' kernels"
|
||||
)
|
||||
|
||||
return SeparabilityArtifacts(
|
||||
scaler=scaler,
|
||||
classifier=classifier,
|
||||
states=list(metadata["reference_states"]),
|
||||
event_transitions=metadata["event_transitions"],
|
||||
feature_dim=int(metadata["feature_dim"]),
|
||||
event_transitions=transitions,
|
||||
)
|
||||
|
||||
|
||||
@@ -92,37 +93,44 @@ def score_session(
|
||||
) -> dict:
|
||||
events = _normalize_events(raw_events)
|
||||
if not events:
|
||||
return {"prob_agent": 0.0, "delta_h": 0.0, "delta_a": 0.0}
|
||||
|
||||
reference_mdp = {"states": artifacts.states}
|
||||
features = featurize_trajectory(events, mdp=reference_mdp, input_dim=artifacts.feature_dim)
|
||||
scaled = artifacts.scaler.transform(features.reshape(1, -1))
|
||||
prob_agent = float(artifacts.classifier.predict_proba(scaled)[0, 1])
|
||||
return {
|
||||
"prob_agent": float(DEFAULT_AGENT_PRIOR),
|
||||
"delta_h": 0.0,
|
||||
"delta_a": 0.0,
|
||||
"gap": 0.0,
|
||||
}
|
||||
|
||||
session_dist = _event_transition_distribution(events)
|
||||
delta_h = _kl_divergence(session_dist, artifacts.event_transitions.get("human", {}))
|
||||
delta_a = _kl_divergence(session_dist, artifacts.event_transitions.get("agent", {}))
|
||||
gap = float(delta_h - delta_a)
|
||||
prob_agent = estimate_agent_probability(delta_h=delta_h, delta_a=delta_a)
|
||||
|
||||
return {
|
||||
"prob_agent": prob_agent,
|
||||
"delta_h": delta_h,
|
||||
"delta_a": delta_a,
|
||||
"gap": gap,
|
||||
}
|
||||
|
||||
|
||||
def estimate_alpha(prob_agent: float, delta_h: float, delta_a: float, temperature: float = 1.0) -> float:
|
||||
divergence_mass = delta_h + delta_a
|
||||
if divergence_mass <= 1e-8:
|
||||
return float(prob_agent)
|
||||
|
||||
ratio = delta_a / divergence_mass
|
||||
blended = 0.5 * prob_agent + 0.5 * ratio
|
||||
if temperature <= 0:
|
||||
return float(np.clip(blended, 0.0, 1.0))
|
||||
|
||||
scaled = 1.0 / (1.0 + np.exp(-temperature * (blended - 0.5)))
|
||||
return float(np.clip(scaled, 0.0, 1.0))
|
||||
def estimate_alpha(
|
||||
prob_agent: float,
|
||||
delta_h: float,
|
||||
delta_a: float,
|
||||
temperature: float = 1.0,
|
||||
prior_agent: float = DEFAULT_AGENT_PRIOR,
|
||||
) -> float:
|
||||
_ = prob_agent
|
||||
return estimate_agent_probability(
|
||||
delta_h=delta_h,
|
||||
delta_a=delta_a,
|
||||
temperature=temperature,
|
||||
prior_agent=prior_agent,
|
||||
)
|
||||
|
||||
|
||||
def score_sessions(raw_sessions: Iterable[Sequence[object]], artifacts: SeparabilityArtifacts) -> List[dict]:
|
||||
def score_sessions(
|
||||
raw_sessions: Iterable[Sequence[object]], artifacts: SeparabilityArtifacts
|
||||
) -> List[dict]:
|
||||
return [score_session(events, artifacts) for events in raw_sessions]
|
||||
|
||||
15
nx.json
15
nx.json
@@ -58,6 +58,21 @@
|
||||
"benchmark": {
|
||||
"cache": false
|
||||
},
|
||||
"whoclicked-publish": {
|
||||
"cache": false
|
||||
},
|
||||
"tpu-ray-bootstrap": {
|
||||
"cache": false
|
||||
},
|
||||
"tpu-ray-deps": {
|
||||
"cache": false
|
||||
},
|
||||
"tpu-ray-verify": {
|
||||
"cache": false
|
||||
},
|
||||
"tpu-ray-teardown": {
|
||||
"cache": false
|
||||
},
|
||||
"up": {
|
||||
"cache": false
|
||||
},
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
],
|
||||
"scripts": {
|
||||
"nx": "nx",
|
||||
"manim:render": "nx run manim:render",
|
||||
"manim:render-all": "nx run manim:render-all",
|
||||
"projects": "nx show projects",
|
||||
"graph": "nx graph",
|
||||
"web:dev": "nx run web:dev",
|
||||
|
||||
@@ -1,6 +1,26 @@
|
||||
$pdf_mode = 1;
|
||||
$pdflatex = 'pdflatex -synctex=1 -interaction=nonstopmode -file-line-error %O %S';
|
||||
$bibtex_use = 2; # run bibtex when needed
|
||||
$bibtex = 'bibtex %O %B';
|
||||
$bibtex_use = 2; # run biber when biblatex .bcf changes
|
||||
# biber cwd is paper/build; scripts/nx_paper.sh symlinks ../build/bib -> ../src/bib so
|
||||
# datasources log as bib/references.bib and latexmk's -e check works from paper/src
|
||||
$biber = 'biber %O %S';
|
||||
|
||||
# Stale latexmk db: biblatex uses biber + .bcf, but the fdb can keep a "bibtex" rule after a bad
|
||||
# run. Then biber never runs and citations stay undefined. Read whole fdb (small) so the rule
|
||||
# line is never missed after a long dependency list.
|
||||
for my $job (qw(main main-genpop summary)) {
|
||||
my $bcf = "../build/$job.bcf";
|
||||
my $bbl = "../build/$job.bbl";
|
||||
my $fdb = "../build/$job.fdb_latexmk";
|
||||
next unless -e $fdb && -e $bcf;
|
||||
my $drop = !-e $bbl;
|
||||
if ( !$drop && open my $fh, '<', $fdb ) {
|
||||
local $/;
|
||||
my $body = <$fh>;
|
||||
close $fh;
|
||||
$drop = 1 if defined $body && $body =~ /\["bibtex $job"\]/;
|
||||
}
|
||||
unlink $fdb if $drop;
|
||||
}
|
||||
$pdf_previewer = 'zathura %O %S';
|
||||
$clean_ext = 'synctex.gz bbl bcf run.xml fls fdb_latexmk glg glo gls ist blg lof lot out toc';
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from scenes import SCENE_ORDER
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Render thesis-defense Manim scenes")
|
||||
parser.add_argument(
|
||||
"--quality",
|
||||
default="qm",
|
||||
choices=["ql", "qm", "qh", "qk"],
|
||||
help="Manim quality preset",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--scene",
|
||||
action="append",
|
||||
dest="scenes",
|
||||
help="Scene name; repeat flag to render many",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--preview", action="store_true", help="Open video after each render"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--list", action="store_true", help="List available scenes and exit"
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def validate_requested(requested: list[str]) -> list[str]:
|
||||
missing = [name for name in requested if name not in SCENE_ORDER]
|
||||
if missing:
|
||||
choices = ", ".join(SCENE_ORDER)
|
||||
raise ValueError(f"Unknown scenes: {', '.join(missing)}. Choices: {choices}")
|
||||
return requested
|
||||
|
||||
|
||||
def run_manim(scene_file: Path, scene_name: str, quality: str, preview: bool) -> None:
|
||||
cmd = [sys.executable, "-m", "manim"]
|
||||
if preview:
|
||||
cmd.append("-p")
|
||||
cmd.extend([f"-{quality}", str(scene_file), scene_name])
|
||||
subprocess.run(cmd, cwd=scene_file.parent, check=True)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
if args.list:
|
||||
for scene in SCENE_ORDER:
|
||||
print(scene)
|
||||
return 0
|
||||
|
||||
scenes = validate_requested(args.scenes) if args.scenes else list(SCENE_ORDER)
|
||||
scene_file = Path(__file__).resolve().parent / "scenes.py"
|
||||
|
||||
try:
|
||||
for scene_name in scenes:
|
||||
run_manim(
|
||||
scene_file=scene_file,
|
||||
scene_name=scene_name,
|
||||
quality=args.quality,
|
||||
preview=args.preview,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
print(
|
||||
"manim executable not found. Install Manim in your Python environment.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
except ValueError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 2
|
||||
except subprocess.CalledProcessError as exc:
|
||||
return exc.returncode
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,2 +0,0 @@
|
||||
manim>=0.18,<1
|
||||
numpy>=1.24
|
||||
File diff suppressed because it is too large
Load Diff
@@ -44,6 +44,23 @@
|
||||
"command": "bash scripts/nx_paper.sh build-arxiv",
|
||||
"cwd": "."
|
||||
}
|
||||
},
|
||||
"build-summary": {
|
||||
"executor": "nx:run-commands",
|
||||
"outputs": [
|
||||
"{projectRoot}/build/summary.pdf"
|
||||
],
|
||||
"options": {
|
||||
"command": "bash scripts/nx_paper.sh build-summary",
|
||||
"cwd": "."
|
||||
}
|
||||
},
|
||||
"watch-summary": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "bash scripts/nx_paper.sh watch-summary",
|
||||
"cwd": "."
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
|
||||
@@ -16,7 +16,13 @@
|
||||
"chapters/04-results"
|
||||
"chapters/05-discussion"
|
||||
"chapters/06-conclusion"
|
||||
"chapters/acknowledgements"
|
||||
"article"
|
||||
"art12"))
|
||||
"art12")
|
||||
(LaTeX-add-labels
|
||||
"app:compute_budget"
|
||||
"tab:compute_derivation"
|
||||
"app:kl_zeros"
|
||||
"app:revelation_log"))
|
||||
:latex)
|
||||
|
||||
|
||||
@@ -630,3 +630,41 @@ Volume: 21},
|
||||
note = {Publisher: Institute of Mathematical Statistics},
|
||||
pages = {50 -- 60},
|
||||
}
|
||||
|
||||
@article{horace_he_and_thinking_machines_lab_defeating_2025,
|
||||
title = {Defeating {Nondeterminism} in {LLM} {Inference}},
|
||||
url = {https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/},
|
||||
doi = {10.64434/tml.20250910},
|
||||
abstract = {Reproducibility is a bedrock of scientific progress. However, it’s remarkably difficult to get reproducible results out of large language models.
|
||||
For example, you might observe that asking ChatGPT the same question multiple times provides different results. This by itself is not surprising, since getting a result from a language model involves “sampling”, a process that converts the language model’s output into a probability distribution and probabilistically selects a token.
|
||||
What might be more surprising is that even when we adjust the temperature down to 0This means that the LLM always chooses the highest probability token, which is called greedy sampling. (thus making the sampling theoretically deterministic), LLM APIs are still not deterministic in practice (see past discussions here, here, or here). Even when running inference on your own hardware with an OSS inference library like vLLM or SGLang, sampling still isn’t deterministic (see here or here).},
|
||||
language = {en},
|
||||
urldate = {2026-03-10},
|
||||
journal = {Thinking Machines Lab: Connectionism},
|
||||
author = {{Horace He and Thinking Machines Lab}},
|
||||
year = {2025},
|
||||
file = {Snapshot:/home/velocitatem/Zotero/storage/U5JG4CNM/defeating-nondeterminism-in-llm-inference.html:text/html},
|
||||
}
|
||||
|
||||
@misc{moritz_ray_2018,
|
||||
title = {Ray: {A} {Distributed} {Framework} for {Emerging} {AI} {Applications}},
|
||||
shorttitle = {Ray},
|
||||
url = {http://arxiv.org/abs/1712.05889},
|
||||
doi = {10.48550/arXiv.1712.05889},
|
||||
abstract = {The next generation of AI applications will continuously interact with the environment and learn from these interactions. These applications impose new and demanding systems requirements, both in terms of performance and flexibility. In this paper, we consider these requirements and present Ray---a distributed system to address them. Ray implements a unified interface that can express both task-parallel and actor-based computations, supported by a single dynamic execution engine. To meet the performance requirements, Ray employs a distributed scheduler and a distributed and fault-tolerant store to manage the system's control state. In our experiments, we demonstrate scaling beyond 1.8 million tasks per second and better performance than existing specialized systems for several challenging reinforcement learning applications.},
|
||||
urldate = {2026-03-13},
|
||||
publisher = {arXiv},
|
||||
author = {Moritz, Philipp and Nishihara, Robert and Wang, Stephanie and Tumanov, Alexey and Liaw, Richard and Liang, Eric and Elibol, Melih and Yang, Zongheng and Paul, William and Jordan, Michael I. and Stoica, Ion},
|
||||
month = sep,
|
||||
year = {2018},
|
||||
note = {arXiv:1712.05889 [cs]},
|
||||
keywords = {Computer Science - Machine Learning, Statistics - Machine Learning, Computer Science - Artificial Intelligence, Computer Science - Distributed, Parallel, and Cluster Computing},
|
||||
file = {Preprint PDF:/home/velocitatem/Zotero/storage/SUTDF5BP/Moritz et al. - 2018 - Ray A Distributed Framework for Emerging AI Applications.pdf:application/pdf;Snapshot:/home/velocitatem/Zotero/storage/5GV2DUAA/1712.html:text/html},
|
||||
}
|
||||
|
||||
@misc{biewald_experiment_2020,
|
||||
title = {Experiment {Tracking} with {Weights} and {Biases}},
|
||||
url = {https://www.wandb.com/},
|
||||
author = {Biewald, Lukas},
|
||||
year = {2020},
|
||||
}
|
||||
|
||||
@@ -7,18 +7,19 @@
|
||||
%% \end{figure}
|
||||
|
||||
\section{Introduction}
|
||||
\label{sec:introduction}
|
||||
|
||||
In this paper we present an exploration and defense against the presence of new commercial entities in digitally powered platforms, preserving market equilibrium in the age of AI. This research establishes the following contributions: definition and formalization of non-human transactors in e-commerce platforms, development of a testing-ground for capturing the behavioral essence of these transactors across a large variety of digital systems, construction of a discriminative model (to prove separability) as a strong learner for downstream mitigation of contamination by non-human entities, translation of such learned separability into existing dynamic pricing machine learning loops, and finally establishment of a high-level KPI-affecting causal effect and cost-saving framework for the future of internet commerce in the presence of such non-human learners.
|
||||
In this paper we present an exploration and defense against the presence of new commercial entities in digitally powered platforms, preserving market equilibrium in the age of AI. This research establishes the following contributions: definition and formalization of non-human transactors in e-commerce platforms, development of a testing-ground for capturing the behavioral essence of these transactors across a large variety of digital systems, construction of a discriminative model (to prove distinguishability) as a guiding teacher for downstream mitigation of contamination by non-human entities, translation of such learned distinguishability into existing dynamic pricing machine learning loops, and finally establishment of a high-level KPI-affecting causal effect and cost-saving framework for the future of internet commerce in the presence of such non-human learners.
|
||||
|
||||
This research effort touches a large variety of domains, spanning behavioral economics for understanding the rationality of behavior as theorized by the concept of homo economicus, agent-based modeling to translate our learned separability into disjoint dynamic pricing systems, reinforcement learning which serves as the SOTA for price-learners, and dynamic pricing and market equilibrium theory to understand the risks of possible supra-competitive pricing phenomena in cases of adversarial pricing systems driving the market out of equilibrium. \footnote{Given the rapid evolution of the field we acknowledge all developments with a cutoff set at the date of March 1st 2026.}
|
||||
This research effort touches a large variety of domains, spanning behavioral economics for understanding the rationality of behavior as theorized by the concept of homo economicus, agent-based modeling to translate our learned distinguishability into disjoint dynamic pricing systems, reinforcement learning which serves as the SOTA for price-learners, and dynamic pricing and market equilibrium theory to understand the risks of possible supra-competitive pricing phenomena in cases of adversarial pricing systems driving the market out of equilibrium. \footnote{Given the rapid evolution of the field we acknowledge all developments with a knowledge cutoff set at the date of March 1st 2026.}
|
||||
|
||||
\subsection{Motivation and Market Context}
|
||||
|
||||
The current innovation boom in generative artificial intelligence and its applications to knowledge-based work tasks has brought many competing technologies for browser-use automation, with benchmarks and evaluations \parencite{xia_evaluation-driven_2025} motivating the development of capabilities focused on commercial research, understanding, and transaction execution \parencite{xie_osworld_2024}. The ``AI Agent'' market is forecasted to grow from around USD 5-8 billion in 2025 to USD 42-52 billion by 2030. This surge reflects adoption in e-commerce, customer service, and enterprise automation, where agents handle interactions previously done by humans, raising the question of how these systems should be designed for future robustness as well as how to maintain a competitive edge in the analytical components of e-commerce platforms \parencite{markntel_advisors_global_2025}.
|
||||
|
||||
The key stakeholders affected by the threat of increasing agent-driven traffic include online businesses and platform operators (especially in bot-heavy sectors like retail, travel, and financial services), their security, fraud, and engineering teams, end users whose accounts and data are exposed and whose experience degrades, regulators and legal stakeholders responding to breaches and fraud, and the attackers or bot operators driving the automation \parencite{imperva_rapid_2025}.
|
||||
The key stakeholders affected by the threat of increasing agent-driven traffic include online businesses and platform operators (especially in bot-heavy sectors like retail, travel, and financial services), their security, fraud, and engineering teams, end users whose accounts and data are exposed and whose user experience degrades, regulators and legal stakeholders responding to breaches and fraud, and the attackers or bot operators driving the automation \parencite{imperva_rapid_2025}.
|
||||
|
||||
The industry has already seen legal action in cases like Amazon against Perplexity \parencite{ghaffary_amazon_2025}, stemming from the difficulty of identifying traffic from hybrid systems like the Commet browser. This paper explores such systems to better understand what the interaction data looks like and what it means for dynamic pricing and recommendation systems downstream. This observed impact indicates a need for prevention of secondary negative effects on the ``legacy'' systems which power modern revenue sources for many companies. Dynamic pricing algorithms rely on directly translating demand features $q$ to new price assignments $\hat{p}$ across a catalogue of products of size $N$. This opens opportunities to design a \textit{tabula rasa} of digital market mechanisms that will shape the future of commerce in the age of artificial intelligence.
|
||||
The industry has already seen legal action in cases like Amazon against Perplexity \parencite{ghaffary_amazon_2025}, stemming from the difficulty of identifying traffic from hybrid systems like the Comet browser. This paper explores such systems to better understand what the interaction data looks like and what it means for dynamic pricing and recommendation systems downstream. This observed impact indicates a need for prevention of secondary negative effects on the ``legacy'' systems which power modern revenue sources for many companies. Dynamic pricing algorithms rely on directly translating demand features $q$ to new price assignments $\hat{p}$ across a catalogue of products of size $N$. Our exploration of this field opens opportunities to design a \textit{tabula rasa} of digital market mechanisms that will shape the future of commerce in the age of artificial intelligence.
|
||||
|
||||
\subsection{Solution Space Overview}
|
||||
Dynamic pricing systems, as presented by \textcite{mueller_low-rank_2019}, often deal with sparse low-rank data of demand signals which, combined with contamination from agents, creates complex interactions that impact pricing. To further complicate the problem, certain commercial settings such as the one presented by \textcite{amjad_censored_2017} must address the true demand of products under censored observations. This provides a formulation for handling demand in our case with multiple kinds of commercial mediators: $\hat{q} \gets q_A + q_H$ where $q_A$ represents the distribution of demand generated by agentic mediators and $q_H$ represents that of true human demand, these are two distinct populations with divergent objective functions.
|
||||
@@ -26,13 +27,14 @@ Dynamic pricing systems, as presented by \textcite{mueller_low-rank_2019}, often
|
||||
We formally define interaction data as coming from some actor which can either be an agent ($A$) or human ($H$). For purposes of this research, an agent is an algorithmic loop with the ability to access a web platform and perform actions such as clicks, scrolls, and input field fills. The loop terminates when the internal large language model judges the provided task definition as complete. A detailed breakdown can be found in \cref{algagent-loop}.
|
||||
|
||||
\subsection{Research Questions}
|
||||
\label{sec:research_questions}
|
||||
|
||||
This dissertation is organized around one main research question and three supporting sub-questions:
|
||||
This dissertation is organized around one main research question and three supporting pillar questions:
|
||||
\begin{enumerate}
|
||||
\item[\textbf{Main RQ}] How can dynamic pricing systems preserve margin integrity when transaction orchestration is increasingly mediated by non-human agents?
|
||||
\item[\textbf{SQ1}] \textit{Separability}: Can agent and human sessions be reliably distinguished from behavioral interaction signals alone, without relying on network-level or device fingerprinting?
|
||||
\item[\textbf{SQ2}] \textit{Theoretical Impact}: What is the formal relationship between agent contamination levels and the erosion of pricing power in dynamic pricing systems?
|
||||
\item[\textbf{SQ3}] \textit{Robust Mitigation}: How can pricing policies be constructed to maintain margin integrity under unknown and non-stationary levels of agent contamination?
|
||||
\item[\textbf{SQ1}] \hypertarget{sq1}{}\textit{Distinguishability}: Can agent and human sessions be reliably distinguished from behavioral interaction signals alone, without relying on network-level or device fingerprinting?
|
||||
\item[\textbf{SQ2}] \hypertarget{sq2}{}\textit{Theoretical Impact}: What is the formal relationship between agent contamination levels and the erosion of pricing power in dynamic pricing systems?
|
||||
\item[\textbf{SQ3}] \hypertarget{sq3}{}\textit{Robust Mitigation}: How can pricing policies be constructed to maintain margin integrity under unknown and non-stationary levels of agent contamination?
|
||||
\end{enumerate}
|
||||
|
||||
|
||||
@@ -64,4 +66,6 @@ Extract final result $r$ from terminal state\;
|
||||
\end{algorithm}
|
||||
|
||||
|
||||
The previously described goal of separability allows us to formulate a task which entails taking raw interaction data for either actor and creating a composite demand estimate $\hat{q}$. We propose a robust optimization objective defined in our methodology, transforming the pricing problem into a form of Distributionally Robust Optimization \parencite{kuhn_distributionally_2025} where the learner must guard against adversarial contamination in observed demand distributors. In this setting we must learn to make decision that perform under the assumption of not having a single estimated probability distribution but under an ambiguity set of any distribution, of which we have limited information. In our case as stated is a mixture of distributions with a parameter which is unknown and non-stationary.
|
||||
The previously described goal of distinguishability allows us to formulate a task which entails taking raw interaction data for either actor and creating a composite demand estimate $\hat{q}$. We propose a robust optimization objective defined in our methodology, transforming the pricing problem into a form of distributionally robust optimization \parencite{kuhn_distributionally_2025} in which the learner guards against adversarial contamination in observed demand \emph{distributions}. The decision rule (in the policy) must perform when the data-generating mechanism is not a single known distribution but any member of an ambiguity set described only partially. Here that mechanism is a mixture whose weight and components need not be stationary.
|
||||
|
||||
Our work's contributions are best understood as a dependency chain centered around dynamic pricing. The work begins with a formal account of why a non-human mediator threatens pricing power, then we construct a platform capable of generating the interaction data needed for our study of that threat. On top of that \textit{substrate} we build behavioral models to determine whether human and agent traffic can be separated. The resulting contamination estimate is then translated into the pricing core itself, where it serves as a key signal for robust control under distributional uncertainty. The breadth of the thesis is therefore a consequence of the problem structure: the theoretical, behavioral, systems, and control components are not separate projects, but successive requirements of a single argument.
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
\section{Literature Review}
|
||||
\label{sec:literature_review}
|
||||
|
||||
To better understand all wedges of the current works, we must start by exploring the nature of agents, agentic computer use and web automation, complementing that with economic reasoning and strategic interaction. The final surface to cover, leads us to data-driven dynamic pricing under uncertainty. The key technical risk is not ``agents buying things'' per se, but agents shaping the behavioral and demand signals that downstream pricing systems consume and depend on. This latter case of agents shopping is currently pending legal action in the case of \textcite{noauthor_amazoncom_2026} which is currently being treated as a violation of the Computer Fraud and Abuse Act. The introduction of these mediating actor entities into economic systems, is further creating a threat of false-name bidding \parencite{yokoo_effect_2004}, which prior research has explored in a trading context. Other research on pseudonyms in dynamic systems, demonstrate whitewashing in AI agents which can ignore defensive mechanisms by re-entry with different identities \parencite{feldman_free-riding_2004}. Dynamic pricing assumes demand proxies are behaviorally meaningful, while bot detection aims at security and access control. The missing bridge is a principled framework for separating non-human reconnaissance from genuine human demand expression and integrating that separation into pricing heuristics without degrading legitimate user experience (in our research tracked by the user-experience index). This gap, is what our contribution aims to address, particularly for the aforementioned stakeholder groups.
|
||||
To situate the work we review agents and agentic computer use, web automation, economic reasoning, and strategic interaction, then turn to data-driven dynamic pricing under uncertainty. The main technical risk is not ``agents buying things'' in isolation but agents reshaping the behavioral and demand signals on which downstream pricing depends. Related litigation is already underway---for example \textcite{noauthor_amazoncom_2026} under the Computer Fraud and Abuse Act. Mediating actors surface classic concerns such as false-name bidding \parencite{yokoo_effect_2004} or pseudonymous re-entry which can whitewash reputation and weaken defenses \parencite{feldman_free-riding_2004}. Dynamic pricing assumes demand proxies are behaviorally meaningful, whereas classical bot detection targets security and access control. The gap we target is a principled way to separate non-human reconnaissance from genuine human demand expression and to fold that signal into pricing without degrading legitimate users (we track harm with a user-experience index), for the stakeholders named in the introduction.
|
||||
|
||||
\subsection{Agent Taxonomy and Definitions}
|
||||
|
||||
An agent in the context of artificial intelligence is generally defined by anything that can reason and act upon observations of its environments (collected through some sensory inputs) and carry out actions through effectors. Moreover, a rational agent is an entity that is capable of perceiving the world around them and taking actions to advance specified goals. This definition by \textcite{russell_artificial_2021} is further developed in an economic context by \textcite{parkes_economic_2015}, suggesting AI research attempts to construct a synthetic \textit{homo economicus}, which may also be termed \textit{machina economicus}.
|
||||
A specific class or taxon of this \textit{machina economicus}, the Large Language Model (LLM) agent, is defined as an autonomous system capable of achieving goals and adapting post-training, often without needing explicit code or fundamental model changes \parencite{xia_evaluation-driven_2025}.
|
||||
|
||||
We must however acknowledge the current SOTA as presented by OSWORLD simulations by \textcite{xie_osworld_2024} have demonstrated that multi-modal tasks across desktop and web interaction modes, have a top-performing score of only 12.24\% success, whereas humans have a higher 72\% success rate; this is linked to the lack of grounding of these agents and their inability of handling unexpected errors. This weakness matters for this research because it clarifies the near-term threat model: practical exploitation does not require a fully competent ``computer assistant'', only enough automation to perform high-volume reconnaissance actions (search/filter/open product pages, probe availability/price boundaries) that can contaminate behavioral signals. With the expected growth of these capabilities, this threat only becomes more perilous to revenue management systems.
|
||||
We must however acknowledge that OSWORLD simulations by \textcite{xie_osworld_2024} report a top success rate of only 12.24\% on multi-modal desktop and web tasks, versus about 72\% for humans, reflecting limited grounding and brittle recovery from unexpected errors. This weakness matters for this research because it clarifies the near-term threat model: practical exploitation does not require a fully competent ``computer assistant'', only enough automation to perform high-volume reconnaissance actions (search/filter/open product pages, probe availability/price boundaries) that can contaminate behavioral signals. With the expected growth of these capabilities, this threat only becomes more perilous to revenue management systems.
|
||||
|
||||
We model an agent session as producing some events with lower in-session conversion levels relative to humans, this we state in our assumption that $P(\text{purchase} \vert A) < P(\text{purchase} \vert H)$ but with a potentially higher volatility in $\hat{q}$, which we observe through the look-to-book metrics in our simulation.
|
||||
We model agent sessions as producing lower in-session conversion than humans, i.e.\ $P(\text{purchase} \vert A) < P(\text{purchase} \vert H)$, with potentially higher volatility in $\hat{q}$, which we proxy with look-to-book metrics in the simulator.
|
||||
|
||||
\subsection{Economic Agents: From Homo Economicus to Machina Economicus}
|
||||
|
||||
@@ -21,9 +22,9 @@ A HAP (HTTP Agent Profile) protocol has been developed as an internet draft by \
|
||||
|
||||
\subsection{Problem Evidence and Market Impact}
|
||||
|
||||
The statistical issue of contamination in dynamic pricing systems that observe demand features as a means to update prices has been documented in various previous contexts. The airline industry (which has accounted for 24\% of observed disruptions) has seen malicious activity with a measureable impact on skewing key performance indicators by behavior visible in the look-to-book metrics. Excessive reconnaissance traffic inflates search volume without corresponding completed bookings, thereby skewing demand forecasts and disrupting dynamic pricing models. Demand proxies have also been observed to cause significant threat to inventory management by creating artificial scarcity that distorts the demand-supply relationships in the enterprise model. Censored demand as shown by \textcite{amjad_censored_2017} can also be observed in low-bias demand under-estimation caused by a distortion effect coming from non-human traffic data \parencite{imperva_rapid_2025}.
|
||||
Contamination in dynamic pricing systems that observe demand features to update prices appears across several industries. Aviation (about 24\% of observed disruptions in one industry survey) illustrates how malicious or scripted traffic can skew KPIs visible in look-to-book metrics. Excessive reconnaissance traffic inflates search volume without corresponding completed bookings, thereby skewing demand forecasts and disrupting dynamic pricing models. Demand proxies have also been observed to cause significant threat to inventory management by creating artificial scarcity that distorts the demand-supply relationships in the enterprise model. Censored demand as shown by \textcite{amjad_censored_2017} can also be observed in low-bias demand under-estimation caused by a distortion effect coming from non-human traffic data \parencite{imperva_rapid_2025}.
|
||||
|
||||
When dynamic pricing algorithms operate on highly contaminated or noisy data, the risk grows significantly in creating inaccurate price inferences. The emergent mitigation driven by un-informed reward and regret signals might lead to price suppression for sales continuity which results in harming margins and resulting in a revenue loss. System that poorly fit undesired behavior might result in price gouging, which calls for strong guardrails while preserving targeted business strategy \parencite{mullapudi_reinforcement_2025}.
|
||||
When dynamic pricing algorithms train on highly contaminated or noisy data, mis-inference risk rises and revenue is threatened. Mis-specified reward and regret signals can push prices down to preserve volume, eroding margins, while misfit to legitimate demand can produce the opposite failure mode where both call for guardrails that preserve commercial intent \parencite{mullapudi_reinforcement_2025}.
|
||||
|
||||
|
||||
%Documented instances of agent-driven market disruptions - Quantitative evidence of pricing manipulation - Case studies from affected industries
|
||||
@@ -31,11 +32,11 @@ When dynamic pricing algorithms operate on highly contaminated or noisy data, th
|
||||
\subsection{Theoretical Foundations: Economic Parallels}
|
||||
|
||||
|
||||
Early hints of exploration of prices in a standard English auction explored by \textcite{varian_economic_1995} which hints at exploration of prices in a sequential manner, which leads to a marginally different cost to the bidder than the reservation price of the seller. This is a setting in which there is no cost incured by the buyer for their actions or exploring prices in the market. They propose that any agent responsable for the pricing of a good must be imune to dynamic strategies which might extract private information from a market. A key take-away which relates to the Vickery auction mechanism (also called a \textit{direct mechanism}) suggests that not only would defenses against such exploitation be necessary, but the construction of a mechanism in which revelation of the true willingness to pay is the dominant strategy for commerce.
|
||||
\textcite{varian_economic_1995} studies sequential exploration of prices in an English auction: the bidder's cost can differ slightly from the seller's reservation price. In that setting the buyer incurs no separate cost for searching or exploring prices. The authors argue that any party \emph{responsible} for pricing must be immune to dynamic strategies that extract private information. The link to the Vickrey (second-price) auction, a \textit{direct mechanism}, is that defenses against exploitation may need to pair with mechanisms in which truthful revelation of willingness to pay is incentive-compatible.
|
||||
|
||||
Like in classical revenue-maximizing auctions \parencite{roughgarden_cs364a_2013} we assume that the human actor in our system has a private valuation $v$ which we formally draw from intrinsically defined distributions. The important note here is that the agent proxy does not have a mechanism to convey this private information into the demand data which directly impacts the pricing systems.
|
||||
|
||||
The key component of this mediation between agents and commercial platforms lays in the transaction costs related to information gathering and negotiation. As proposed by \textcite{shahidi_coasean_2025} these costs are bound to collapse towards zero (which we demonstrate mathematically), calling for a re-evaluation of the boundaries between firms and markets. As argued by \textcite{coase_nature_1937}, the market participation and time associated with that participation, is critical part of the Coasean transaction cost logic which includes the discovery or relevant pricing within a given market. This process of price discovery without the presence of AI Agents can be time consuming and resource intensive. To build on top of this work we provide a proof of optimal conditions theorised by Coaes as an extension to AI-mediated markets.
|
||||
The mediation between agents and commercial platforms turns on transaction costs of information gathering and negotiation. \textcite{shahidi_coasean_2025} argue these costs tend toward zero (we give a complementary formal result in Section~3). \textcite{coase_nature_1937} treats search and participation time as central to Coasean transaction costs, including discovery of relevant prices. Price discovery without AI intermediaries is already costly. We extend this classical Coasean logic to AI-mediated markets.
|
||||
|
||||
% Economic foundations: relating the problem to options pricing theory. Cost of Information (COI) concept and its relevance
|
||||
|
||||
@@ -43,13 +44,13 @@ The key component of this mediation between agents and commercial platforms lays
|
||||
|
||||
\subsection{Landscape of Existing Work}
|
||||
|
||||
Explorations of the algorithmic collusion by LLMs \parencite{fish_algorithmic_2025} has demonstrated a cross-model tendency of market division with a strong sensitivity to instructions provided in the ``system prompt''. If a dynamic pricing algorithm which is trained to respond to market signals learns to coordinate with competitor agents (or become manipulated by those agents), the market equilibrium is under threat of destabilization. This is particularly true for Q-learning pricing learners as demonstrated by \textcite{calvano_artificial_2018}.
|
||||
Work on algorithmic collusion by LLMs \parencite{fish_algorithmic_2025} reports cross-model sensitivity to instructions in the ``system prompt,'' including tendencies toward market division. If a dynamic pricing algorithm which is trained to respond to market signals learns to coordinate with competitor agents (or become manipulated by those agents), the market equilibrium is under threat of destabilization. This is particularly true for Q-learning pricing learners as demonstrated by \textcite{calvano_artificial_2018}.
|
||||
|
||||
Our effort to combat contamination stems from research by \textcite{hardt_strategic_2015} on strategic classification, in conjunction with \textcite{liu_contextual_2024} who demonstrate a linear regret if contamination is ignored. The strategic classification adversarial effect comes from an effort to manipulate some representative features used in a learning pipeline, which can result in lower prices on loans or lower prices from dynamic pricing algorithms.
|
||||
|
||||
To bridge the gap between detection and robust pricing, we look at work in Distributionally Robust Optimization (DRO). As defined by \textcite{kuhn_wasserstein_2024}, DRO provides a framework for decision-making under ambiguity, where the true data distribution is unknown but lies within a ``Wasserstein ball'' of a target distribution. In our context, the ``ambiguity set'' represents the uncertainty introduced by agentic reconnaissance. By optimizing for the worst-case distribution within this set, pricing mechanisms can become resilient to the distributional shifts such as the ones caused by non-human actors, effectively robustifying the revenue function against the contamination described in our problem statement.
|
||||
|
||||
In order to create an environment in which prices can be tested against a demand estimate generated by some behavioral model, we take inspiration from the architecture proposed by \textcite{ie_recsim_2019} in the RecSim platform built for recommendation systems. By modeling the distinct user behavior as POMDPs we can generate faithful interactions which allow us to generalize, past the constraint which is also present in recommendation systems, of rarely having enough experience with individual actor's interactions for good recommendations without generalization. The key inspiration comes from the user choice modeling which we translate to a user transition model for each distinct actor type (agent or human). We further consider the possibility of modeling our quantitative research platform using dynamic Bayesian networks for the sake of tractability within the system. The contribution or RecSim enables researchers to better understand learning algorithms in fixed environments, a gap we identify as needing to be bridged within the space of dynamic pricing.
|
||||
To build an environment where prices face a demand estimate from a behavioral model, we draw on RecSim \parencite{ie_recsim_2019}. Modeling user behavior as partially observable Markov decision processes yields synthetic interaction that generalizes past the usual cold-start limit of per-user data. We translate RecSim-style user choice modeling into per-class transition models (human versus agent). Dynamic Bayesian networks remain a tractability option for the full platform. RecSim's main contribution is a sandbox for recommender learners and we adapt that idea to dynamic pricing under contamination into a sort of contaminated pricing simulator.
|
||||
% TODO: mention https://github.com/meta-pytorch/OpenEnv/tree/main/envs/browsergym_env
|
||||
|
||||
We also acknowledge the difficulty in similarly affected fields such as authorship, where \textcite{ganie_uncertainty_2025} demonstrate the theoretical limits of the distributional divergence between text authored by a human or large language model. Their approach of computing the divergence between two distributions demonstrates purely theoretically that no classifier can outperform random guessing on their particular task. This is yet another factor to take into consideration when exploring the potential mitigation strategies.
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
\section{Methodology}
|
||||
\label{sec:methodology}
|
||||
|
||||
% Extra notes and clarifications: we observed some humans and get their transition probabilities between event types
|
||||
% We modify behavioral profiles of transition matrices with price elasticity matrices generated by sample valuations of a distributing.
|
||||
|
||||
This section details the theoretical and practical framework developed to address dynamic pricing under the influence of non-human actors. We begin by formalizing the problem environment and the nature of the actors. We then derive the \textit{Cost of Information} (COI) theorem, proving the erosion of pricing power in the limit of agent saturation. Following this, we outline our generative contamination strategy using GOFAI-driven separability and transition probability learning. Finally, we formulate the robust control problem as a Stackelberg game solved via Distributionally Robust Reinforcement Learning (DR-RL) with constructed ambiguity sets.
|
||||
This section addresses the theoretical and practical framework developed to address dynamic pricing under the influence of non-human actors. We begin by formalizing the problem environment and the nature of the actors. We then derive the \textit{Cost of Information} (COI) theorem, proving the erosion of pricing power in the limit of agent saturation. Following this, we outline our generative contamination strategy using GOFAI-driven distinguishability and transition probability learning. Finally, we formulate the robust control problem as a Stackelberg game solved via Distributionally Robust Reinforcement Learning (DR-RL) with constructed ambiguity sets.
|
||||
|
||||
\subsection{Problem Formalization}
|
||||
|
||||
We define a commercial environment where the platform interacts with a stream of sessions. Let $\mathcal{S}$ denote the set of all sessions. Each session $s \in \mathcal{S}$ is generated by an actor belonging to a latent class $\theta_s \in \{H, A\}$, where $H$ denotes Human and $A$ denotes Agent.
|
||||
We define a commercial environment where the platform interacts with a stream of sessions. Let $\mathcal{S}$ denote the set of all sessions. Each session $s \in \mathcal{S}$ is generated by an actor belonging to a latent class $Y_s \in \{H, A\}$, where $H$ denotes Human and $A$ denotes Agent.
|
||||
|
||||
Each session produces a trajectory of observable events $\tau_s = (e_{s,1}, \ldots, e_{s,L_s})$. An event $e_{s,k}$ is a tuple defined as:
|
||||
\begin{equation}
|
||||
@@ -20,12 +21,12 @@ where:
|
||||
\item $t_{s,k} \in \mathbb{R}_+$ is the continuous timestamp.
|
||||
\end{itemize}
|
||||
|
||||
The platform does not directly observe the true underlying demand function $d(p)$. Instead, it observes a behavioral proxy $\hat{q}_t$, which is a composite signal derived from the mixture of actor types. We define the demand proxy for product $i$ at epoch $t$ as a weighted aggregation of events:
|
||||
The platform does not directly observe the true underlying demand function $d(p)$ where $d \in \mathbb{R}^{+}$ and our proxy $\hat{q} \in \mathbb{R}^{+}$. Instead, it observes a behavioral proxy $\hat{q}_t$, which is a composite signal derived from the mixture of actor types. We define the demand proxy for product $i$ at epoch $t$ as a weighted aggregation of events:
|
||||
\begin{equation}
|
||||
\label{eq:qhat}
|
||||
\hat{q}_{t,i} = \sum_{s \in \mathcal{S}_t} \sum_{k=1}^{L_s} \omega(a_{s,k}) \cdot \mathbb{1}[i_{s,k} = i]
|
||||
\hat{q}_{t,i} = \sum_{s \in \mathcal{S}_t} \sum_{k=1}^{L_s} \omega(a_{s,k}) \cdot \mathbf{1}[i_{s,k} = i]
|
||||
\end{equation}
|
||||
where $\omega: \mathcal{A} \to \mathbb{R}_+$ assigns weights to actions based on their signal strength regarding willingness to pay.
|
||||
where $\omega: \mathcal{A} \to \mathbb{R}^+$ assigns weights to actions based on their signal strength regarding willingness to pay.
|
||||
|
||||
In the current engine implementation, we use the normalized variant of this proxy for each step:
|
||||
\begin{equation}
|
||||
@@ -34,19 +35,21 @@ In the current engine implementation, we use the normalized variant of this prox
|
||||
with fixed category-level weights (cart, dwell, nav, filter) following the same rank order from Table~\ref{tab:action_space}. This keeps the signal dense and directly usable in the simulator.
|
||||
|
||||
\subsubsection{Actor Types and Demand Curves}
|
||||
We formalize the heterogeneity of actors by introducing a type space $\Theta$. An actor of class $Y_s$ is further parameterized by a type $\theta \sim \mathcal{D}_{Y}$. This type determines the actor's demand response function $d(p; \theta)$, sampled from a distribution of possible demand curves. The total observed demand is a stochastic process governed by the naively defined mixture:
|
||||
We formalize the heterogeneity of actors by introducing a type space $\Theta$. An actor of class $Y_s$ is further parameterized by a type $\theta \sim \mathcal{D}_{Y_s}$. This type determines the actor's demand response function $d\!\left(p \mid Y_s,\theta\right)$, sampled from a distribution of possible demand curves. In compact form, demand remains price-dependent as $d(p\mid Y=y)$. The total observed demand is a stochastic process governed by the naively defined mixture:
|
||||
\begin{equation}
|
||||
\label{eq:mixture_demand}
|
||||
Q(p) = (1-\alpha) \cdot \mathbb{E}_{\theta \sim \mathcal{D}_H}[d(p; \theta)] + \alpha \cdot \mathbb{E}_{\theta \sim \mathcal{D}_A}[d(p; \theta)] + \epsilon_t
|
||||
Q(p) = (1-\alpha) \cdot \mathbb{E}_{\theta \sim \mathcal{D}_H}[d(p\mid Y=H,\theta)] + \alpha \cdot \mathbb{E}_{\theta \sim \mathcal{D}_A}[d(p\mid Y=A,\theta)] + \epsilon_t
|
||||
\end{equation}
|
||||
where $\alpha \in [0, 1]$ represents the contamination parameter (proportion of agents) and $\epsilon_t$ is non-stationary market noise.
|
||||
We address that the composition of two non-stationary variables can cause difficulty distinguishing the sources of possible dynamic composition in online environments, whether from market noise or agents specifically.
|
||||
Accounting for behavioral and market variation, we also treat $\epsilon_t$ as absorbing serving-path variability from LLM infrastructure (e.g., batch-size-dependent inference behavior under changing load), which appears stochastic at the request level even under greedy decoding \parencite{horace_he_and_thinking_machines_lab_defeating_2025}.
|
||||
|
||||
|
||||
|
||||
\subsection{Cost of Information (COI) Framework}
|
||||
|
||||
The platform's pricing power comes from information asymmetry: users who express strong interest signals pay more than the base price. We quantify this markup as the \textit{Cost of Information} (COI), which represents the average premium extracted above marginal cost. COI measures the revenue at risk when information asymmetry collapses.
|
||||
A top-level view in the current AI discourse is that sufficiently large productivity gains can induce vertical deflation through cost compression and supply expansion \parencite{rachitsky_marc_2026}. Our contribution is narrower and mechanism-level: even under long-run deflation, platform revenue still depends on short-run information costs to the user. We formalize that rent as the Cost of Information (COI) and study how agentic reconnaissance accelerates its erosion.
|
||||
The platform's pricing power comes from information asymmetry: users who express strong interest signals pay more than the base price. We quantify this markup as the \textit{Cost of Information} (COI), which represents the average premium extracted above marginal cost. The intuition behind this being a cost comes from the perspective of the user who is interacting with the platform, where the user is the one incurring that ``cost.'' COI measures the revenue at risk when information asymmetry collapses.
|
||||
A top-level view in the current AI discourse is that sufficiently large productivity gains can induce vertical deflation (vertical supply chain price decrease) through cost compression and supply expansion \parencite{rachitsky_marc_2026}. Our contribution is narrower and mechanism-level: even under long-run deflation, platform revenue still depends on short-run information costs to the user. We formalize that rent as the Cost of Information (COI) and study how agentic reconnaissance accelerates its erosion.
|
||||
|
||||
\begin{definition}[Cost of Information]
|
||||
Let $\pi(\tau)$ be a pricing policy mapping interaction histories to prices. The COI is defined as:
|
||||
@@ -87,13 +90,14 @@ where $\mathbb{E}[P]$ is the expected price charged by the policy and $\underlin
|
||||
\draw[<->, thick, red] (\pmin, 2.0) -- (\mean, 2.0) node[midway, above] {COI};
|
||||
|
||||
\end{tikzpicture}
|
||||
\caption{Illustration of the Cost of Information (COI). The COI is defined as the difference between the expected price $\mathbb{E}[p]$ realized by the policy and the minimum viable price $\underline{p}$.}
|
||||
\caption{Illustration of the Cost of Information (COI). The COI is defined as the difference between the expected price $\mathbb{E}[p]$ realized by the policy and the minimum viable price $\underline{p}$. The abstraction we assume is that the reservation price $\underline{p}$ already has some innate margin and would always result in at least a break-even transaction.}
|
||||
\label{fig:coi_illustration}
|
||||
\end{figure}
|
||||
|
||||
We now formally demonstrate that standard dynamic pricing mechanisms are not incentive-compatible with high-frequency agentic traffic. As the number of independent competitive agents $N$ querying the system grows, the platform's ability to sustain a COI vanishes.
|
||||
|
||||
A fundamental assumption for our claim lies in the alignment of the AI agent through its prompt which has been demonstrated by \cite{fish_algorithmic_2025} to cause strong collusive behavior under linguistic nudges. This assumption can be generalized to the human user asking the agent to research products with a minimizing objective.
|
||||
\paragraph{Assumption Scope}
|
||||
The theorem and core experiments in this thesis assume a non-collusive independent-session setting: each agent queries prices independently and does not share sampled quotes across agents. Collusive coordination is outside the current proof scope and is treated as an extension scenario.
|
||||
|
||||
\begin{theorem}[COI Erosion in the Limit]
|
||||
Let $N$ be the number of independent, utility-maximizing agents querying the platform. Let $p_{(1)}$ be the first order statistic (minimum) of the prices offered to these agents. As $N \to \infty$, the Cost of Information converges to 0.
|
||||
@@ -125,7 +129,7 @@ Since the integrand vanishes as $N \to \infty$ for all $t > \underline{p}$, the
|
||||
\end{proof}
|
||||
|
||||
|
||||
This result naively proves that standard pricing policies $\pi$ fail to extract surplus in the presence of large-scale agentic search, necessitating a robust counter-mechanism.
|
||||
This result implies that standard pricing policies $\pi$ cannot extract the same surplus under large-scale agentic search without additional structure, which motivates the robust control layer below.
|
||||
|
||||
% The DRO objective creates a lower bound on COI extraction, effectively guaranteeing a minimum margin even in the presence of adversarial agents. we need to prove this and demonstrate that in a theorem.
|
||||
|
||||
@@ -134,20 +138,22 @@ This result naively proves that standard pricing policies $\pi$ fail to extract
|
||||
|
||||
\subsection{System Architecture: Hybrid Kappa-Lambda Architecture}
|
||||
|
||||
In order for our research to have grounding in interactions we built a robust e-commerce web-platform. We initially conducted a survey of the leading platforms of airlines and hotel booking sites to identify the specific interface patterns that effectively manage complex travel data. Our analysis revealed a clear industry standard: while both sectors rely on tabbed service selection and left-sidebar filtering to streamline navigation, they diverge in result presentation: airlines utilize visual date-price bars and multi-step wizards to optimize for logistical transparency, whereas hotel platforms leverage image-led cards and scarcity triggers to drive emotional engagement and urgency. Our web framework defines a highly agnostic boilerplate which can be seeded with any data-modality with an easy-to-tailor pattern, which we leverage to define a \texttt{hotel} and \texttt{airline} mode. Both modes are then individually deployed via an environment level argument which adjusts the proxy routing with a custom middleware inside next.js to render only the desired mode. The purpose of this was to create a baseline adaptable to any use-case or desired commercial application.
|
||||
In order for our research to have grounding in interactions we built a robust e-commerce web-platform. In this framing Kappa represents streamed processing and Lambda batch operations as is given by terminology in big-data processing. We initially conducted a survey of the leading platforms of airlines and hotel booking sites to identify the specific interface patterns that effectively manage complex travel data. To better understand the playing field, we collected artifacts on design across various airlines and hotels. While both sectors rely on tabbed service selection and left-sidebar filtering to streamline navigation, they diverge in result presentation: airlines utilize visual date-price bars and multi-step wizards to optimize for logistical transparency, whereas hotel platforms leverage image-led cards and scarcity triggers to drive emotional engagement and urgency. Our web framework defines a highly agnostic boilerplate which can be seeded with any data-modality with an easy-to-tailor pattern, which we leverage to define a \texttt{hotel} and \texttt{airline} mode. Both modes are then individually deployed via an environment-level argument which adjusts the proxy routing with custom middleware in Next.js to render only the desired mode. The purpose of this was to create a baseline adaptable to any use-case or desired commercial application.
|
||||
|
||||
The architecture of this platform begins with the deployed web-apps posting interaction data to our backend which processes them and stores each ingested interaction into a kafka cluster. This serves as our data reservoir tracking and associating each interaction with its session and importantly with which experiment it belongs to. Not only do we track the behavioral interactions, but our pricing provider micro-service, once called by the frontend reports the observed/queried price-product into kafka. This kafka cluster is subscribed to by our pipeline which is configured on a schedule in Airflow, with the possibility of manual trigger. The final stage of the pricing pipeline, submits computed dynamic pricing results into a redis database for quick updates which is then read by the pricing provider and displayed on the webapp. This is a very generic end-to-end mechanism which is applicable to a variety of different e-commerce tasks. We intentionally put emphasis on the development of this infrastructure to establish a reproducible framework for interaction and to minimize any noise.
|
||||
The architecture begins with deployed web applications posting interaction data to a backend that stores each record in Apache Kafka. Kafka acts as the reservoir linking sessions to experiments. Behavioral events and, separately, price observations from the pricing-provider microservice (invoked by the frontend) land in Kafka topics. A scheduled Airflow pipeline (with manual triggers) consumes the stream and the final pricing stage writes vectors to Redis for low-latency reads by the provider and display in the client. This design pattern allows us to generalize to other commercial settings, where Kafka is used for durability and replay, Redis for serving and quick queries. We invested in this stack to keep runs reproducible and to limit extraneous variance so the same skeleton applies across e-commerce settings.
|
||||
|
||||
\paragraph{Public Web Artifact} We transition the Kappa like architecture of the data collection to a Lambda architecture for actual learning in a surrogate environment. This allows us to move faster on data which is provided and helps us create a feedback loop for production deployment. To support further research in this intersection of fields we release P4P \footnote{\url{https://github.com/velocitatem/p4p}} as a public repository providing the interaction layer of the PHANTOM framework. This provides a configurable storefront which can be tailored to any commercial setting with a standardized session-level event tracking. We document the API adapters or what the framework expects in terms of schemas for pricing providers and log ingestion servicse. The repository is intended for controlled experimentation and method replication rather than production commerce deployment.
|
||||
\paragraph{Public Web Artifact} We transition the Kappa-like architecture of the data collection to a Lambda architecture for actual learning in a surrogate environment. This allows us to move faster on data which is provided and helps us create a feedback loop for production deployment. To support further research in this intersection of fields we release P4P \footnote{\url{https://github.com/velocitatem/p4p}} as a public repository providing the interaction layer of the PHANTOM framework. This provides a configurable storefront which can be tailored to any commercial setting with a standardized session-level event tracking. We document the API adapters and expected schemas for pricing providers and log ingestion services. The repository is intended for controlled experimentation and method replication rather than production commerce deployment.
|
||||
|
||||
\paragraph{Public Dataset} For reproducibility of the behavioral analysis and distinguishability experiments, we also release the interaction dataset used in this thesis as \textit{WhoClickedIt}. The dataset is hosted on Hugging Face \footnote{\url{https://huggingface.co/datasets/velocitatem/whoclickedit}} and is distributed as one flattened event sheet (\texttt{whoclicked.csv}) with explicit labels (\texttt{actor\_type}, \texttt{is\_agent}, and \texttt{record\_type}). The dataset card on that page documents the schema, collection process, and known limitations.
|
||||
|
||||
|
||||
\subsubsection{DevOps Principles}
|
||||
|
||||
Reproducible results are key to quality research platforms, this is taken into mind when deploying and working with our research platform. From a deployment standpoint the platform can be deployed across a large variety of providers and can be run locally. When developing a new interaction modality apart from the ones that come out of the box, a simple template pattern can be followed. The middleware of the framework is designed to properly render the chosen modality from environmental variables, thus deployment of different or parallel version of the software can be easily parametrized.
|
||||
Reproducibility guided deployment choices: the stack runs locally or on common cloud providers. New interaction modalities follow a small template; middleware reads environment variables so parallel deployments (e.g.\ staging versus production-like experiments) differ only in configuration, not in forked codebases.
|
||||
|
||||
\subsubsection{Online Dynamic Pricing}
|
||||
|
||||
In order to collect data from actors under correct conditions we replicate a naive and simple dynamic pricing algorithm which runs in the background during the experiments.
|
||||
To expose participants to state-dependent prices without over-constraining the study, we run a transparent surge--discount heuristic in the background during data collection.
|
||||
The dynamic pricing done is handled by a pipeline which computes a demand estimate on a per-product basis of a specific window of the data, defined by the period $T$ which by default is 5 minutes. This dynamic pricing pipeline computes a demand estimate vector $\hat{q} \in \mathbb{R}^N$ by a weighted sum of interactions for each product, it additionally computes a price elasticity vector $\hat{\epsilon}$ in the same dimensions as our demand. The final features matrix is of the size $N \times 2$ which we translate to a new price vector $\hat{p} \in \mathbb{R}^N$.
|
||||
|
||||
|
||||
@@ -155,14 +161,14 @@ The transformation that governs this dynamic pricing is a very simple surge-base
|
||||
|
||||
\begin{equation}
|
||||
\hat{p}_i = \begin{cases}
|
||||
p_{0,i} \cdot \lambda_{\text{surge}} & \text{if } \hat{q}_i \geq \theta_{\text{high}} \\
|
||||
p_{0,i} \cdot \lambda_{\text{disc}} & \text{if } \hat{q}_i \leq \theta_{\text{low}} \\
|
||||
p_{0,i} & \text{otherwise}
|
||||
p_{0,i} \cdot \lambda_{\text{surge}} & \text{if } \hat{q}_i \geq \varrho_{\text{high}} \\
|
||||
p_{0,i} \cdot \lambda_{\text{disc}} & \text{if } \hat{q}_i \leq \varrho_{\text{low}} \\
|
||||
p_{0,i} & \text{otherwise}
|
||||
\end{cases}
|
||||
\quad \forall i \in \{1, \ldots, N\}
|
||||
\end{equation}
|
||||
|
||||
where $p_0 \in \mathbb{R}^N$ is the base price vector (which is seeded into our database distinctly for each mode of the commerce platform), $\theta_{\text{high}}, \theta_{\text{low}} \in \mathbb{R}$ are demand thresholds defining surge and discount regions, and $\lambda_{\text{surge}}, \lambda_{\text{disc}} \in \mathbb{R}^+$ are multiplicative factors with typical values $\lambda_{\text{surge}} = 1.2$ and $\lambda_{\text{disc}} = 0.9$. This piecewise function enables rapid price adjustment in response to observed demand without requiring complex elasticity estimation or historical calibration, allowing us to expose actors within our experiments to a system with a dynamic component of pricing.
|
||||
where $p_0 \in \mathbb{R}^N$ is the base price vector (which is seeded into our database distinctly for each mode of the commerce platform), $\varrho_{\text{high}}, \varrho_{\text{low}} \in \mathbb{R}$ are demand thresholds defining surge and discount regions, and $\lambda_{\text{surge}}, \lambda_{\text{disc}} \in \mathbb{R}^+$ are multiplicative factors with typical values $\lambda_{\text{surge}} = 1.2$ and $\lambda_{\text{disc}} = 0.9$. This piecewise function enables rapid price adjustment in response to observed demand without requiring complex elasticity estimation or historical calibration, allowing us to work with actors within our experiments to a system with a dynamic component of pricing.
|
||||
|
||||
% For our offline experimental setting, we generalize a master value function that can encompass different demand estimation and pricing strategies.
|
||||
%
|
||||
@@ -174,21 +180,45 @@ where $p_0 \in \mathbb{R}^N$ is the base price vector (which is seeded into our
|
||||
|
||||
\subsection{Experimental Design}
|
||||
|
||||
We start from a practical constraint: we do not have access to proprietary production data. Because of that, we design our own fictional platform that still represents how commercial platforms work in the real world. The design comes from a survey of hotel and airline websites, where we extracted common interface components and used them as a high-level template for dynamic pricing environments.
|
||||
% We start from a practical constraint: we do not have access to proprietary production data. Because of that, we design our own fictional platform that still represents how commercial platforms work in the real world. The design comes from a survey of hotel and airline websites, where we extracted common interface components and used them as a high-level template for dynamic pricing environments.
|
||||
In the aforementioned platform we develop for our experiments, we use the surveyed websites and create an \textit{average} representation of what the most expected interfaces would be by extracting common components and designing a high level template for dynamic pricing environments.
|
||||
|
||||
The interface is organized as a product catalog where each product belongs to a time-bounded price vector (for example, a daily pricing period). During each period we collect interaction data by instrumenting UI components and predefined action templates that are still customizable. This gives us control without losing realism.
|
||||
|
||||
The interface is organized as a product catalog where each product belongs to a time-bounded price vector (for example, a daily pricing period). During each period we collect interaction data by instrumenting UI components and predefined action templates that are still customizable. That yields controlled variation while keeping the interface controlled-for.
|
||||
|
||||
Since users act with motivations, we define a pool of tasks (jobs to be done) and assign tasks randomly to participants.
|
||||
The task pool is stored as a structured table with fields \texttt{id}, \texttt{created\_at}, \texttt{task\_name}, \texttt{task\_description}, and \texttt{task\_def\_of\_done}. We formulate the tasks as compact jobs-to-be-done rather than as strict click scripts, because the target is to elicit realistic browsing and comparison behavior which can capture nuance of different people. In hotel mode the assigned tasks include \textit{Cheapest Room}, \textit{Cheapest Room w/ View}, \textit{MultiStep Cheapest Room}, \textit{The Digital Nomad (Executive)}, and \textit{The 3-Way Tradeoff (Desk + Quiet + Flexible)}. These prompts deliberately require critical thought in search, inspection of room details, comparison of amenities or images, return visits to the listing page, and a final booking decision which create a degree of cognitive load. In airline mode we use \textit{Last-Minute One-Way Flight}, where the actor must urgently travel to LAX from either SEA or JFK within the next 1--3 days, inspect at least a small set of candidate itineraries, and then book a reasonable earliest departure.
|
||||
A representative task is to find the cheapest feasible catalog item under explicit constraints while removing strict financial limits so we avoid trivial optimization behavior. Participants are also randomly assigned to one experimental platform mode (hotel or airline). Once assigned, they are dropped into the experiment with an actor ID. Under each experiment ID, we can observe multiple sessions across time and gather long interaction traces for the same actor.
|
||||
We discuss limitations and choices made in this experimental design in Section~\ref{sec:limitations_risks}.
|
||||
The task pool is stored as a structured table with fields \texttt{id}, \texttt{created\_at}, \texttt{task\_name}, \texttt{task\_description}, and \texttt{task\_def\_of\_done}. We formulate the tasks as compact jobs-to-be-done rather than as rigid instructions, because the target is to elicit realistic browsing and comparison behavior which can capture nuance of different people. In hotel mode the assigned tasks include \textit{Cheapest Room}, \textit{Cheapest Room w/ View}, \textit{MultiStep Cheapest Room}, \textit{The Digital Nomad (Executive)}, and \textit{The 3-Way Tradeoff (Desk + Quiet + Flexible)}. These prompts deliberately require critical thought in search, inspection of room details, comparison of amenities or images, return visits to the listing page, and a final booking decision which create a degree of cognitive load. In airline mode we use \textit{Last-Minute One-Way Flight} or \textit{Family/Work Emergency Travel}, where the actor must urgently travel to LAX from either SEA or JFK within the next 1 to 3 days, inspect at least a small set of candidate itineraries, and then book a reasonable earliest departure. Figure~\ref{fig:exp_design_tree} summarizes the assignment tree.
|
||||
|
||||
The human data collection involved 18 participants, all of whom provided explicit informed consent prior to their session. Participants had an average age of 21 years and were recruited from a university population. Alongside the 18 human sessions we ran 18 agent sessions of equivalent task scope, giving a balanced dataset of 36 labeled trajectories. Each participant was assigned a single platform mode and a single task drawn from the pool, and completed the session independently without guidance on navigation or pricing strategy.
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\resizebox{0.88\columnwidth}{!}{%
|
||||
\input{chapters/figures/experiment_design_tree.tex}
|
||||
}
|
||||
\caption{Experimental design decision tree for participant assignment.}
|
||||
\label{fig:exp_design_tree}
|
||||
\end{figure}
|
||||
|
||||
A representative task is to find the cheapest feasible catalog item under explicit constraints while removing strict financial limits so we avoid trivial optimization behavior. Participants are also randomly assigned to one experimental platform mode (hotel or airline). Once assigned, they are dropped into the experiment with an actor ID. Under each experiment ID, we can observe multiple sessions across time and gather long interaction traces for the same actor. This de-risks our lower sample size of individuals by allowing broad interaction data to come from each one.
|
||||
|
||||
The human data collection involved 13 participants, all of whom provided explicit informed consent prior to their session. Participants had an average age of 21 years and were recruited from a university population. Alongside the 13 human sessions we ran 16 agent sessions of equivalent task scope, yielding 29 labeled trajectories in total (45\% human, 55\% agent). Each participant was assigned a single platform mode and a single task drawn from the pool, and completed the session independently without guidance on navigation or pricing strategy.
|
||||
|
||||
To evaluate quality and realism of the setup, we store both structured event logs and full interaction transcripts. This lets us combine quantitative analysis with transcript-level qualitative findings. The result is an isolated system where we can control the interaction process while preserving realistic behavior.
|
||||
|
||||
Operationally, goals and experiment runs are tracked in PostgreSQL (goal table, run table, and assignment mapping). This data-acquisition phase is the first half of the methodology and is intentionally a disconnected component that feeds the later contributions. The second half uses collected behavioral traces to separate classes $\theta \in \{A,H\}$ with session-conditioned probability estimates, then injects those estimates into the pricing learner.
|
||||
Operationally, goals and experiment runs are tracked in PostgreSQL (goal table, run table, and assignment mapping). This data-acquisition phase is the first half of the methodology and is intentionally a disconnected component that feeds the later contributions. The second half uses collected behavioral traces to distinguish classes $Y \in \{A,H\}$ with session-conditioned probability estimates, then injects those estimates into the pricing learner.
|
||||
|
||||
Our process follows three stages: (1) observe and \textit{vectorize} behavioral interactions, (2) learn separability to characterize human versus agent patterns, and (3) use the learned signal to train a defensive policy in a controlled dynamic-pricing simulator.
|
||||
Our process follows three stages: (1) observe and \textit{vectorize} behavioral interactions, (2) learn distinguishability to characterize human versus agent patterns, and (3) use the learned signal to train a defensive policy in a controlled dynamic-pricing simulator.
|
||||
|
||||
Figure~\ref{fig:phantom_unified_architecture} summarizes the full mechanism from online interaction capture to divergence-based contamination scoring and robust control of pricing decisions.
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\resizebox{\textwidth}{!}{%
|
||||
\input{chapters/hero_architecture_figure.tex}
|
||||
}
|
||||
\caption{Unified PHANTOM defense architecture. (a) Online serving and logging with behavioral and price-query streams. (b) Distinguishability layer that estimates KL divergence to human/agent prototypes and derives session-level contamination scores. (c) Distributionally robust pricing control that optimizes under an ambiguity set while penalizing COI leakage and tracking UX cost.}
|
||||
\label{fig:phantom_unified_architecture}
|
||||
\end{figure}
|
||||
|
||||
\begin{figure}[ht]
|
||||
\resizebox{\columnwidth}{!}{%
|
||||
@@ -201,16 +231,15 @@ Our web platform (developed in similar spirit to RecSim \parencite{ie_recsim_201
|
||||
|
||||
To speak to realism, user interviews reported that the platform architecture mirrored standard booking interfaces and reduced the cognitive load required to learn the system. One participant described the flow as ``intuitive'' and close to a ``normal'' transaction, suggesting observed behavior was primarily driven by pricing treatment rather than interface novelty.
|
||||
|
||||
The dynamic pricing mechanism elicited immediate behavioral adjustments. Participants were sensitive to price volatility: sudden boosts triggered urgency and faster booking attempts, while large listing-to-final discrepancies triggered deeper comparison behavior. This is comforting because the controlled setup still produces commercially relevant interaction data.
|
||||
The dynamic pricing mechanism elicited immediate behavioral adjustments. Participants were sensitive to price volatility: sudden boosts triggered urgency and faster booking attempts, while large listing-to-final discrepancies triggered deeper comparison behavior. The responses match what one expects from live e-commerce experiences, such as reactions to volatility, which supports external validity despite the lab setting.
|
||||
|
||||
|
||||
\subsubsection{Design of Training Factorial Study}
|
||||
\subsubsection{Design of Training Sweeps}
|
||||
|
||||
The simulator has multiple configurable factors. We design a multi-factor study across five axes derived from the sweep configurations: (1) RL algorithm (\texttt{ppo}, \texttt{a2c}, \texttt{dqn}, \texttt{qtable}; 4 levels), (2) contamination ratio $\alpha$ sampled from $[0.1, 0.6]$ at four representative levels, (3) robustness radius $\epsilon_\alpha \in \{0.0, 0.15, 0.3\}$ (3 levels), (4) COI penalty weight $\lambda_\text{coi}$ at two reference levels, and (5) pricing action granularity (two discretization settings for \texttt{action\_levels}); giving a grid of $4\times4\times3\times2\times2 = 192$ configurations. Statistical power for the behavioral comparisons is determined by a two-sample test over per-session KL divergence scores; a formal power analysis with minimum detectable effect size at $n=18+18$ is reported in the results.
|
||||
% Power analysis plan: apply a two-sample Mann-Whitney U (or permutation test) on per-session (delta_H - delta_A) divergence scores comparing the human and agent groups. Compute minimum detectable effect size at alpha=0.05, power=0.8, given n=18 per group. Bootstrap confidence intervals on mean KL are a cleaner complement given the non-normality of divergence distributions.
|
||||
The simulator has multiple configurable factors. Training runs are driven by Weights \& Biases sweep definitions versioned with the codebase, mixing random and grid schedules rather than a single full factorial. For the contamination ratio $\alpha$, exploratory sweeps draw $\alpha$ uniformly on $[0.1,0.6]$ and then some sweeps use the narrower interval $[0.1,0.5]$. Grid sweeps fix explicit level sets, for example $\alpha\in\{0.1,0.2,0.3,0.4,0.6,0.8\}$ (six levels, including $0.8$ beyond the typical exploratory upper endpoint) or five levels $\{0.1,0.2,0.3,0.4,0.6\}$. Auxiliary schedules also include $\alpha=0$ alongside positive values. Robustness radius $\epsilon_\alpha$, COI penalty $\lambda_\text{coi}$, RL algorithm (\texttt{ppo}, \texttt{a2c}, \texttt{dqn}, \texttt{qtable}), and the discretization of the price action grid vary by sweep. Broad random search may use uniform $\epsilon_\alpha\in[0,0.3]$ and $\lambda_\text{coi}\in[0.05,0.6]$; tighter grids may fix $\epsilon_\alpha=0.2$ and restrict $\lambda_\text{coi}$ to $\{0.15,0.30\}$. Behavioral distinguishability is assessed with a two-sample Mann--Whitney test on per-session divergence gap scores at cohort sizes $n_H=13$ and $n_A=16$.
|
||||
While this scale is generally expensive for reinforcement learning, we execute it on a large TPU cluster to make the sweep tractable.
|
||||
|
||||
Our training budget is provisioned through TPU Research Cloud and spans 384 chips across TPU v4, v5e, and v6e generations, with a spot-heavy allocation plus an on-demand reserve. At peak BF16 throughput this corresponds to approximately 160\,PFLOPS of aggregate compute (derivation in Appendix~\ref{app:compute_budget}), which makes repeated seeds, ablations, and sensitivity sweeps feasible within practical wall-clock limits. We allocate v6e capacity to the highest-intensity policy training jobs, use v5e for wider hyperparameter exploration where throughput-per-dollar is favorable, and reserve on-demand v4 capacity for runs that should not be interrupted.
|
||||
Our training budget is provisioned through TPU Research Cloud and spans 384 chips across TPU v4, v5e, and v6e generations, with a spot-heavy allocation plus an on-demand reserve. At peak BF16 throughput this corresponds to approximately 160\,PFLOPS of aggregate compute (derivation in Appendix~\ref{app:compute_budget}), which makes repeated seeds, ablations, and sensitivity sweeps feasible within practical wall-clock limits. We allocate v6e capacity to the highest-intensity policy training jobs, use v5e for wider hyperparameter exploration, and reserve on-demand v4 capacity for runs that should not be interrupted.
|
||||
|
||||
\begin{table}[ht]
|
||||
\centering
|
||||
@@ -245,11 +274,13 @@ v4 & 64 (32 + 32) & us-central2-b & 32 Spot + 32 On-demand \\
|
||||
\end{tabular}
|
||||
\end{table}
|
||||
|
||||
For connections from Madrid, we prioritize the europe-west4 allocation for latency-sensitive runs with the benefit of having the most grouped chips within a single region. This regional grouping is important for the deployment of our Kubernetes cluster which cannot span multiple regions. All sweep metadata, model checkpoints, and reward traces are logged in Weights \& Biases. Hardware specifications are from the official Google Cloud TPU documentation \parencite{noauthor_tpu_2026,noauthor_tpu_2025-1,noauthor_tpu_2025}.
|
||||
For connections from Madrid, we prioritize the europe-west4 allocation for the sake of latency and the benefit of having the most grouped chips within a single region. This regional grouping is important for the deployment of our Kubernetes cluster which cannot span multiple regions. All sweep metadata, model checkpoints, and reward traces are logged in Weights \& Biases. \parencite{noauthor_tpu_2026,noauthor_tpu_2025-1,noauthor_tpu_2025}.
|
||||
% TODO: cite this (from bib)
|
||||
|
||||
Design of training processes: we build docker image with the fact in mind of different caching over layers in order to most speed up docker re-building and such we place the most volatile steps towards the end of the image building. What is means in practice is that any dependency installations are isolated so edits to source code do no trigger rebuilds. Only if we update our entry point of training a sweep, Docker will also rebuild the source-code copy stage.
|
||||
|
||||
Due to the preemptive nature of the current demand of TPU chips we sttle for running our on demeaned as the primary source of compute. The on demand TPU pod of 32 chips spread across 4 virtual hosts creates a relatively unique parallelization setup. Despite our desire to use a traditional approach of clustering and perhaps deploying SLURM jobs of our sweep agent, the lack of predictability in provisioning each instance of a compute resource makes this an high friction layer we do not want to add.
|
||||
Training images abide by Docker layer caching principles with maximal caching on the lowest levels. Dependency layers are separate from the copy of application source so code edits or tweaks do not re-boot the entire build such that only changes to the training entrypoint or dependencies force a full rebuild.
|
||||
|
||||
TPU capacity is scarce and often preemptible, so we rely primarily on on-demand pods for workloads that must finish without interruption. A typical reservation is a 32-chip pod across four worker VMs. That layout already gives enough parallelism for our sweep driver without adding a separate cluster scheduler. We considered SLURM-style job arrays, but fluctuating provisioning times would have added operational overhead with little benefit for our workload, so orchestration stays in the container and Ray layer described below.
|
||||
|
||||
\subsubsection{Interaction Schema}
|
||||
|
||||
@@ -257,7 +288,7 @@ We extend the basic event tuple $e_{s,k}$ to capture the full observational sign
|
||||
\begin{equation}
|
||||
e_{s,k} = \left( a_{s,k}, \, i_{s,k}, \, t_{s,k}, \, \mu_{s,k}, \, \delta_{s,k} \right)
|
||||
\end{equation}
|
||||
where $\mu_{s,k} \in \mathcal{M}$ is a metadata record containing action-specific context (e.g., price observed, filter parameters, element text), and $\delta_{s,k} \in \mathbb{R}_+$ is the dwell time in milliseconds for attention-based actions.
|
||||
where $\mu_{s,k} \in \mathcal{M}$ is a metadata record containing action-specific context (e.g., price observed, filter parameters, element text), and $\delta_{s,k} \in \mathbb{R}^+$ is the dwell time in milliseconds for attention-based actions.
|
||||
|
||||
A session $s$ is itself a structured record:
|
||||
\begin{equation}
|
||||
@@ -284,8 +315,7 @@ $\mathcal{A}_{\text{filter}}$ & \texttt{search}, \texttt{filter\_date}, \texttt{
|
||||
\end{table}
|
||||
|
||||
This partition enables the weight function $\omega$ from Eq.~\ref{eq:qhat} to assign category-specific signal strengths, with $\omega(\mathcal{A}_{\text{cart}}) > \omega(\mathcal{A}_{\text{dwell}}) > \omega(\mathcal{A}_{\text{nav}}) > \omega(\mathcal{A}_{\text{filter}})$ reflecting decreasing commitment.
|
||||
Its important to acknowledge that this creates a very blatant assumption in the weighting, we do motivate the scale of each weight by the per-category observed divergence between each behavioral profile.
|
||||
In the simulator baseline this order is encoded with a compact fixed scale: cart $=4.0$, dwell $=2.0$, nav $=1.0$, filter $=0.5$. Unknown actions are mapped by prefix heuristics to the nearest category.
|
||||
The ordering cart $>$ dwell $>$ nav $>$ filter is a deliberate simplification: we set it from early data by ranking categories by KL divergence between human and agent transition rows and then spacing weights in powers of two. The simulator encodes cart $=4.0$, dwell $=2.0$, nav $=1.0$, filter $=0.5$ and finally unknown actions map by prefix to the nearest category (or are discarded).
|
||||
|
||||
The metadata record $\mu$ varies by action type. For product views, $\mu$ contains the observed price $p_{\text{obs}}$ and product attributes. For dwell events, $\mu$ includes the element text and accumulated hover duration. This heterogeneous structure is captured via a schema-on-read approach in our Kafka ingestion pipeline, where events are validated against type-specific schemas before storage.
|
||||
|
||||
@@ -294,17 +324,17 @@ In addition to behavioral events, the platform logs price observations to a sepa
|
||||
|
||||
|
||||
|
||||
\subsection{Generative Contamination and Separability}
|
||||
\subsection{Generative Contamination and Distinguishability}
|
||||
|
||||
To train a robust pricing learner, we need a simulator that can generate realistic interaction data under controlled contamination. We build this from Phantom data using a two-stage approach.
|
||||
|
||||
|
||||
\subsubsection{Ground-Truth Separability}
|
||||
Because sessions are collected under controlled experimental conditions where each actor is assigned a known type at the start of the trial, labels $\theta_s \in \{H, A\}$ are available as ground truth rather than as the output of a heuristic classifier. We therefore estimate separate transition kernels directly from each labeled partition $\mathcal{D}_H$ and $\mathcal{D}_A$, treating the resulting $\hat{\mathcal{T}}_H$ and $\hat{\mathcal{T}}_A$ as the ground-truth behavioral profiles for each class. We then ask a direct methodological question: are the kernels separable enough to justify downstream pricing control that depends on that separability?
|
||||
\subsubsection{Ground-Truth Distinguishability}
|
||||
Because sessions are collected under controlled experimental conditions where each actor is assigned a known type at the start of the trial, labels $Y_s \in \{H, A\}$ are available as ground truth rather than as the output of a heuristic classifier. We therefore estimate separate transition kernels directly from each labeled partition $\mathcal{D}_H$ and $\mathcal{D}_A$, treating the resulting $\hat{\mathcal{T}}_H$ and $\hat{\mathcal{T}}_A$ as the ground-truth behavioral profiles for each class. We then ask a direct methodological question: are the kernels distinguishable enough to justify downstream pricing control that depends on that distinguishability?
|
||||
|
||||
To answer this, we compute per-session KL divergence scores against both class-level centroids. For each session $s$ in either partition, we fit a session-level event transition kernel $\hat{\mathcal{T}}_s$ from that session's trajectory alone, then compute its average KL divergence to the human centroid ($\Delta_{H,s}$) and to the agent centroid ($\Delta_{A,s}$). The per-session separability score is the gap $\Delta_{H,s} - \Delta_{A,s}$: a negative value indicates proximity to human behavior, a positive value indicates proximity to agent behavior.
|
||||
For each session $s$ we fit a session-level transition kernel $\hat{\mathcal{T}}_s$, then average KL divergence to the human centroid ($\Delta_{H,s}$) and to the agent centroid ($\Delta_{A,s}$). The distinguishability score is the gap $\Delta_{H,s} - \Delta_{A,s}$ (negative $\approx$ human-like, positive $\approx$ agent-like). KL is used because it compares full categorical rows, not single features.
|
||||
|
||||
The normality assumption cannot be made for KL divergence distributions, which are right-skewed and bounded below by zero, so we do not use a Student's $t$-test. Instead we apply a Mann-Whitney $U$ test \parencite{mann_test_1947} on the per-session gap scores between the two groups. The Mann-Whitney test is a rank-based nonparametric test that compares the stochastic ordering of two independent samples without distributional assumptions, making it appropriate for small samples drawn from skewed populations. We report $U$, the exact two-sided $p$-value, and group-level descriptive statistics for the gap scores.
|
||||
Gap scores are skewed and nonnegative, so we test cohort differences with a Mann--Whitney $U$ test \parencite{mann_test_1947} rather than a $t$-test. We report $U$, the two-sided $p$-value, and descriptive statistics for each group.
|
||||
|
||||
\begin{definition}[Kullback-Leibler Divergence for Transition Distributions]
|
||||
Let $P_e$ and $Q_e$ be categorical distributions over destination states following event $e$, derived from human and agent trajectories respectively. The KL divergence between these distributions is:
|
||||
@@ -313,21 +343,22 @@ Let $P_e$ and $Q_e$ be categorical distributions over destination states followi
|
||||
\end{equation}
|
||||
where $\mathcal{S}_e$ denotes the set of destination events that follow $e$ in the human trajectories.
|
||||
\end{definition}
|
||||
We exploit KL asymmetry so that ``distance from human-like'' is explicit in the score, not only distance from agents.
|
||||
|
||||
To obtain this statistic, we aggregate transitions by triggering event $e$ and treat normalized outgoing probabilities as categorical distributions $P_e$ (human) and $Q_e$ (agent). We intersect shared event labels, then accumulate log-ratio contributions over shared destinations. Large contributions, including near-zero $Q_e(k)$ cases, identify transitions where one actor class is difficult to mimic.
|
||||
|
||||
With these divergence features we train a contrastive model to estimate a weak agent probability $f(\tau)\in[0,1]$, which we later use as a weighting and control signal.
|
||||
With these divergence features we compute a weak agent probability $f(\tau')\in[0,1]$ directly from divergence gaps, which we later use as a weighting and control signal.
|
||||
|
||||
|
||||
\subsubsection{Transition Probability Estimation}
|
||||
\label{sec:tpe}
|
||||
|
||||
|
||||
For both subsets, we model session dynamics as an MDP and estimate transition kernel $\mathcal{T}$. For each actor type we estimate global kernels $\hat{\mathcal{T}}_A$ and $\hat{\mathcal{T}}_H$, then cluster into behavioral sub-kernels $\hat{\mathcal{T}}_y^i$ to avoid collapsing all behavior into one average profile. Transition probabilities are estimated by maximum likelihood:
|
||||
For both subsets, we model session dynamics as a Markov decision process and estimate transition kernel $\mathcal{T}$. For each actor type we estimate global kernels $\hat{\mathcal{T}}_A$ and $\hat{\mathcal{T}}_H$, then cluster into behavioral sub-kernels $\hat{\mathcal{T}}_y^i$ to avoid collapsing all behavior into one average profile. Transition probabilities are estimated by maximum likelihood:
|
||||
\begin{equation}
|
||||
\hat{P}(s' \mid s) = \frac{N(s, s')}{\sum_{k \in \mathcal{S}} N(s, k)}
|
||||
\end{equation}
|
||||
where $N(s, s')$ is the observed transition count. This allows us to construct a \textit{Contamination Generator} $\mathcal{G}(\alpha)$. Given a clean trajectory dataset, $\mathcal{G}$ injects synthetic agent trajectories sampled from $\hat{\mathcal{T}}_A$ until the effective mixing ratio reaches $\alpha$. The properties of an MDP such as ... should be preserved by the operation described below.
|
||||
where $N(s, s')$ is the observed transition count. This allows us to construct a \textit{Contamination Generator} $\mathcal{G}(\alpha)$. Given a clean trajectory dataset, $\mathcal{G}$ injects synthetic agent trajectories sampled from $\hat{\mathcal{T}}_A$ until the effective mixing ratio reaches $\alpha$. The properties of an MDP such as a discrete state space, nonnegative transition mass, and row-stochasticity ($\sum_{s'}\hat{P}(s'\mid s)=1$ for visited states) should be preserved by the operation described below.
|
||||
|
||||
To scale this to catalog-level pricing, we expand the base event transition matrix from $T\times T$ into product-specific transitions using the current demand condition. In practice, we normalize the demand vector across products and use it to weight how much transition mass each product pair receives. Concretely, each cell of the base matrix becomes an $N\times N$ block (for $N$ products), so the transition matrix grows from $T\times T$ to $(T\cdot N)\times(T\cdot N)$. Finally, we add $C$ generic states (homepage, login, checkout terminal states), which gives the full kernel size $(T\cdot N + C)\times(T\cdot N + C)$.
|
||||
% The validity of this demand-weighted block expansion is still subject to formal proof: it needs to be shown that the resulting matrix retains row-stochasticity (rows summing to 1) and that the weighting by the demand vector preserves the Markov property for the expanded state space. In the engine source this is the target of ongoing validation before the expansion is relied on for behavioral generation at scale.
|
||||
@@ -349,7 +380,8 @@ To scale this to catalog-level pricing, we expand the base event transition matr
|
||||
|
||||
\subsection{Distributionally Robust Reinforcement Learning (DR-RL)}
|
||||
|
||||
We formulate pricing as a Stackelberg game: the platform (leader) sets prices $p_t$, and the population (follower) responds through trajectories and demand. A useful intuition is that the platform behaves like a distorted mirror at a 45-degree angle: what it mirrors is population demand into an estimated demand proxy, and that proxy drives revenue.
|
||||
We formulate pricing as a Stackelberg game in which the platform (leader) sets prices $p_t$, and the population (follower) responds through trajectories and demand. A useful intuition is that the platform behaves like a distorted mirror at a 45-degree angle: what it mirrors is population demand into an estimated demand proxy, and that proxy drives revenue.
|
||||
% TODO: add canonical Stackelberg citation.
|
||||
|
||||
Because contamination level $\alpha$ and demand shift are non-stationary online, a simple error term is not enough. We therefore use a Distributionally Robust Optimization objective. Let $\tau'$ be a newly observed trajectory generated by an unknown actor profile (sampled from the behavioral models in Section~\ref{sec:tpe}). We need a demand mapping conditioned on price and trajectory, $\hat{Q}(p,\tau')$. For each $\tau'$, we compute $\hat{\mathcal{T}}'$ and compare it with controlled baselines $\bar{\mathcal{T}}_H$ and $\bar{\mathcal{T}}_A$:
|
||||
|
||||
@@ -360,9 +392,38 @@ Because contamination level $\alpha$ and demand shift are non-stationary online,
|
||||
\Delta_A &= D_{KL}(\hat{\mathcal{T}}^\prime \parallel \bar{\mathcal{T}}_A)
|
||||
\end{align}
|
||||
|
||||
This yields two centroid-like heuristics that act as a session-level agent score in the engine. On a per-customer or use-case basis a similar study should be done in order to obtain ground truth behavior models for humans and agents and their specific interaction with a given products website.
|
||||
From these two divergences we define the gap score following previously highlighted intuition of the divergence:
|
||||
\begin{equation}
|
||||
g(\tau') = \Delta_H(\tau') - \Delta_A(\tau').
|
||||
\end{equation}
|
||||
Positive values indicate trajectories farther from the human centroid and closer to the agent centroid.
|
||||
|
||||
In implementation, we maintain an alternating game-history stack (our \textit{Limbo} stack) and execute it explicitly every epoch with exactly two transitions: first the platform publishes a price vector (leader move), then the market responds with trajectory-derived demand (follower move).
|
||||
We map this gap to a weak agent probability using a temperature-controlled logistic map:
|
||||
\begin{equation}
|
||||
f(\tau') = P(Y=A\mid\tau') = \operatorname{softmax}(-\Delta_A,-\Delta_H)_A = \sigma\left(\frac{\Delta_H-\Delta_A}{T}\right), \quad T>0.
|
||||
\end{equation}
|
||||
The session-level control signal injected into pricing is then
|
||||
\begin{equation}
|
||||
\hat{\alpha}(\tau') = f(\tau').
|
||||
\end{equation}
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\input{chapters/figures/sigmoid_softmax_gap.tex}
|
||||
\caption{Logistic mapping from the gap $\Delta_H-\Delta_A$ to the weak agent probability $f(\tau')$. Markers indicate the contrasts $\Delta_H<\Delta_A$ and $\Delta_H>\Delta_A$.}
|
||||
\label{fig:sigmoid_softmax_gap}
|
||||
\end{figure}
|
||||
|
||||
This turns distinguishability into an operational control input in the engine. On a per-customer or use-case basis, a similar data collection and fitting process should be repeated to obtain domain-specific behavior kernels.
|
||||
|
||||
In implementation we keep an alternating game-history buffer and advance it each epoch with two transitions where the platform publishes a price vector (leader move), then the environment returns trajectory-derived demand (follower move). We call this the \textit{Limbo}.
|
||||
|
||||
To avoid notation drift, we separate two COI objects used for different purposes:
|
||||
\begin{align}
|
||||
\text{COI}_{\text{level}}(\pi) &= \mathbb{E}[P]-\underline{p}\\
|
||||
\text{COI}_{\text{leak}}(p,\tau') &= f(\tau')\cdot \text{InfoValue}(p,\tau')
|
||||
\end{align}
|
||||
where $\text{COI}_{\text{level}}$ is evaluated at policy level and $\text{COI}_{\text{leak}}$ is evaluated per observed quote during training. Subsequently, when discussing the reward structure, we will better understand the term of the information value.
|
||||
|
||||
% Mention discretized action space and the clipping and over shotting in continuous action spaces
|
||||
% Also talk about catastrophic economics, we add termination on bankrupcy or zero demand so market collaps
|
||||
@@ -383,12 +444,14 @@ and we evaluate a small fixed grid in $\mathcal{A}_{\epsilon_\alpha}(\alpha_0)$
|
||||
|
||||
|
||||
\subsubsection{Environment Setup for Dynamic Pricing}
|
||||
The complete pricing-demand-trajectory loop is illustrated in Figure~\ref{fig:oracle_flow}. The Oracle maps historical price and demand state to a new price vector, which is exposed to a distribution of demand curves. Each product generates trajectories weighted by behavioral kernels $\tau_\theta$, producing a full transition matrix $\tau'$ over sessions. Sampled trajectories $\{\tau_k\}$ are aggregated through the demand proxy function $Q(\cdot)$ to yield the next demand vector, which feeds back into the Oracle.
|
||||
The complete pricing-demand-trajectory loop is illustrated in Figure~\ref{fig:oracle_flow}. The Oracle maps historical price and demand state to a new price vector, which is exposed to a distribution of demand curves. Each product generates trajectories weighted by behavioral kernels $\tau_Y$, producing a full transition matrix $\tau'$ over sessions. Sampled trajectories $\{\tau_k\}$ are aggregated through the demand proxy function $Q(\cdot)$ to yield the next demand vector, which feeds back into the Oracle.
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\[
|
||||
\text{Oracle}(\vec{p}_{t-1},\vec{\hat{q}})\to
|
||||
{\setlength{\arraycolsep}{4pt}%
|
||||
\resizebox{0.85\linewidth}{!}{$
|
||||
\begin{aligned}
|
||||
&\text{Oracle}(\vec{p}_{t-1},\vec{\hat{q}})\to
|
||||
\begin{pmatrix}
|
||||
p_0\\
|
||||
p_1\\
|
||||
@@ -397,14 +460,15 @@ p_N
|
||||
\end{pmatrix}
|
||||
\underrightarrow{d_i \sim \mathcal{N}_{\vec{p}}}
|
||||
\begin{pmatrix}d_0\\ d_1\\ \cdots \\ d_N\end{pmatrix}
|
||||
\underrightarrow{\vec{d}\times \tau_\theta \to \tau^\prime}
|
||||
\underrightarrow{\vec{d}\otimes \tau_Y}
|
||||
\begin{bmatrix}
|
||||
0.01 & 0.02 & \cdots & 0.3 \\
|
||||
0.41 & 0.24 & \cdots & 0.0 \\
|
||||
\cdots & \cdots & \cdots & \cdots \\
|
||||
0.51 & 0.09 & \cdots & 0.1 \\
|
||||
\end{bmatrix}
|
||||
\underrightarrow{\tau_k \sim \tau^\prime}
|
||||
\\
|
||||
&\underrightarrow{\tau_k \sim \tau^\prime}
|
||||
\{\tau_k\}_{k=0}^K \to \hat{Q}(\tau_k)
|
||||
\to \begin{pmatrix}
|
||||
\hat{q}_0 \\
|
||||
@@ -413,8 +477,10 @@ p_N
|
||||
\hat{q}_N \\
|
||||
\end{pmatrix}
|
||||
\to \text{Oracle}(\cdot)
|
||||
\]
|
||||
\caption{Oracle-based pricing loop: historical price and demand state map to a new price vector; each product samples demand curves from $\mathcal{N}_{\vec{p}}$; trajectories are generated by mixing demand with behavioral kernels $\tau_\theta$ into transition matrix $\tau'$; sampled trajectories $\{\tau_k\}$ aggregate through proxy $Q(\cdot)$ to yield updated demand $\vec{\hat{q}}$, closing the feedback loop.}
|
||||
\end{aligned}
|
||||
$}%
|
||||
}
|
||||
\caption{Oracle-based pricing loop: historical price and demand state map to a new price vector; each product samples demand curves from $\mathcal{N}_{\vec{p}}$; trajectories are generated via the Kronecker product $\vec{d}\otimes\tau_Y$ into transition matrix $\tau'$; sampled trajectories $\{\tau_k\}$ aggregate through proxy $Q(\cdot)$ to yield updated demand $\vec{\hat{q}}$, closing the feedback loop.}
|
||||
\label{fig:oracle_flow}
|
||||
\end{figure}
|
||||
|
||||
@@ -422,46 +488,52 @@ p_N
|
||||
The robust policy $\pi^*$ is obtained by solving the maximin problem:
|
||||
\begin{equation}
|
||||
\label{eq:robust_policy}
|
||||
\pi^* = \arg \max_{\pi} \min_{Q \in \mathcal{U}_\epsilon} \mathbb{E}_{d \sim Q} \left[ R(p, d) - \lambda \cdot \text{COI}_{\text{leak}}(p,\tau') \right]
|
||||
\pi^* = \arg \max_{\pi} \min_{Q \in \mathcal{U}_\epsilon} \mathbb{E}_{d \sim Q} \left[ R(p, d) - \lambda \cdot \text{COI}_{\text{leak}}(p,\tau') - \eta_{\text{ux}} \cdot \text{UX}(\tau', p) \right]
|
||||
\end{equation}
|
||||
where $R(p, d)$ is the revenue function and $\lambda$ weighs the information-leakage penalty.
|
||||
where $R(p, d)$ is the revenue function, $\lambda$ weighs the information-leakage penalty, $\eta_{\text{ux}}$ weighs the user-experience penalty, and $\text{UX}(\tau', p)\in[0,1]$. We note that $p$ is directly dependent on $\pi$, which is the one deciding this as its action.
|
||||
Looking at the reward structure, note that we are not subtracting COI but rather the leakage of COI, which is as defined below.
|
||||
|
||||
|
||||
In practice, we parameterize this with a session-level leakage term:
|
||||
\begin{equation}
|
||||
\text{COI}_{\text{leak}}(p,\tau') = f(\tau')\cdot \text{InfoValue}(p,\tau')
|
||||
\end{equation}
|
||||
where $f(\tau')$ is the weak agent probability and $\text{InfoValue}$ is implemented either as a constant query-tax surrogate or as a revelation surrogate $-\log\pi(p\mid\tau')$.
|
||||
where $f(\tau')$ is the weak agent probability and $\text{InfoValue}$ is implemented either as a constant query-tax surrogate or as a revelation surrogate $-\log\pi(p\mid\tau')$. This is the surprise of a certain price-setting probability. Essentially, we proxy the leakage term as a surprise of the price our policy is setting, weighted by the contamination estimate. Appendix~\ref{app:revelation_log} expands on why the logarithm is used in the revelation surrogate.
|
||||
|
||||
The inner minimization selects the contamination candidate that makes the penalized reward smallest, so the outer policy update faces the worst plausible leakage scenario inside the ambiguity set rather than an average case.
|
||||
|
||||
For the baseline engine reported here, we intentionally use the constant query-tax surrogate to keep the mechanism minimal:
|
||||
\begin{equation}
|
||||
r_t = R(p_t,\tilde q_t) - \lambda\,f(\tau_t')\,c_{\text{info}}
|
||||
\label{eq:baseline_step_reward}
|
||||
r_t = R\!\left(p_t,\hat{Q}_t\right) - \lambda\,f(\tau_t')\,c_{\text{info}} - \eta_{\text{ux}}\,\text{UX}(\tau_t', p_t)
|
||||
\end{equation}
|
||||
with fixed $c_{\text{info}}>0$.
|
||||
with fixed $c_{\text{info}}>0$, matching the leakage term $\text{COI}_{\text{leak}}=f(\tau_t')\,c_{\text{info}}$ and the user-experience penalty already introduced in~\eqref{eq:robust_policy}.
|
||||
|
||||
|
||||
Another possible extension is to adapt the ambiguity radius online, e.g., $\epsilon(\Delta_H)$, so the Wasserstein ball changes with live divergence. We keep this as future work and retain a fixed-radius setup because Wasserstein ambiguity already handles heavy-tail and ``black swan'' behavior without absolute continuity assumptions \parencite{kuhn_wasserstein_2024}.
|
||||
|
||||
\subsubsection{Actor Implementation}
|
||||
In our simulation, the ``follower'' is implemented as a set of Actors. Each Actor is initialized with a type $\theta$ which samples a specific demand curve $d(p; \theta)$ from the latent distribution. This formalization ensures that our DR-RL agent does not overfit to a single deterministic demand function but learns a policy robust to the distributional uncertainty defined by $\mathcal{U}_\epsilon$.
|
||||
In our simulation, the ``follower'' is implemented as a set of Actors. Each Actor is initialized with a class $Y$ and a latent type $\theta \sim \mathcal{D}_Y$, which samples a specific demand curve $d\!\left(p\mid Y,\theta\right)$ from the latent distribution. This formalization ensures that our DR-RL agent does not overfit to a single deterministic demand function but learns a policy robust to the distributional uncertainty defined by $\mathcal{U}_\epsilon$.
|
||||
|
||||
Practical implementation of browser agents is a strongly evolving field with near-weekly releases of SOTA architectures. In this thesis implementation we abstract that layer into trajectory generators learned from observed human/agent transition kernels.
|
||||
|
||||
|
||||
As part of reward engineering, we keep a UX factor ($UX\in[0,1]$) as an auxiliary evaluation axis. In the current baseline it is not injected into the core reward; it is tracked separately to compare policy trade-offs.
|
||||
As part of reward engineering, we keep a UX factor ($UX\in[0,1]$) as an auxiliary evaluation axis. In code, the UX index is implemented as a volatility penalty on relative price changes, with an extra upward-volatility component weighted by $0.5$ and scaled by $\eta_{\text{ux}}$ and an information-budget term. We also keep a separate supra-competitive penalty tied to persistent price excess above a competitive anchor, which punishes high-price behavior even when volatility is low.
|
||||
We measure volatility as mean absolute relative price movement, $v_t=\frac{1}{N}\sum_{i=1}^N\bigl|(p_{t,i}-p_{t-1,i})/\max(p_{t-1,i},1)\bigr|$.
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\resizebox{0.5\columnwidth}{!}{%
|
||||
\input{chapters/balance_figure.tex}
|
||||
}
|
||||
\caption{Introducing the UX index allows us to better distinguish the kind of impact different methods have and allows us to compare them on this Pareto-like scale.}
|
||||
\caption{Introducing the UX index allows us to better distinguish the kind of impact different methods have and allows us to compare them on this Pareto-efficiency-like scale.}
|
||||
\end{figure}
|
||||
|
||||
We also consider taxation-like overlays for agent traffic under strategy-proof mechanism design (e.g., Vickrey-Clarke-Groves style rules). This remains an extension path and is not part of the main implementation in this thesis.
|
||||
|
||||
\subsubsection{Pricing Mechanism Summary}
|
||||
|
||||
We now present the complete pricing mechanism that integrates the behavioral separability, contamination estimation, and robust optimization components developed in the preceding sections. Algorithm~\ref{alg:phantom_loop_clean} formalizes the defensive pricing loop as a Stackelberg game where the platform (leader) sets prices and the aggregate demand (follower) responds through observed session trajectories.
|
||||
We now present the complete pricing mechanism that integrates the behavioral distinguishability, contamination estimation, and robust optimization components developed in the preceding sections. Algorithm~\ref{alg:phantom_loop_clean} formalizes the defensive pricing loop as a Stackelberg game where the platform (leader) sets prices and the aggregate demand (follower) responds through observed session trajectories.
|
||||
|
||||
\begin{algorithm}[t]
|
||||
\caption{PHANTOM defensive pricing loop}
|
||||
@@ -491,6 +563,50 @@ We now present the complete pricing mechanism that integrates the behavioral sep
|
||||
\end{algorithm}
|
||||
|
||||
|
||||
The algorithm operates in discrete epochs indexed by $t$. At each epoch, the platform applies one discrete multiplicative price action, the environment samples a batch of sessions, and demand is recomputed from weighted events. Robustness is implemented as an inner minimization over a small local grid of contamination candidates around nominal $\alpha_0$, matching the current engine implementation. The history buffer $\mathcal{L}$ (``Limbo'' in our implementation) enforces the alternating Stackelberg structure by preserving the temporal sequence of price publications and demand observations.
|
||||
The algorithm operates in discrete epochs indexed by $t$. At each epoch, the platform applies one discrete multiplicative price action, the environment samples a batch of sessions, and demand is recomputed from weighted events. Robustness is implemented as an inner minimization over a small local grid of contamination candidates around nominal $\alpha_0$, matching the current engine implementation. The history buffer $\mathcal{L}$ enforces the alternating Stackelberg structure by preserving the temporal sequence of price publications and demand observations.
|
||||
|
||||
%The defensive price update in Line 24 implements contamination-aware margin shrinkage: as estimated contamination $\hat{\alpha}_t$ rises, the margin $(p^{\mathrm{ref}} - c)$ is reduced by factor $\kappa\in[0,1]$, with projection $\Pi_{\mathcal{P}}$ ensuring feasibility. In subsequent experiments this heuristic rule is replaced by DR-RL policy $\pi^*$ from Eq.~\ref{eq:robust_policy}.
|
||||
|
||||
\subsection{Parallelization Strategy}
|
||||
|
||||
To reduce mid-job preemption we standardize on a TPU v4 allocation with 40 chips and five workers. A head process launches Ray \parencite{moritz_ray_2018} and attaches workers across the remaining hosts.
|
||||
|
||||
\subsubsection{Computational Cost Analysis of the Simulation Step}
|
||||
The per-step cost of Algorithm~\ref{alg:phantom_loop_clean} is not uniform across its components. To inform hardware provisioning and to identify where algorithmic improvements are most impactful, we profile the hot path of the engine using Python's \texttt{cProfile} instrumentation over 20 environment steps under two configurations: a baseline with the robustness inner loop disabled ($K=1$, $\epsilon_\alpha=0$) and a standard robust setting ($K=5$, $\epsilon_\alpha=0.2$). Both runs use $M=10$ sessions per market call and $N=3$ products.
|
||||
|
||||
The baseline achieves approximately 26 steps per second. Enabling the robustness inner loop with $K=5$ candidates drops throughput to 7.2 steps per second, a $3.6\times$ slowdown that is directly proportional to $K$, consistent with the $O(K)$ scaling of the adversarial alpha selection in the implementation.
|
||||
|
||||
\begin{table}[ht]
|
||||
\centering
|
||||
\caption{Per-step profiling results (20 steps, $M=10$ sessions, $N=3$ products). Self-time measures time spent inside the function excluding callees and cumulative time includes the full call subtree.}
|
||||
\label{tab:profile_results}
|
||||
\begingroup
|
||||
\small
|
||||
\setlength{\tabcolsep}{4pt}
|
||||
\begin{tabular}{@{}lrrrr@{}}
|
||||
\toprule
|
||||
\textbf{Function} & \textbf{Calls} & \textbf{Self (ms)} & \textbf{Cum. (ms)} & \textbf{Cum. \%} \\
|
||||
\midrule
|
||||
\multicolumn{5}{l}{\textit{Baseline ($K=1$, 0.77\,s total, 26 steps/s)}} \\
|
||||
\texttt{sample\_behavior\_from\_transitions} & 420 & 131 & 658 & 86\% \\
|
||||
\texttt{DataFrame.xs} & 4,820 & 30 & 201 & 26\% \\
|
||||
\texttt{numpy.nan\_to\_num} & 4,904 & 43 & 97 & 13\% \\
|
||||
\texttt{adjust\_behavior\_to\_condition} & 84 & 3 & 54 & 7\% \\
|
||||
\midrule
|
||||
\multicolumn{5}{l}{\textit{Robust ($K=5$, 2.79\,s total, 7.2 steps/s)}} \\
|
||||
\texttt{sample\_behavior\_from\_transitions} & 1,220 & 519 & 2,447 & 88\% \\
|
||||
\texttt{DataFrame.xs} & 16,668 & 108 & 729 & 26\% \\
|
||||
\texttt{numpy.nan\_to\_num} & 16,912 & 164 & 363 & 13\% \\
|
||||
\texttt{adjust\_behavior\_to\_condition} & 244 & 11 & 108 & 4\% \\
|
||||
\bottomrule
|
||||
\end{tabular}
|
||||
\endgroup
|
||||
\end{table}
|
||||
|
||||
Across both configurations, \texttt{sample\_behavior\_from\_transitions} accounts for 86--88\% of total wall time. The function implements the Markov chain sampler described in Section~\ref{sec:tpe}: at each transition it retrieves the current-state row from the expanded transition \texttt{DataFrame} via label-based indexing, which internally dispatches through the pandas \texttt{xs} and \texttt{fast\_xs} code paths. For $M$ sessions each running up to $L_{\max}=40$ transitions, a single \texttt{market.act()} call issues up to $M \cdot L_{\max}$ individual row lookups. With $K=5$ robustness candidates per outer step this accumulates to $5 \times 10 \times 40 = 2{,}000$ row accesses per outer step, producing the 16k \texttt{xs} invocations observed in Table~\ref{tab:profile_results}.
|
||||
|
||||
The \texttt{numpy.nan\_to\_num} calls, accounting for 13\% of self-time, occur once per row lookup to sanitize sampled probability vectors before normalization; their call count therefore tracks the \texttt{xs} count exactly.
|
||||
|
||||
\texttt{adjust\_behavior\_to\_condition} expands the base $E \times E$ event transition matrix to a $(E \cdot N) \times (E \cdot N)$ product-specific matrix via a Kronecker product. At $N=3$ this is inexpensive, but the cost scales as $O(E^2 N^2)$, so at the $N=10$ default it becomes a more significant contributor. The result is not cached across the $K$ robustness candidates inside a single outer step, meaning the Kronecker expansion is recomputed $2K$ times per step (once for the human kernel and once for the agent kernel at each candidate $\alpha_k$).
|
||||
|
||||
The dominant bottleneck therefore has a clear structural cause: the expanded transition matrix is a string-keyed \texttt{DataFrame}, and pandas object-level indexing carries substantial per-call overhead relative to the arithmetic being performed. Converting the expanded matrix to a \texttt{numpy} array with an accompanying integer state-to-index map, computed once per \texttt{market.act()} call and cached for the duration of the robustness inner loop, eliminates the entire pandas dispatch chain. We leverage this bottleneck identified as an opportunity to squeeze the gap which is left by the computational needs of the pricing learner. We make use of JAX to parallelize on the TPU, and surprisingly we open up a large speedup even on CPU-only compute, improving throughput from 26 to 220 steps/s in the baseline configuration and from 7.2 to 136 steps/s under the full robust inner loop, an 8.5$\times$ and 19$\times$ speedup respectively.
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
\section{Results}
|
||||
\label{sec:results}
|
||||
|
||||
% The gap we target is not detection for its own sake but whether behavioral signals can support pricing decisions once agent traffic is present. This section follows the supporting questions in \cref{sec:research_questions}: we first establish session-level distinguishability (behavioral evidence and a rank test), then estimate how contamination shifts revenue in a controlled sweep, and finally compare robust and baseline policies under factorial training with COI and revenue readouts. The ordering is deliberate---each stage feeds the next so that separability, contamination effects, and policy outcomes form one connected line of evidence.
|
||||
|
||||
In our work, the gap we target is not the detection for its own sake. Our aim is to understand behavioral signals which can support pricing decisions once agent traffic is present. Now we set to conclude and piece together the path we laid out in \cref{sec:research_questions}. We established distinguishability (behavioral evidence and test) that estimate how contamination shifts revenue in an adversarial environment and finally we compare robust and baseline pricing under factorial training.
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\input{chapters/figures/supra.tex}
|
||||
\caption{Evolution of price distributions over experiment steps. The heatmap illustrates the density of price offerings. This is an early baseline simulation which demonstrates supra-competitive price-setting in deep learning agents such as SAC as can be clearly seen by the high density at the highest available price.}
|
||||
\input{chapters/figures/supra/supra.tex}
|
||||
\caption{Evolution of price distributions over experiment steps. The heatmap illustrates the density of price offerings. This is an early baseline simulation which demonstrates supra-competitive price-setting in deep learning agents such as Soft Actor Critic as can be clearly seen by the high density at the highest available price.}
|
||||
\label{fig:supra_heatmap}
|
||||
\end{figure}
|
||||
|
||||
@@ -10,7 +16,7 @@
|
||||
|
||||
\subsection{Behavioral Analysis}
|
||||
|
||||
Separability between human and agent sessions is evaluated by computing per-session divergence gap scores $\Delta_{H,s} - \Delta_{A,s}$ and comparing the two groups with a Mann-Whitney $U$ test. Table~\ref{tab:divergence_significance} reports the group-level descriptive statistics for the gap scores and the test result.
|
||||
Distinguishability between human and agent sessions is evaluated by computing per-session divergence gap scores $\Delta_{H,s} - \Delta_{A,s}$ and comparing the two groups with a Mann-Whitney $U$ test. The full recorded cohort contains $n_H=13$ human sessions and $n_A=16$ agent sessions, and Table~\ref{tab:divergence_significance} reports the corresponding group-level statistics and test result.
|
||||
|
||||
\begin{table}[ht]
|
||||
\centering
|
||||
@@ -20,48 +26,87 @@ Separability between human and agent sessions is evaluated by computing per-sess
|
||||
\toprule
|
||||
Group & $n$ & Mean gap & Std \\
|
||||
\midrule
|
||||
Human sessions & 11 & $-3.3522$ & $2.6748$ \\
|
||||
Agent sessions & 6 & $+1.6482$ & $2.8349$ \\
|
||||
Human sessions & 13 & $-3.35$ & $2.67$ \\
|
||||
Agent sessions & 16 & $+1.65$ & $2.83$ \\
|
||||
\midrule
|
||||
\multicolumn{4}{l}{Mann-Whitney $U = 2.0$, $p = 0.0006$ (two-sided)} \\
|
||||
\multicolumn{4}{l}{Mann-Whitney two-sided test: $p<0.001$} \\
|
||||
\bottomrule
|
||||
\end{tabular}
|
||||
\end{table}
|
||||
|
||||
The sign structure is consistent with the theoretical expectation: human sessions produce negative gap scores (closer to the human centroid, far from the agent centroid) while agent sessions produce positive gap scores (closer to the agent centroid). The two-sided $p$-value of $0.0006$ indicates near-complete rank separation between the groups at $n_H=11$, $n_A=6$, providing strong evidence that the transition kernels are separable enough to justify their use as a control signal in downstream pricing.
|
||||
The sign structure is consistent with the theoretical expectation: human sessions produce negative gap scores (closer to the human centroid, far from the agent centroid) while agent sessions produce positive gap scores (closer to the agent centroid). The two-sided test result ($p<0.001$) at $n_H=13$, $n_A=16$ indicates strong rank distinction between groups, providing evidence that the transition kernels are distinguishable enough to justify their use as a control signal in downstream pricing.
|
||||
|
||||
|
||||
\subsection{Experimental Outcomes}
|
||||
|
||||
To evaluate robustness contributions, we compare two policies on the same environment family: (i) robust pricing with COI-aware reward and adversarial contamination step, and (ii) non-robust baseline with revenue-only reward (\texttt{--no-robust}).
|
||||
To evaluate robustness contributions, we compare two policies on the same environment family: (i) robust pricing with COI-aware reward and adversarial contamination step, and (ii) a baseline policy with revenue-only reward.
|
||||
|
||||
We report two preliminary stages before the full factorial interpretation. First, we executed a short calibration run at $\alpha=0.3$ (2 evaluation episodes, 3000 training timesteps per tier) across \texttt{qtable}, \texttt{ppo}, \texttt{a2c}, and \texttt{dqn}. In that first run, \texttt{ppo} produced the highest objective score and revenue (objective $=3.76\mathrm{e}5$, revenue $=4.15\mathrm{e}5$), while the remaining tiers stayed lower in this small-budget regime. The corresponding price traces show a monotone escalation for \texttt{ppo} (mean price from $8.61\mathrm{e}1$ to $1.49\mathrm{e}2$), whereas \texttt{qtable}, \texttt{a2c}, and \texttt{dqn} remained nearly flat over the episode horizon. This confirms that the simulation loop is able to express policy-dependent pricing dynamics rather than collapsing into a single trajectory shape.
|
||||
|
||||
Second, we launched an overnight paired benchmark over $\alpha \in \{0.00,0.15,0.30,0.45,0.60\}$ with 8 evaluation episodes and 8000 timesteps, comparing robust and non-robust settings at fixed seed/tier/contamination tuples. At the time of writing, two seeds (11 and 22) are complete and one additional seed is still running. We therefore frame the numbers below as an initial signal, not a final claim.
|
||||
|
||||
\subsubsection{The Impact of Contamination on Revenue}
|
||||
|
||||
The contamination--revenue slope is estimated on a controlled cohort (single sweep, baseline policy, $n_{\text{products}}=100$, $n=95$). In this setting, contamination $\alpha$ is set exogenously by the experiment, so the slope identifies the within-sweep causal effect of contamination on revenue under fixed policy and environment settings. These results are in favor of our second research question \hyperlink{sq2}{\textbf{SQ2}} (\textit{Theoretical Impact}) from \cref{sec:research_questions}.
|
||||
|
||||
\begin{table}[ht]
|
||||
\centering
|
||||
\caption{Early overnight aggregate over completed seeds ($n=2$; seeds 11 and 22).}
|
||||
\label{tab:pricing_benchmark}
|
||||
\begin{tabular}{lcccc}
|
||||
\caption{Slope verification table for contamination versus revenue.}
|
||||
\label{tab:contamination_slope_table}
|
||||
\begin{tabular}{@{}lrrrrr@{}}
|
||||
\toprule
|
||||
Mode & Mean objective score & Mean revenue & Mean COI level & Mean margin \\
|
||||
Term & Coef. & Std. Err. & $t$ & $p>|t|$ & 95\% CI \\
|
||||
\midrule
|
||||
Robust & $3.41\mathrm{e}5$ & $3.80\mathrm{e}5$ & $1.08\mathrm{e}2$ & 0.901 \\
|
||||
Non-robust (\texttt{--no-robust}) & $3.91\mathrm{e}5$ & $4.18\mathrm{e}5$ & $1.11\mathrm{e}2$ & 0.906 \\
|
||||
Intercept & 348,823.41 & 784.29 & 444.77 & $<10^{-99}$ & $[347,264.96,\,350,381.86]$ \\
|
||||
$\alpha$ & $-90,140.53$ & 1,466.90 & $-61.45$ & $4.27\times10^{-77}$ & $[-93,053.38,\,-87,227.68]$ \\
|
||||
\midrule
|
||||
HC1 robust check ($\alpha$) & $-90,140.53$ & 2,185.22 & $-41.25$ & $1.42\times10^{-61}$ & -- \\
|
||||
\bottomrule
|
||||
\end{tabular}
|
||||
\end{table}
|
||||
|
||||
At pair level (same seed, tier, and contamination), robust exceeds non-robust in $13/40$ configurations on objective score and in $16/40$ configurations on revenue. The current early evidence therefore suggests a conditional robustness effect: the defense is active and measurable, but not yet uniformly beneficial without further calibration.
|
||||
Interpreted on the contamination grid, a $+0.1$ increase in $\alpha$ corresponds to an average revenue decrease of about $9{,}014$ units, and the robust check preserves both direction and significance.
|
||||
% TODO: add a compact proposal note for re-running tests with statsmodels in the appendix methodology notes.
|
||||
|
||||
\subsubsection{Large Scale Factorial Training}
|
||||
|
||||
In our complete training runs we logged $\approx 180$ days of net compute time. The results we draw from extensive training are
|
||||
\begin{enumerate*}[label=(\roman*)]
|
||||
\item the ability to extract COI is greater in the presence of robustness within the training loop
|
||||
\item short term revenue measurements suffer $\approx 3\%$ loss but COI margin compensates for this loss in the long run
|
||||
\item a larger catalog size contributes positively to COI preservation under higher contamination ratios
|
||||
\item supra-competitive pricing is a natural reward hacking tendency which is drastically reduced by a balanced UX penalty
|
||||
\end{enumerate*}
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\input{chapters/figures/results/includes/final_focus_revenue_by_alpha.tex}
|
||||
\caption{Revenue curves by contamination for the final cohort. The baseline remains above the defended curve in most cells, but the gap narrows in the high-contamination region.}
|
||||
\label{fig:final_focus_revenue_by_alpha}
|
||||
\end{figure}
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\input{chapters/figures/results/includes/final_focus_coi_by_alpha.tex}
|
||||
\caption{COI level curves by contamination for the final cohort. The shaded band marks the per-$\alpha$ gap between defended and baseline policies.}
|
||||
\label{fig:final_focus_coi_by_alpha}
|
||||
\end{figure}
|
||||
|
||||
\begin{figure}[ht]
|
||||
\centering
|
||||
\input{chapters/figures/results/includes/final_focus_coi_preservation_grid.tex}
|
||||
\caption{COI preservation by product count at the contamination endpoints ($\alpha=0.0$ and $\alpha=1.0$). Bars report defended-minus-baseline mean COI level, with the zero line separating preservation from erosion.}
|
||||
\label{fig:final_focus_coi_preservation_grid}
|
||||
\end{figure}
|
||||
|
||||
|
||||
|
||||
\subsection{Interpretation and Insights}
|
||||
The Mann-Whitney result ($U=2.0$, $p<0.001$) confirms that per-session divergence gaps separate the two actor classes with near-zero overlap in rank ordering. This is the condition required for separability to act as a useful control signal in the pricing loop rather than just an auxiliary classifier score.
|
||||
The Mann-Whitney result ($p<0.001$) confirms that per-session divergence gaps distinguish the two actor classes with near-zero overlap in rank ordering. This is the condition required for distinguishability to act as a useful control signal in the pricing loop rather than just an auxiliary classifier score. This is a direct result relevant to our first pillar \hyperlink{sq1}{\textbf{SQ1}} (\textit{Distinguishability}) from \cref{sec:research_questions}.
|
||||
|
||||
The first calibration and overnight runs additionally confirm three practical points aligned with the thesis mechanism. First, the control loop is reproducible end-to-end (training, evaluation, artifact generation) across algorithms and contamination levels. Second, policy class materially changes price trajectories and resulting COI/revenue profiles under identical environment settings. Third, objective improvements from robustness are regime-dependent in the current baseline, which is consistent with the thesis claim that contamination-aware pricing needs explicit calibration rather than a one-size-fits-all penalty.
|
||||
The first calibration and paired benchmark runs additionally confirm three practical points aligned with the thesis. First, the control loop is reproducible end-to-end (training, evaluation, artifact generation) across algorithms and contamination levels. Second, policy class materially changes price trajectories and resulting COI/revenue profiles under identical environment settings. Third, objective improvements from robustness are regime-dependent in the current baseline, which is consistent with the thesis claim that contamination-aware pricing needs explicit calibration rather than a one-size-fits-all penalty.
|
||||
|
||||
We also note that maximizing revenue in isolation can favor aggressive high-price behavior, even in our early runs, the non-robust aggregate shows slightly higher mean COI and margin. For this reason, all subsequent reporting in this thesis is interpreted on a multi-metric basis (objective, revenue, COI, and stability), and not by revenue alone. This is another direct answer to our third pillar \hyperlink{sq3}{\textbf{SQ3}} (\textit{Robust Mitigation}) from \cref{sec:research_questions}.
|
||||
|
||||
We also note that maximizing revenue in isolation can favor aggressive high-price behavior; even in these early runs, the non-robust aggregate shows slightly higher mean COI and margin. For this reason, all subsequent reporting in this thesis is interpreted on a multi-metric basis (objective, revenue, COI, and stability), and not by revenue alone.
|
||||
|
||||
\subsection{Anomalies}
|
||||
In our initial runs, we observed an instability pocket in one completed run (A2C, robust, seed 11, $\alpha=0.30$) with a large performance drop relative to neighboring configurations. We retain this run in the preliminary summary to avoid survivorship bias and treat it as evidence that robustness sensitivity analysis is necessary before final conclusions.
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
\section{Discussion}
|
||||
\label{sec:discussion}
|
||||
|
||||
% TODO: Gpdr here
|
||||
|
||||
|
||||
\subsection{Transition to Agentic Market Microstructure}
|
||||
|
||||
Our analysis of the interaction dynamics between the platform and non-human actors suggests that the current static pricing models are insufficient for an agent-mediated economy. If we assume a transition toward a direct revelation mechanism, where actors must reveal their true valuation of a good through bidding dynamics, we inevitably introduce significant stochasticity into the pricing system. Unlike traditional e-commerce where prices are relatively sticky, such a mechanism implies a high volatility characteristic of financial equity markets (without the fungability however).
|
||||
|
||||
However, ecommerce commodities differ fundamentally from financial securities: they possess a hard floor defined by unit economics and reservation prices. The market might react enthusiastically to an iPhone priced at \$1, such a transaction is not permissible. The platform must establish an initial valuation anchor ($P_{0}$) defined by the marginal cost plus a target margin, around which the market price is permitted to fluctuate. We float the introduction of GenAI Agents as Institutional Market Makers. As the arms race for greater autonomy of agnetic systems grows, the commercial viability of AI agents has the potential to disseminate into every-day users directly interacting with them rather than e-commerce platforms. This is also under the assumption of expected transactional capabilities being given to AI Agents.
|
||||
Our analysis of the interaction dynamics between the platform and non-human actors suggests that the current static pricing models are insufficient for an agent-mediated economy. If we assume a transition toward a direct revelation mechanism, where actors must reveal their true valuation of a good through bidding dynamics, we inevitably introduce significant stochasticity into the pricing system. Unlike traditional e-commerce where prices are relatively sticky, such a mechanism implies a high volatility characteristic of financial equity markets (without the fungibility however).
|
||||
|
||||
However, e-commerce commodities differ fundamentally from financial securities: they possess a hard floor defined by unit economics and reservation prices. The market might react enthusiastically to an iPhone priced at \$1. Such a transaction is not permissible. The platform must establish an initial valuation anchor ($P_0$) defined by the marginal cost plus a target margin, around which the market price is permitted to fluctuate.
|
||||
|
||||
We float the introduction of GenAI Agents as Institutional Market Makers. As the arms race for greater autonomy of agentic systems grows, the commercial viability of AI agents has the potential to disseminate into everyday users directly interacting with them rather than e-commerce platforms. This is also under the assumption of expected transactional capabilities being given to AI Agents.
|
||||
|
||||
\subsection{Risk Assessment and Limitations}
|
||||
\label{sec:limitations_risks}
|
||||
|
||||
This technology does not come without a more bitter side, ethical concerns do arise from the idea of deploying black-box like solutions to set prices based on a behavioral attributes. Approaches like universal behavioral profile modeling (UBPM) used in recommendation systems is very broadly utilized.
|
||||
Behavior-based pricing raises predictable ethics questions when models are opaque: a behavioral profile can become a basis for price discrimination or exclusion if deployed without governance. Universal behavioral profile modeling (UBPM) in recommendation already shows how fine-grained traces enable strong personalization. The same machinery applied to prices needs guardrails.
|
||||
|
||||
With a system like this there is potential for strong drift given the rapid advance of agentic systems and user preference. Our intent behind adding the UX term into the reward shaping process was to further address the risk of degraded user experience. Looking deeper at the underlying methodology, reinforcement learning does not come without it's complications such as reward hacking and often the lack of intepretability which is quite critical in systems that have a strong impact on the revenue of a company.
|
||||
|
||||
\subsection{Implications of Findings}
|
||||
We balance human and agent sessions near one-to-one so cohorts are comparable despite different population sizes. The row-level dataset still contains thousands of events.
|
||||
|
||||
Interpretation of results and altenrative scenarios with broader market implications.
|
||||
% Rapid change in agent capabilities and user expectations induces model drift; the UX term in reward shaping was included partly to penalize policies that sacrifice legitimate users for short-run revenue. Reinforcement learning adds its own risks---reward hacking and limited interpretability---which matter when policies touch live revenue; deployment would require monitoring and constraints beyond what we exercised here.
|
||||
With the exponential growth in capability of agents aswell as user expectations, a degree of model drift is expected in this setting. The computational requirements for continuous extraction of margin as demonstrated by our work are required by the persistent speed of the market. Reinforcement learning that sacrifices legitimate user experience for short run revenue does not hold up in the long run. Reward hacking, to which pricing algorithms are not impervious due to their limited interpretability, is a significant risk for a company if live revenue is in play. Deployment requires consistent monitoring and constraints beyond what was done as an exercise in this work.
|
||||
|
||||
% \subsection{Implications of Findings} Interpretation of results and altenrative scenarios with broader market implications.
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
\section{Conclusion}
|
||||
\label{sec:conclusion}
|
||||
|
||||
For our troubles, we now conclude that...
|
||||
This thesis examined reinforcement-learning policies for dynamic pricing when a fraction of traffic is orchestrated by non-human agents intent on extracting information before purchase. We introduced COI-oriented metrics, a behavioral distinguishability layer, and a distributionally robust training loop, empirical runs show where robustness helps and where it must be tuned.
|
||||
|
||||
\subsection{Summary of contributions}
|
||||
The authors contribution was not without the advice of many experienced experts in the field. We thank Marco Casalaina VP Products, Core AI and AI Futurist at Microsoft for the initial critical discussion on the topic of dynamic pricing systems and the spark which has lead to this work. Eugene Bykovets, PhD pointing out the parallels in blockchain systems and the complexity of anonymous interaction and understanding of intent. Importantly, the contributions of Alberto Martín Izquierdo, my academic advisor for the support over and for taking on the challenge of this ambitious work. Many breakthroughs were thanks to numerous discussions with my peers on the topics covered here.
|
||||
A thanks to the head of innovation at Amadeus for insight into the industry split on the topic of collapsing margins. Finally we acknowledge the power and use of generative AI technologies for in depth research, rapid prototyping and surfacing of key topics and niches.
|
||||
Our work has yielded a broad set of dependencies which we carefully orchestrated to give us measurable results. To give a clear picture we outline the specific contributions of each stage of our work. The theoretical component formalizes why agent-mediated reconnaissance erodes pricing power, the behavioral component establishes that such contamination is detectable from interaction traces alone, the control component translates that distinguishability into a robust pricing mechanism, and the systems component provides the controlled experimental environment required to observe, test, and reproduce these effects.
|
||||
|
||||
\subsection{Future Works and Next Steps}
|
||||
\begin{itemize}
|
||||
\item TPU-accelerated parallelization of the behavioral simulation and reinforcement learning pipeline, making large factorial sweeps tractable.
|
||||
\item Formalization of non-human transaction orchestration in e-commerce as a distinct source of contamination in dynamic pricing systems.
|
||||
\item Definition of the Cost of Information (COI) as a mechanism-level quantity for pricing power, together with a theorem on its erosion under increasing agent saturation.
|
||||
\item Design and implementation of a controlled e-commerce research platform on a hybrid Kappa--Lambda architecture for collecting and replaying high-fidelity interaction trajectories.
|
||||
\item Construction and empirical validation of a behavioral distinguishability framework that separates human and agent sessions from interaction signals alone using transition kernels and KL-based divergence.
|
||||
\item A generative contamination mechanism that injects learned agent behavior into the pricing environment for controlled robustness experiments.
|
||||
\item Translation of distinguishability scores into defensive pricing via distributionally robust reinforcement learning under non-stationary contamination.
|
||||
\item Evidence that contamination depresses revenue and that robustness gains are regime-dependent, so penalties and radii need calibration rather than a single default.
|
||||
\item Release of a public experimental artifact (code and dataset) for reproducing and extending work on agent-mediated traffic.
|
||||
\end{itemize}
|
||||
|
||||
During the eights months of research dedicated to this work, a plethora of opportunities and industry gaps was identified, sadly a majority of which could not be addressed directly.
|
||||
\subsection{Limitations and future work}
|
||||
|
||||
Several constraints are intentional and could be relaxed later. Action weights in the demand proxy are currently derived from simple divergence rankings, learning them from data is an obvious next step. We propose a jointly learn the demand proxy, policy, and simulator parameters instead of treating them modularly. Another avenue we could not cover in this work is incorporating Bayesian methods better capture demand uncertainty and propagation of that uncertainty into reward systems.
|
||||
The Stackelberg interface assumes a clean alternation between platform move and market response. Richer histories (multi-agent, multi-platform) would need a less rigid state definition. Non-perishable catalog supply in the simulator widens the sim-to-real gap for inventory-constrained domains. Within-session contamination is modeled as stable, time-varying $\alpha$ inside a session would better match some attack patterns.
|
||||
|
||||
Before any deployment, human baselines should grow beyond the convenience sample used here, catalog scaling laws should be re-checked when transition matrices grow with SKU count, and the full pipeline should be re-validated under production traffic volumes, governance constraints, and product mixes.
|
||||
We conclude our work with enthusiasm for future developments in the field of agent mediated commerce, we are excited to provide the foundations for these developments and hope to see future work in similar spirit.
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
\section{Acknowledgements}
|
||||
\section*{Acknowledgements}
|
||||
|
||||
Eugene Bykovets, PhD - ETH
|
||||
This research was supported by the TPU Research Cloud program, which provided access to Google Cloud Tensor Processing Unit (TPU) accelerators, including TPU v4, v5e, and v6e.
|
||||
|
||||
I am grateful to Marco Casalaina (VP of Product, Core AI, Microsoft) for an early conversation on dynamic pricing that helped frame the problem. Eugene Bykovets (Ph.D.) pointed out useful parallels with blockchain systems and the difficulty of inferring intent under pseudonymity. Alberto Mart\'{i}n Izquierdo supervised this work and accepted an unusually wide brief. Several peers contributed through discussion of the topics covered here. The head of innovation at Amadeus offered industry perspective on margin compression under automation.
|
||||
|
||||
Generative tools were used for literature search, prototyping, and drafting support; all claims, experiments, and final wording remain the author's responsibility.
|
||||
|
||||
165
paper/src/chapters/auto/whoclicked_dataset_card.md
Normal file
165
paper/src/chapters/auto/whoclicked_dataset_card.md
Normal file
@@ -0,0 +1,165 @@
|
||||
---
|
||||
pretty_name: whoclickedit
|
||||
license: mit
|
||||
language:
|
||||
- en
|
||||
task_categories:
|
||||
- tabular-classification
|
||||
task_ids:
|
||||
- tabular-multi-class-classification
|
||||
tags:
|
||||
- e-commerce
|
||||
- dynamic-pricing
|
||||
- behavioral-telemetry
|
||||
- human-vs-agent
|
||||
- session-data
|
||||
size_categories:
|
||||
- 1K<n<10K
|
||||
---
|
||||
|
||||
<img align="right" width="280" src="https://raw.githubusercontent.com/velocitatem/PHANTOM/main/docs/static/images/banner.svg" alt="PHANTOM research banner" />
|
||||
|
||||
# [whoclickedit](https://huggingface.co/datasets/velocitatem/whoclickedit)
|
||||
|
||||
[](https://huggingface.co/datasets/velocitatem/whoclickedit)
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
> **Event-level behavior data for dynamic pricing research.**
|
||||
> This dataset captures how humans and automated agents browse, query prices, and move through the PHANTOM storefronts during controlled experiments.
|
||||
|
||||
## What this dataset gives you
|
||||
|
||||
- A single flat file (`whoclicked.csv`) with both interaction and price-log events.
|
||||
- Explicit labels for actor origin: `actor_type` and `is_agent`.
|
||||
- Provenance fields from Kafka envelopes when available.
|
||||
- Metadata flattened into feature-ready `metadata_*` columns.
|
||||
|
||||
## Snapshot
|
||||
|
||||
| Metric | Value |
|
||||
| --- | --- |
|
||||
| Rows | `3874` |
|
||||
| Columns | `42` |
|
||||
| Time range (UTC) | `2025-12-05T09:43:31.301000+00:00` -> `2026-03-23T12:08:30.151000+00:00` |
|
||||
| Unique sessions | `36` |
|
||||
|
||||
## Composition
|
||||
|
||||
### Rows by actor
|
||||
| Actor | Rows | Share |
|
||||
| --- | --- | --- |
|
||||
| `human` | 798 | 20.6% |
|
||||
| `agent` | 3076 | 79.4% |
|
||||
|
||||
### Rows by actor and record type
|
||||
| Actor | Record type | Rows |
|
||||
| --- | --- | --- |
|
||||
| `agent` | `interaction` | 197 |
|
||||
| `agent` | `price_log` | 2879 |
|
||||
| `human` | `interaction` | 328 |
|
||||
| `human` | `price_log` | 470 |
|
||||
|
||||
### Store mode coverage
|
||||
| Store mode | Rows |
|
||||
| --- | --- |
|
||||
| `hotel` | 3628 |
|
||||
| `airline` | 196 |
|
||||
| `shop` | 50 |
|
||||
|
||||
### Top interaction events
|
||||
| Interaction event | Count |
|
||||
| --- | --- |
|
||||
| `page_view` | 246 |
|
||||
| `learn_more_about_item` | 91 |
|
||||
| `view_item_page` | 88 |
|
||||
| `add_item_to_cart` | 47 |
|
||||
| `hover_over_title` | 23 |
|
||||
| `checkout_start` | 20 |
|
||||
| `hover_over_paragraph` | 6 |
|
||||
| `remove_item` | 4 |
|
||||
|
||||
## Collection pipeline
|
||||
|
||||
Data is sourced from two roots inside PHANTOM:
|
||||
|
||||
- `experiments/collected_data` (human sessions)
|
||||
- `experiments/agents/collected_data` (agent sessions)
|
||||
|
||||
Each session directory contains:
|
||||
|
||||
- `int.json`: user interaction events
|
||||
- `price.json`: price quote observations
|
||||
|
||||
ETL behavior:
|
||||
|
||||
1. Accepts both Kafka-envelope records and flat payload records.
|
||||
2. Flattens nested JSON to a tabular schema.
|
||||
3. Preserves row-level provenance (`source_session_dir`, `source_row_index`, topic fields).
|
||||
4. Adds modeling labels (`actor_type`, `is_agent`, `record_type`).
|
||||
|
||||
## Schema highlights
|
||||
|
||||
Core modeling fields:
|
||||
|
||||
- `actor_type`, `is_agent`, `record_type`
|
||||
- `sessionId`, `experimentId`, `storeMode`, `ts`
|
||||
- `eventName`, `page`, `productId`, `price`, `userAgent`
|
||||
|
||||
Kafka provenance fields:
|
||||
|
||||
- `kafka_partition_id`, `kafka_offset`, `kafka_timestamp_ms`, `kafka_compression`
|
||||
- `kafka_is_transactional`, `kafka_headers`, `kafka_key_*`, `kafka_value_*`
|
||||
|
||||
<details>
|
||||
<summary>Metadata columns in this release</summary>
|
||||
|
||||
- `metadata_cabinClass`
|
||||
- `metadata_dateIndex`
|
||||
- `metadata_dwellTime`
|
||||
- `metadata_elementText`
|
||||
- `metadata_fareRule`
|
||||
- `metadata_flightType`
|
||||
- `metadata_itemCount`
|
||||
- `metadata_nights`
|
||||
- `metadata_price`
|
||||
- `metadata_referrer`
|
||||
- `metadata_roomType`
|
||||
- `metadata_total`
|
||||
- `metadata_type`
|
||||
|
||||
</details>
|
||||
|
||||
## Quick start
|
||||
|
||||
```python
|
||||
from datasets import load_dataset
|
||||
|
||||
ds = load_dataset("velocitatem/whoclickedit")
|
||||
```
|
||||
|
||||
Recommended split strategy:
|
||||
|
||||
- Prefer session-aware or time-aware splits.
|
||||
- Do not split rows from the same `sessionId` across train and test.
|
||||
|
||||
## Intended use
|
||||
|
||||
- Human-vs-agent behavior classification.
|
||||
- Session-level telemetry modeling for dynamic pricing defenses.
|
||||
- Robustness experiments under agent-mediated reconnaissance.
|
||||
|
||||
## Safety and limitations
|
||||
|
||||
- `userAgent` and referrer metadata can be quasi-identifying in very small samples.
|
||||
- Data comes from a controlled research platform, not a full production marketplace.
|
||||
- Current release has stronger coverage for `hotel` flows than `airline` flows.
|
||||
|
||||
## Citation
|
||||
|
||||
If you use this dataset, cite the PHANTOM thesis project and link this page:
|
||||
`https://huggingface.co/datasets/velocitatem/whoclickedit`
|
||||
3
paper/src/chapters/figures/.gitignore
vendored
Normal file
3
paper/src/chapters/figures/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pdf-view-restore
|
||||
36
paper/src/chapters/figures/experiment_design_tree.tex
Normal file
36
paper/src/chapters/figures/experiment_design_tree.tex
Normal file
@@ -0,0 +1,36 @@
|
||||
% Horizontal tree: level distance must exceed ~half parent + half child width or nodes overlap (resizebox does not fix that).
|
||||
\begin{tikzpicture}[
|
||||
grow=right,
|
||||
level distance=30mm,
|
||||
sibling distance=23mm,
|
||||
decision/.style={
|
||||
rectangle,
|
||||
draw,
|
||||
rounded corners=1.5pt,
|
||||
align=center,
|
||||
inner sep=1.2pt,
|
||||
minimum width=14mm,
|
||||
minimum height=4.8mm,
|
||||
font=\scriptsize,
|
||||
},
|
||||
leaf/.style={
|
||||
rectangle,
|
||||
draw,
|
||||
align=center,
|
||||
inner sep=1.2pt,
|
||||
text width=19mm,
|
||||
minimum height=4mm,
|
||||
font=\scriptsize,
|
||||
},
|
||||
edge from parent/.style={draw, -{Latex[length=1.2mm]}},
|
||||
]
|
||||
\node[decision] {Participant}
|
||||
child {
|
||||
node[decision] {Platform: Hotel}
|
||||
child {node[leaf] {Task sampled\\from hotel pool}}
|
||||
}
|
||||
child {
|
||||
node[decision] {Platform: Airline}
|
||||
child {node[leaf] {Task sampled\\from airline pool}}
|
||||
};
|
||||
\end{tikzpicture}
|
||||
@@ -0,0 +1,12 @@
|
||||
alpha,revenue_delta,revenue_delta_pct,reward_delta,reward_delta_pct,volatility_delta,supra_delta,coi_leakage_delta
|
||||
0.0,-17982.383542886935,-5.11072862876989,-17145.799161982606,-5.235033672101227,0.001232973729699119,0.0,-0.0030412479577408003
|
||||
0.1,-14962.041501283413,-4.410637208586118,-14303.760282736213,-4.531344436782669,0.0011858665298920962,0.0,-0.004133727080174038
|
||||
0.2,-16153.416666167905,-4.826514761457546,-15398.621298776357,-4.9418165571901715,0.00200624274016295,0.0,-0.0033201883450373615
|
||||
0.3,-17294.9275360335,-5.382423616385397,-16544.91845114401,-5.533399709364953,-0.0011022484400295268,0.0,-0.0029151149203366505
|
||||
0.4,-19543.8750398212,-6.215299839915013,-18613.487687777204,-6.35858461426586,-2.7530592947980215e-05,0.0,-0.0038561140856475523
|
||||
0.5,-16411.03168918495,-5.3630681206030015,-15638.77510066732,-5.4888928630525315,0.00015428950526953644,0.0,-0.00439661338956944
|
||||
0.6,-14729.668247641937,-5.069964928178309,-13912.22417824401,-5.148827377884945,-0.002735776807082743,0.0,-0.004310129386364658
|
||||
0.7,-21160.81910514756,-7.351404104505076,-20171.762105623755,-7.525169314210056,-0.0008903632602569461,0.0,-0.0026198461183787186
|
||||
0.8,-16404.76825612632,-5.9342582959227075,-15645.025250480074,-6.078699946285722,0.0010338614665691137,0.0,-0.002542765270289696
|
||||
0.9,-8674.090655496111,-3.2592966246269577,-8371.30734891587,-3.378943339994106,-0.0005579187914590139,0.0,-0.0013720835439427759
|
||||
1.0,768.8099906174757,0.2991618705853567,399.7394696234842,0.16706914330070038,0.0014659834822295797,0.0,-0.0007600066499474645
|
||||
|
@@ -0,0 +1,23 @@
|
||||
alpha,mode,runs,revenue_mean,reward_mean,supra_mean,volatility_mean,coi_leakage_mean,coi_level_mean
|
||||
0.0,baseline,36,351855.57381502265,327520.32242613373,0.0,0.06922494093544151,0.11931704468268205,136.80105514058158
|
||||
0.0,defended,35,333873.1902721357,310374.5232641511,0.0,0.07045791466514063,0.11627579672494125,136.81832905386602
|
||||
0.1,baseline,32,339226.3020897988,315662.6136522988,0.0,0.06952778671756812,0.11924519238669087,136.47864859317326
|
||||
0.1,defended,33,324264.2605885154,301358.8533695626,0.0,0.07071365324746022,0.11511146530651684,136.7200845824852
|
||||
0.2,baseline,31,334680.76789409376,311598.399506997,0.0,0.06848006194428993,0.11597869134898402,136.83684469591932
|
||||
0.2,defended,35,318527.35122792586,296199.77820822067,0.0,0.07048630468445288,0.11265850300394666,137.2758153292305
|
||||
0.3,baseline,30,321322.30327214615,299000.9636054795,0.0,0.07085669473747759,0.11527347603412934,136.4452630715689
|
||||
0.3,defended,44,304027.37573611265,282456.0451543355,0.0,0.06975444629744806,0.11235836111379269,136.4704115371568
|
||||
0.4,baseline,33,314447.8230046008,292730.04633793415,0.0,0.07038147753765028,0.11304685781445543,136.70817144219887
|
||||
0.4,defended,38,294903.9479647796,274116.55865015695,0.0,0.0703539469447023,0.10919074372880788,136.75671002806396
|
||||
0.5,baseline,33,306000.80625751516,284916.7489847879,0.0,0.06938663916591635,0.11118137138243217,136.9528780620641
|
||||
0.5,defended,35,289589.7745683302,269277.9738841206,0.0,0.06954092867118589,0.10678475799286273,136.65018588845163
|
||||
0.6,baseline,28,290528.0106727377,270201.7985298805,0.0,0.07139577980623227,0.11081647254398667,135.258395468266
|
||||
0.6,defended,41,275798.3424250958,256289.57435163652,0.0,0.06866000299914952,0.10650634315762202,136.3194947785247
|
||||
0.7,baseline,40,287847.3119465684,268057.25244656845,0.0,0.07132313199532896,0.10746267580456732,137.0170522633547
|
||||
0.7,defended,40,266686.49284142087,247885.4903409447,0.0,0.07043276873507201,0.1048428296861886,136.56834095392904
|
||||
0.8,baseline,26,276441.76303208206,257374.52726285128,0.0,0.06945655282263205,0.1063246766773884,136.66765260798618
|
||||
0.8,defended,39,260036.99477595574,241729.5020123712,0.0,0.07049041428920116,0.1037819114070987,136.61222667078658
|
||||
0.9,baseline,35,266133.8213268301,247749.2667554015,0.0,0.0709569180547784,0.10455882265976374,136.5370653814206
|
||||
0.9,defended,39,257459.73067133396,239377.95940648564,0.0,0.07039899926331938,0.10318673911582096,136.7368893225831
|
||||
1.0,baseline,35,256987.96076959255,239265.888198164,0.0,0.06888231148034313,0.10369761394735275,136.68691718467974
|
||||
1.0,defended,30,257756.77076021003,239665.62766778748,0.0,0.07034829496257271,0.10293760729740528,136.65287739235566
|
||||
|
@@ -0,0 +1,45 @@
|
||||
alpha,n_products,baseline_runs,defended_runs,baseline_coi_level_mean,defended_coi_level_mean,coi_preserved,coi_preserved_pct
|
||||
0.0,5.0,9,10,137.060822623968,136.18680853180368,-0.874014092164316,-0.6376833842316922
|
||||
0.0,25.0,9,2,137.114858903596,136.13793579187393,-0.9769231117220727,-0.7124852255501622
|
||||
0.0,50.0,9,11,137.16224858153575,136.92415566181484,-0.23809291972091273,-0.17358487643878118
|
||||
0.0,100.0,9,12,135.86629045322655,137.3609873086303,1.4946968554037596,1.1001234010420895
|
||||
0.1,5.0,3,6,136.59581715538818,135.6308466787041,-0.9649704766840728,-0.7064421859904723
|
||||
0.1,25.0,11,8,135.9860669350444,136.43616365263273,0.45009671758833747,0.33098737814318313
|
||||
0.1,50.0,10,11,136.28362874897243,136.92880179422633,0.6451730452538982,0.4734046570203046
|
||||
0.1,100.0,8,8,137.35578496752095,137.53394777402949,0.17816280650853855,0.12970899372797937
|
||||
0.2,5.0,8,9,135.55116314329388,137.30311388107864,1.7519507377847674,1.2924645551973204
|
||||
0.2,25.0,10,9,137.01587649612287,137.22137163685403,0.20549514073115915,0.1499790724887083
|
||||
0.2,50.0,4,8,137.45096138958434,137.1307018163465,-0.32025957323784837,-0.2329991511155169
|
||||
0.2,100.0,9,9,137.50780776750915,137.43195025898902,-0.07585750852013007,-0.0551659645744523
|
||||
0.3,5.0,6,6,134.95569459599133,134.21855668602896,-0.7371379099623709,-0.5462073402453271
|
||||
0.3,25.0,9,16,136.38346021911525,136.32131251342705,-0.06214770568820427,-0.04556835967378819
|
||||
0.3,50.0,8,6,136.97414077213367,136.88041560990786,-0.09372516222580884,-0.06842544271310845
|
||||
0.3,100.0,7,16,137.19706520314455,137.31020460277784,0.11313939963329744,0.08246488324351146
|
||||
0.4,5.0,8,11,135.6494813257779,136.5487738152141,0.899292489436192,0.6629531352769695
|
||||
0.4,25.0,7,9,136.38451372914378,136.10614648175604,-0.27836724738773455,-0.20410473284420322
|
||||
0.4,50.0,7,10,137.12976275807247,136.98838321468799,-0.14137954338448822,-0.10309909427460566
|
||||
0.4,100.0,11,8,137.4158065068933,137.4849148270489,0.06910832015560686,0.050291390715769026
|
||||
0.5,5.0,7,19,135.91101413475477,136.145621134976,0.2346070002212457,0.1726180925915501
|
||||
0.5,25.0,8,7,137.0972914279529,137.35620682163616,0.2589153936832531,0.18885522170896996
|
||||
0.5,50.0,8,1,137.0714841014652,135.66696334266234,-1.404520758802846,-1.0246629837050352
|
||||
0.5,100.0,10,8,137.4717672869487,137.35366167964338,-0.11810560730532416,-0.08591262746975456
|
||||
0.6,5.0,8,13,133.13626070539635,136.09936023073067,2.9630995253343144,2.225614201296411
|
||||
0.6,25.0,5,10,136.0741624588533,136.26219778039936,0.18803532154606728,0.13818591137970535
|
||||
0.6,50.0,8,10,135.09036188289087,136.05846380616936,0.968101923278482,0.7166328595060871
|
||||
0.6,100.0,7,8,137.29304001584052,137.07512338179083,-0.2179166340496863,-0.15872372993164377
|
||||
0.7,5.0,7,7,136.0533783988379,135.14350016006424,-0.9098782387736719,-0.6687656341075052
|
||||
0.7,25.0,8,11,137.12781750399415,136.8176582131797,-0.3101592908144539,-0.2261826203172962
|
||||
0.7,50.0,14,11,137.06965735909125,136.7028634119364,-0.3667939471548607,-0.26759674914335285
|
||||
0.7,100.0,11,11,137.48279078937205,137.09121810549402,-0.39157268387802446,-0.28481578067317975
|
||||
0.8,5.0,4,7,135.3095773096514,136.59715728802078,1.2875799783693935,0.9515808148766959
|
||||
0.8,25.0,12,13,136.93488398652164,135.73319876476054,-1.201685221761096,-0.8775596011600497
|
||||
0.8,50.0,6,8,136.4704324290659,136.86568018140107,0.39524775233516607,0.289621528487943
|
||||
0.8,100.0,4,11,137.519864039095,137.4763376137669,-0.04352642532811046,-0.03165100957032396
|
||||
0.9,5.0,5,5,134.77024204025943,136.6651608019597,1.8949187617002679,1.4060364758669837
|
||||
0.9,25.0,9,13,136.7554042236364,136.06108143100832,-0.6943227926280713,-0.507711411164888
|
||||
0.9,50.0,10,12,136.08715955450202,137.07569864767092,0.988539093168896,0.7264014447836223
|
||||
0.9,100.0,11,9,137.57053132642514,137.30115968842037,-0.2693716380047704,-0.19580620602940735
|
||||
1.0,5.0,5,7,136.43177888041947,135.92674388998284,-0.5050349904366271,-0.37017401266847305
|
||||
1.0,25.0,11,9,136.7037183889911,136.22617845471228,-0.47753993427880914,-0.34932475861407586
|
||||
1.0,50.0,11,5,136.93074105866745,137.05826644845806,0.12752538979060546,0.09313130769953819
|
||||
1.0,100.0,8,9,136.4880191421812,137.41913068956546,0.9311115473842619,0.682192879079234
|
||||
|
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"bundle": "/home/velocitatem/Documents/Projects/PHANTOM/engine/studies/results/wandb_sweep_bundles/bundle_20260317_122818",
|
||||
"focus_cohort": "max_alpha_coverage",
|
||||
"focus_sweep_id": "i88nw811",
|
||||
"focus_run_count": 768,
|
||||
"git_commit": "ace52e8e14e0f7fa96ab5eb113c0c898b0bce1a0",
|
||||
"alpha_cells": 11,
|
||||
"alpha_min": 0.0,
|
||||
"alpha_max": 1.0,
|
||||
"mean_revenue_delta_pct": -4.784039478033151,
|
||||
"mean_reward_delta_pct": -4.913967517075595,
|
||||
"zone_summary": [
|
||||
{
|
||||
"zone": "high_alpha_0_7_plus",
|
||||
"alpha_cells": 4,
|
||||
"revenue_delta_pct_mean": -4.0614492886173466,
|
||||
"reward_delta_pct_mean": -4.2039358642972955,
|
||||
"coi_leakage_delta_mean": -0.0018236753956396637,
|
||||
"volatility_delta_mean": 0.00026289072427068336
|
||||
},
|
||||
{
|
||||
"zone": "low_alpha_below_0_7",
|
||||
"alpha_cells": 7,
|
||||
"revenue_delta_pct_mean": -5.196948157699325,
|
||||
"reward_delta_pct_mean": -5.319699890091765,
|
||||
"coi_leakage_delta_mean": -0.003710447880695786,
|
||||
"volatility_delta_mean": 0.00010197380928049306
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
zone,alpha_cells,revenue_delta_pct_mean,reward_delta_pct_mean,coi_leakage_delta_mean,volatility_delta_mean
|
||||
high_alpha_0_7_plus,4,-4.0614492886173466,-4.2039358642972955,-0.0018236753956396637,0.00026289072427068336
|
||||
low_alpha_below_0_7,7,-5.196948157699325,-5.319699890091765,-0.003710447880695786,0.00010197380928049306
|
||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"normality": {
|
||||
"test": "jarque_bera",
|
||||
"available": true,
|
||||
"statistic": 362.38850707984324,
|
||||
"p_value": 2.0339278125496517e-79
|
||||
},
|
||||
"heteroskedasticity": {
|
||||
"test": "breusch_pagan",
|
||||
"available": true,
|
||||
"lm_stat": 6.0366025380616275,
|
||||
"df": 1,
|
||||
"p_value": 0.014012224810767138
|
||||
},
|
||||
"influence": {
|
||||
"max_leverage": 0.03769234230180875,
|
||||
"mean_leverage": 0.021052631578947392,
|
||||
"high_leverage_threshold": 0.042105263157894736,
|
||||
"high_leverage_count": 0,
|
||||
"max_cooks_distance": 0.29121755538277183,
|
||||
"high_cooks_threshold": 0.042105263157894736,
|
||||
"high_cooks_count": 6
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
sweep_id,sweep_full_id,run_id,run_name,state,run_url,created_at,runtime,downloaded_files,history_rows,selected_for_clone,download_error,alpha,n_products,eta_ux,lambda_coi,baseline_mode,no_robust,study_mode,eval_revenue_mean,eval_reward_mean,eval_stress_revenue_worst,eval_stress_reward_worst,eval_supra_share_mean,eval_supra_penalty_mean,eval_volatility_mean,eval_upward_volatility_mean,eval_coi_level_mean,eval_coi_leakage_mean,objective_score,mode
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,0yph6ddt,sweep/ppo/sb3/cpu/default/a0.7/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/0yph6ddt,2026-03-15T13:48:47Z,7579.766959963,0,0,0,,0.7,100.0,0.0,0.05,True,True,baseline,285875.15518050164,266287.2051805016,274356.50146499986,255620.24146499988,0.0,0.0,0.0711188680417482,0.0,137.42722406640746,0.1099719716550294,255620.24146499988,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,bjwmxlf4,sweep/ppo/sb3/cpu/default/a0.9/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/bjwmxlf4,2026-03-15T13:48:49Z,7514.003863569,0,0,0,,0.9,100.0,0.0,0.05,True,True,baseline,267194.6114143838,248902.78141438385,258791.60782635584,241079.0878263559,0.0,0.0,0.0706779448814682,0.0,137.4716591479769,0.1060063717489262,241079.0878263559,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,afod7srx,sweep/ppo/sb3/cpu/default/a0/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/afod7srx,2026-03-15T13:48:55Z,8428.923550896,0,0,0,,0.0,100.0,0.0,0.15,True,True,baseline,331626.71399641165,307929.2839964116,301903.22363424243,278909.22363424255,0.0,0.0,0.0699106903089938,0.0,134.44341240328637,0.1239456985672444,278909.22363424255,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,czbwbw4o,sweep/ppo/sb3/cpu/default/a0.3/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/czbwbw4o,2026-03-15T13:48:55Z,8019.834460958,0,0,0,,0.3,100.0,0.0,0.05,True,True,baseline,325062.60932028474,302657.9893202848,313580.73955351143,292103.1195535114,0.0,0.0,0.0700934793925504,0.0,137.30226556155992,0.1156304945350146,292103.1195535114,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,spncr5i5,sweep/ppo/sb3/cpu/default/a0.4/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/spncr5i5,2026-03-15T13:48:57Z,7984.536208498,0,0,0,,0.4,100.0,0.0,0.3,True,True,baseline,313890.156459866,292317.566459866,301905.6061551721,281189.2661551722,0.0,0.0,0.0700585666613017,0.0,137.27393385978286,0.1140225013120235,281189.2661551722,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,9utcbgal,sweep/ppo/sb3/cpu/default/a0.6/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/9utcbgal,2026-03-15T13:48:58Z,7794.573495005,0,0,0,,0.6,100.0,0.0,0.3,True,True,baseline,296881.4938150014,276559.4338150014,282693.0664052287,263321.0864052287,0.0,0.0,0.0689497793839256,0.0,137.65459475595475,0.1116745762120893,263321.0864052287,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,6uhc0zfi,sweep/ppo/sb3/cpu/default/a0.1/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/6uhc0zfi,2026-03-15T13:48:59Z,8739.343652451,5,5000,1,,0.1,100.0,0.0,0.3,True,True,baseline,345607.36851277394,321934.388512774,330271.9018417394,307619.2418417394,0.0,0.0,0.0688978199434404,0.0,137.65927138408344,0.1180576040723697,307619.2418417394,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,mid9h16o,sweep/ppo/sb3/cpu/default/a0.3/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/mid9h16o,2026-03-15T13:48:59Z,7934.709025792,0,0,0,,0.3,100.0,0.0,0.15,True,True,baseline,321120.1030044527,298922.9430044526,312002.2572538445,290604.6972538445,0.0,0.0,0.0725338635316591,0.0,136.9642983472208,0.1152504371251349,290604.6972538445,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,hm8geh95,sweep/ppo/sb3/cpu/default/a0.3/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/hm8geh95,2026-03-15T13:49:01Z,8324.170881475,0,0,0,,0.3,100.0,0.0,0.05,True,True,baseline,321120.1030044527,298922.9430044526,312002.2572538445,290604.6972538445,0.0,0.0,0.0725338635316591,0.0,136.9642983472208,0.1152504371251349,290604.6972538445,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,2k3bx48e,sweep/ppo/sb3/cpu/default/a0.7/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/2k3bx48e,2026-03-15T13:49:03Z,7579.046562713,0,0,0,,0.7,100.0,0.0,0.3,True,True,baseline,288003.5379862045,268208.7279862045,274205.49798255006,255466.81798255,0.0,0.0,0.0732015803628115,0.0,137.25851714050424,0.1065894678006264,255466.81798255,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,mlcllxuf,sweep/ppo/sb3/cpu/default/a0.3/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/mlcllxuf,2026-03-15T15:28:13Z,8048.447950291,0,0,0,,0.3,100.0,0.0,0.05,True,True,baseline,325062.60932028474,302657.9893202848,313580.73955351143,292103.1195535114,0.0,0.0,0.0700934793925504,0.0,137.30226556155992,0.1156304945350146,292103.1195535114,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,gsx5p3xl,sweep/ppo/sb3/cpu/default/a0.7/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/gsx5p3xl,2026-03-15T15:29:00Z,7666.062008427,0,0,0,,0.7,100.0,0.0,0.3,True,True,baseline,286859.8032779717,267231.9932779717,273198.5349293896,254530.3349293896,0.0,0.0,0.0694378534785247,0.0,137.6169536272908,0.1086813731317916,254530.3349293896,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,dh2sidg0,sweep/ppo/sb3/cpu/default/a0.8/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/dh2sidg0,2026-03-15T15:31:51Z,7450.114589126,0,0,0,,0.8,100.0,0.0,0.3,True,True,baseline,277537.1135308166,258574.23353081665,260525.6140973399,242761.4740973399,0.0,0.0,0.0691119185711536,0.0,137.63850710873982,0.1055234893030045,242761.4740973399,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,izb1xfjn,sweep/ppo/sb3/cpu/default/a0.4/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/izb1xfjn,2026-03-15T15:38:35Z,8138.431632101,0,0,0,,0.4,100.0,0.0,0.05,True,True,baseline,313890.156459866,292317.566459866,301905.6061551721,281189.2661551722,0.0,0.0,0.0700585666613017,0.0,137.27393385978286,0.1140225013120235,281189.2661551722,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,h5v0bjkk,sweep/ppo/sb3/cpu/default/a1/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/h5v0bjkk,2026-03-15T15:53:08Z,7430.137394885,0,0,0,,1.0,100.0,0.0,0.05,True,True,baseline,258250.4083985968,240558.37839859675,257579.27605596423,239906.35605596425,0.0,0.0,0.0710781742010645,0.0,137.43891114039735,0.1034797519569495,239906.35605596425,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,oo9x7mtj,sweep/ppo/sb3/cpu/default/a0/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/oo9x7mtj,2026-03-15T17:08:57Z,8434.676111878,0,0,0,,0.0,100.0,0.0,0.15,True,True,baseline,331626.71399641165,307929.2839964116,301903.22363424243,278909.22363424255,0.0,0.0,0.0699106903089938,0.0,134.44341240328637,0.1239456985672444,278909.22363424255,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,2tnqjvsr,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/2tnqjvsr,2026-03-15T17:10:41Z,8326.316856098,0,0,0,,0.2,100.0,0.0,0.3,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,uwl4b1t4,sweep/ppo/sb3/cpu/default/a0.6/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/uwl4b1t4,2026-03-15T17:11:41Z,7730.138244902,0,0,0,,0.6,100.0,0.0,0.15,True,True,baseline,293934.0132863448,273673.5532863448,278235.2158621181,259045.3158621181,0.0,0.0,0.0702286844227449,0.0,137.02187396075487,0.1108792101893818,259045.3158621181,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,mq08631s,sweep/ppo/sb3/cpu/default/a0.7/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/mq08631s,2026-03-15T17:11:46Z,7830.903683379,0,0,0,,0.7,100.0,0.0,0.3,True,True,baseline,286859.8032779717,267231.9932779717,273198.5349293896,254530.3349293896,0.0,0.0,0.0694378534785247,0.0,137.6169536272908,0.1086813731317916,254530.3349293896,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,oenf81vs,sweep/ppo/sb3/cpu/default/a0.9/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/oenf81vs,2026-03-15T17:14:03Z,7571.420325966,0,0,0,,0.9,100.0,0.0,0.15,True,True,baseline,268129.28805568966,249777.98805568964,259354.03651639624,241657.8165163962,0.0,0.0,0.0692141212557269,0.0,137.56737533812094,0.1028102128114812,241657.8165163962,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,imvig8ea,sweep/ppo/sb3/cpu/default/a0.9/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/imvig8ea,2026-03-15T17:26:17Z,7548.356923917,0,0,0,,0.9,100.0,0.0,0.05,True,True,baseline,269095.26288012683,250709.3028801269,257985.06236888352,240343.2023688835,0.0,0.0,0.0687681637998595,0.0,137.63174822647662,0.1040919495927453,240343.2023688835,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,kc46mwot,sweep/ppo/sb3/cpu/default/a0.9/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/kc46mwot,2026-03-15T17:36:54Z,7402.437478922,0,0,0,,0.9,100.0,0.0,0.3,True,True,baseline,269095.26288012683,250709.3028801269,257985.06236888352,240343.2023688835,0.0,0.0,0.0687681637998595,0.0,137.63174822647662,0.1040919495927453,240343.2023688835,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,6c5g20m0,sweep/ppo/sb3/cpu/default/a0.4/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/6c5g20m0,2026-03-15T17:39:15Z,7987.751960449,0,0,0,,0.4,100.0,0.0,0.05,True,True,baseline,314792.9405088838,293199.96050888376,304000.02795477153,283160.5079547715,0.0,0.0,0.0706474903672308,0.0,137.54347765167836,0.1134114537317883,283160.5079547715,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,zmfirgme,sweep/ppo/sb3/cpu/default/a0.6/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/zmfirgme,2026-03-15T17:39:38Z,7729.43292327,0,0,0,,0.6,100.0,0.0,0.3,True,True,baseline,296881.4938150014,276559.4338150014,282693.0664052287,263321.0864052287,0.0,0.0,0.0689497793839256,0.0,137.65459475595475,0.1116745762120893,263321.0864052287,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,5w978f6n,sweep/ppo/sb3/cpu/default/a0.2/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/5w978f6n,2026-03-15T17:42:23Z,8196.563842857,0,0,0,,0.2,100.0,0.0,0.3,True,True,baseline,328662.28105387173,305848.95105387166,316489.4913151873,294621.8913151873,0.0,0.0,0.0726481757500429,0.0,136.60489081120323,0.115056283050696,294621.8913151873,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,v6yuq532,sweep/ppo/sb3/cpu/default/a0.3/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/v6yuq532,2026-03-15T18:27:32Z,8171.524047551,0,0,0,,0.3,100.0,0.0,0.3,True,True,baseline,325536.3728999571,303203.77289995714,311530.19009115506,290169.93009115505,0.0,0.0,0.0690101249418158,0.0,137.57976469566975,0.115140125484157,290169.93009115505,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,wzs4h708,sweep/ppo/sb3/cpu/default/a1/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/wzs4h708,2026-03-15T18:44:40Z,7213.500579862,0,0,0,,1.0,100.0,0.0,0.3,True,True,baseline,258250.4083985968,240558.37839859675,257579.27605596423,239906.35605596425,0.0,0.0,0.0710781742010645,0.0,137.43891114039735,0.1034797519569495,239906.35605596425,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,drjegsa8,sweep/ppo/sb3/cpu/default/a0.8/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/drjegsa8,2026-03-15T18:53:51Z,7642.750902648,0,0,0,,0.8,100.0,0.0,0.05,True,True,baseline,278042.9708277731,258987.21082777312,265119.53279206343,246979.39279206347,0.0,0.0,0.069699479796535,0.0,137.47635104131075,0.1063946886684759,246979.39279206347,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,np3fvzwt,sweep/ppo/sb3/cpu/default/a0.9/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/np3fvzwt,2026-03-15T18:57:50Z,7300.325366337,0,0,0,,0.9,100.0,0.0,0.3,True,True,baseline,269095.26288012683,250709.3028801269,257985.06236888352,240343.2023688835,0.0,0.0,0.0687681637998595,0.0,137.63174822647662,0.1040919495927453,240343.2023688835,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,kk0sqa97,sweep/ppo/sb3/cpu/default/a0.1/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/kk0sqa97,2026-03-15T19:06:17Z,8525.177181009,0,0,0,,0.1,100.0,0.0,0.3,True,True,baseline,341404.1205957663,317885.0305957663,329505.50925893825,306817.3492589383,0.0,0.0,0.0685274095002656,0.0,137.33021724658855,0.1206998447923596,306817.3492589383,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,i0rpx1kf,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/i0rpx1kf,2026-03-15T19:20:36Z,8356.73493734,0,0,0,,0.2,100.0,0.0,0.05,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,lqmaq5g2,sweep/ppo/sb3/cpu/default/a1/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/lqmaq5g2,2026-03-15T20:02:28Z,7470.274064026,0,0,0,,1.0,100.0,0.0,0.05,True,True,baseline,246584.29279154172,229303.12279154177,244564.78814724492,227386.888147245,0.0,0.0,0.0692074374069363,0.0,135.2844805658817,0.1093837602765936,227386.888147245,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,2umearxm,sweep/ppo/sb3/cpu/default/a0.5/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/2umearxm,2026-03-15T20:09:56Z,7829.406313163,0,0,0,,0.5,100.0,0.0,0.3,True,True,baseline,303325.5596877454,282520.29968774534,291965.65710567136,271937.69710567134,0.0,0.0,0.0686525035124021,0.0,137.57073544790862,0.1132342695408356,271937.69710567134,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,k7pirqxy,sweep/ppo/sb3/cpu/default/a1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/k7pirqxy,2026-03-15T20:33:53Z,7216.626889631,0,0,0,,1.0,100.0,0.0,0.15,True,True,baseline,254537.24517731377,236935.99517731369,254471.2696855663,236912.16968556636,0.0,0.0,0.0703905833083271,0.0,136.6143424312229,0.1038838810036006,236912.16968556636,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,algnjce4,sweep/ppo/sb3/cpu/default/a0.6/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/algnjce4,2026-03-15T20:54:24Z,7739.30650029,0,0,0,,0.6,100.0,0.0,0.05,True,True,baseline,296881.4938150014,276559.4338150014,282693.0664052287,263321.0864052287,0.0,0.0,0.0689497793839256,0.0,137.65459475595475,0.1116745762120893,263321.0864052287,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,vqe2dmcq,sweep/ppo/sb3/cpu/default/a0.4/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/vqe2dmcq,2026-03-15T21:08:22Z,7815.774646473,0,0,0,,0.4,100.0,0.0,0.05,True,True,baseline,316543.04043212667,294899.01043212664,299980.59649797506,279386.7564979751,0.0,0.0,0.067603468946279,0.0,137.7846896269947,0.1128739206843639,279386.7564979751,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,0xlvpawh,sweep/ppo/sb3/cpu/default/a0.3/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/0xlvpawh,2026-03-15T21:16:04Z,7997.68392245,0,0,0,,0.3,100.0,0.0,0.15,True,True,baseline,325062.60932028474,302657.9893202848,313580.73955351143,292103.1195535114,0.0,0.0,0.0700934793925504,0.0,137.30226556155992,0.1156304945350146,292103.1195535114,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,bofuxayn,sweep/ppo/sb3/cpu/default/a0.7/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/bofuxayn,2026-03-15T21:18:05Z,7486.102336723,0,0,0,,0.7,100.0,0.0,0.05,True,True,baseline,285875.15518050164,266287.2051805016,274356.50146499986,255620.24146499988,0.0,0.0,0.0711188680417482,0.0,137.42722406640746,0.1099719716550294,255620.24146499988,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,rujnezt7,sweep/ppo/sb3/cpu/default/a0.5/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/rujnezt7,2026-03-15T21:20:23Z,7936.01356938,0,0,0,,0.5,100.0,0.0,0.15,True,True,baseline,305342.590984541,284402.02098454104,287794.11179162114,267934.8717916211,0.0,0.0,0.0698329564541014,0.0,137.34875112178105,0.1110975441706762,267934.8717916211,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,f9e6wtv0,sweep/ppo/sb3/cpu/default/a0.7/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/f9e6wtv0,2026-03-15T22:07:04Z,8030.825365422,0,0,0,,0.7,100.0,0.0,0.05,True,True,baseline,288003.5379862045,268208.7279862045,274205.49798255006,255466.81798255,0.0,0.0,0.0732015803628115,0.0,137.25851714050424,0.1065894678006264,255466.81798255,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,r8hsz3ko,sweep/ppo/sb3/cpu/default/a0.7/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/r8hsz3ko,2026-03-15T22:13:06Z,7691.998775531,0,0,0,,0.7,100.0,0.0,0.3,True,True,baseline,286859.8032779717,267231.9932779717,273198.5349293896,254530.3349293896,0.0,0.0,0.0694378534785247,0.0,137.6169536272908,0.1086813731317916,254530.3349293896,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,yukg46hv,sweep/ppo/sb3/cpu/default/a1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/yukg46hv,2026-03-15T23:03:27Z,7094.861108483,0,0,0,,1.0,100.0,0.0,0.15,True,True,baseline,254537.24517731377,236935.99517731369,254471.2696855663,236912.16968556636,0.0,0.0,0.0703905833083271,0.0,136.6143424312229,0.1038838810036006,236912.16968556636,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,e5tciezz,sweep/ppo/sb3/cpu/default/a0.7/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/e5tciezz,2026-03-16T00:16:08Z,7569.145925588,0,0,0,,0.7,100.0,0.0,0.05,True,True,baseline,285875.15518050164,266287.2051805016,274356.50146499986,255620.24146499988,0.0,0.0,0.0711188680417482,0.0,137.42722406640746,0.1099719716550294,255620.24146499988,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,1rop5sf9,sweep/ppo/sb3/cpu/default/a0.3/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/1rop5sf9,2026-03-16T00:21:00Z,8354.617713686,0,0,0,,0.3,100.0,0.0,0.05,True,True,baseline,321120.1030044527,298922.9430044526,312002.2572538445,290604.6972538445,0.0,0.0,0.0725338635316591,0.0,136.9642983472208,0.1152504371251349,290604.6972538445,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,7muxpseb,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/7muxpseb,2026-03-16T00:21:21Z,8514.602541985,0,0,0,,0.2,100.0,0.0,0.05,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,304dyypp,sweep/ppo/sb3/cpu/default/a0.4/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/304dyypp,2026-03-16T00:37:04Z,7949.736292204,0,0,0,,0.4,100.0,0.0,0.3,True,True,baseline,313890.156459866,292317.566459866,301905.6061551721,281189.2661551722,0.0,0.0,0.0700585666613017,0.0,137.27393385978286,0.1140225013120235,281189.2661551722,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,zbw7nmeo,sweep/ppo/sb3/cpu/default/a0.1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/zbw7nmeo,2026-03-16T00:53:02Z,8423.598177489,0,0,0,,0.1,100.0,0.0,0.05,True,True,baseline,340941.7898046945,317438.6698046944,328185.5337341634,305593.15373416344,0.0,0.0,0.0709483560344898,0.0,137.21682561970587,0.1186714838821206,305593.15373416344,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,oxu7rm37,sweep/ppo/sb3/cpu/default/a0.9/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/oxu7rm37,2026-03-16T00:53:31Z,7464.830361968,0,0,0,,0.9,100.0,0.0,0.3,True,True,baseline,268129.28805568966,249777.98805568964,259354.03651639624,241657.8165163962,0.0,0.0,0.0692141212557269,0.0,137.56737533812094,0.1028102128114812,241657.8165163962,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,m78p26vk,sweep/ppo/sb3/cpu/default/a0/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/m78p26vk,2026-03-16T00:56:58Z,8717.289024041,5,1004,1,,0.0,100.0,0.0,0.15,True,True,baseline,348861.1454509751,324713.0754509751,335967.6160126648,312660.3160126648,0.0,0.0,0.0674835742466741,0.0,136.8813175598437,0.118985751213389,312660.3160126648,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,65zzmszh,sweep/ppo/sb3/cpu/default/a1/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/65zzmszh,2026-03-16T01:14:03Z,7326.553384609,0,0,0,,1.0,100.0,0.0,0.3,True,True,baseline,246584.29279154172,229303.12279154177,244564.78814724492,227386.888147245,0.0,0.0,0.0692074374069363,0.0,135.2844805658817,0.1093837602765936,227386.888147245,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,47xraqt6,sweep/ppo/sb3/cpu/default/a0.9/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/47xraqt6,2026-03-16T01:22:01Z,7299.814264453,0,0,0,,0.9,100.0,0.0,0.3,True,True,baseline,269095.26288012683,250709.3028801269,257985.06236888352,240343.2023688835,0.0,0.0,0.0687681637998595,0.0,137.63174822647662,0.1040919495927453,240343.2023688835,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,mibyt0bf,sweep/ppo/sb3/cpu/default/a0.9/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/mibyt0bf,2026-03-16T01:34:44Z,7541.153639959,0,0,0,,0.9,100.0,0.0,0.3,True,True,baseline,267194.6114143838,248902.78141438385,258791.60782635584,241079.0878263559,0.0,0.0,0.0706779448814682,0.0,137.4716591479769,0.1060063717489262,241079.0878263559,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,8ww25eu1,sweep/ppo/sb3/cpu/default/a0.4/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/8ww25eu1,2026-03-16T01:45:51Z,8003.812511886,0,0,0,,0.4,100.0,0.0,0.3,True,True,baseline,313890.156459866,292317.566459866,301905.6061551721,281189.2661551722,0.0,0.0,0.0700585666613017,0.0,137.27393385978286,0.1140225013120235,281189.2661551722,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,cxdz0iyj,sweep/ppo/sb3/cpu/default/a0.6/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/cxdz0iyj,2026-03-16T01:50:19Z,7623.493600288,0,0,0,,0.6,100.0,0.0,0.3,True,True,baseline,293934.0132863448,273673.5532863448,278235.2158621181,259045.3158621181,0.0,0.0,0.0702286844227449,0.0,137.02187396075487,0.1108792101893818,259045.3158621181,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,1aeqr4sw,sweep/ppo/sb3/cpu/default/a1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/1aeqr4sw,2026-03-16T01:58:10Z,7156.375097998,0,0,0,,1.0,100.0,0.0,0.3,True,True,baseline,254537.24517731377,236935.99517731369,254471.2696855663,236912.16968556636,0.0,0.0,0.0703905833083271,0.0,136.6143424312229,0.1038838810036006,236912.16968556636,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,7sgqchvk,sweep/ppo/sb3/cpu/default/a0.9/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/7sgqchvk,2026-03-16T02:09:14Z,7268.202978965,0,0,0,,0.9,100.0,0.0,0.15,True,True,baseline,267194.6114143838,248902.78141438385,258791.60782635584,241079.0878263559,0.0,0.0,0.0706779448814682,0.0,137.4716591479769,0.1060063717489262,241079.0878263559,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,3s777ena,sweep/ppo/sb3/cpu/default/a0.5/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/3s777ena,2026-03-16T02:14:54Z,7762.769931002,0,0,0,,0.5,100.0,0.0,0.05,True,True,baseline,303325.5596877454,282520.29968774534,291965.65710567136,271937.69710567134,0.0,0.0,0.0686525035124021,0.0,137.57073544790862,0.1132342695408356,271937.69710567134,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,oxsvuh5p,sweep/ppo/sb3/cpu/default/a0.1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/oxsvuh5p,2026-03-16T02:27:01Z,8529.692612353,0,0,0,,0.1,100.0,0.0,0.15,True,True,baseline,340941.7898046945,317438.6698046944,328185.5337341634,305593.15373416344,0.0,0.0,0.0709483560344898,0.0,137.21682561970587,0.1186714838821206,305593.15373416344,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,4unnwl9l,sweep/ppo/sb3/cpu/default/a0.7/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/4unnwl9l,2026-03-16T02:34:01Z,7780.065361146,0,0,0,,0.7,100.0,0.0,0.15,True,True,baseline,286859.8032779717,267231.9932779717,273198.5349293896,254530.3349293896,0.0,0.0,0.0694378534785247,0.0,137.6169536272908,0.1086813731317916,254530.3349293896,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,qlfu6ts4,sweep/ppo/sb3/cpu/default/a0.1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/qlfu6ts4,2026-03-16T02:46:52Z,8357.276406226,0,0,0,,0.1,100.0,0.0,0.3,True,True,baseline,340941.7898046945,317438.6698046944,328185.5337341634,305593.15373416344,0.0,0.0,0.0709483560344898,0.0,137.21682561970587,0.1186714838821206,305593.15373416344,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,ya2bb56z,sweep/ppo/sb3/cpu/default/a1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/ya2bb56z,2026-03-16T03:04:37Z,7161.126998896,0,0,0,,1.0,100.0,0.0,0.15,True,True,baseline,254537.24517731377,236935.99517731369,254471.2696855663,236912.16968556636,0.0,0.0,0.0703905833083271,0.0,136.6143424312229,0.1038838810036006,236912.16968556636,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,9hrjmcaf,sweep/ppo/sb3/cpu/default/a0.1/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/9hrjmcaf,2026-03-16T03:13:29Z,8543.819880598,5,1004,1,,0.1,100.0,0.0,0.15,True,True,baseline,345607.36851277394,321934.388512774,330271.9018417394,307619.2418417394,0.0,0.0,0.0688978199434404,0.0,137.65927138408344,0.1180576040723697,307619.2418417394,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,bdz7jpg9,sweep/ppo/sb3/cpu/default/a0.4/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/bdz7jpg9,2026-03-16T03:19:29Z,8156.512730959,0,0,0,,0.4,100.0,0.0,0.15,True,True,baseline,313890.156459866,292317.566459866,301905.6061551721,281189.2661551722,0.0,0.0,0.0700585666613017,0.0,137.27393385978286,0.1140225013120235,281189.2661551722,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,4e8bw9fr,sweep/ppo/sb3/cpu/default/a0.4/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/4e8bw9fr,2026-03-16T03:23:44Z,7900.988162577,0,0,0,,0.4,100.0,0.0,0.3,True,True,baseline,313890.156459866,292317.566459866,301905.6061551721,281189.2661551722,0.0,0.0,0.0700585666613017,0.0,137.27393385978286,0.1140225013120235,281189.2661551722,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,rudposqg,sweep/ppo/sb3/cpu/default/a0.8/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/rudposqg,2026-03-16T04:16:36Z,7803.944972672,0,0,0,,0.8,100.0,0.0,0.15,True,True,baseline,277186.5585556976,258169.5585556976,260819.58418764165,242908.9641876417,0.0,0.0,0.0684627361221973,0.0,137.3260908975896,0.1077409453905398,242908.9641876417,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,r24xwwl9,sweep/ppo/sb3/cpu/default/a0.1/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/r24xwwl9,2026-03-16T04:43:43Z,8571.635566955,0,0,0,,0.1,100.0,0.0,0.15,True,True,baseline,340941.7898046945,317438.6698046944,328185.5337341634,305593.15373416344,0.0,0.0,0.0709483560344898,0.0,137.21682561970587,0.1186714838821206,305593.15373416344,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,34c0wzgt,sweep/ppo/sb3/cpu/default/a0.5/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/34c0wzgt,2026-03-16T04:43:54Z,7912.776898111,0,0,0,,0.5,100.0,0.0,0.05,True,True,baseline,306631.1127310434,285624.6727310434,292140.0218133485,272205.32181334845,0.0,0.0,0.0706121906603894,0.0,137.48236407441985,0.112886126809283,272205.32181334845,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,7bvonhab,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/7bvonhab,2026-03-16T04:59:24Z,8276.510250338,0,0,0,,0.2,100.0,0.0,0.15,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,4f7j1z4p,sweep/ppo/sb3/cpu/default/a0/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/4f7j1z4p,2026-03-16T05:37:06Z,8672.519975981,5,1004,1,,0.0,100.0,0.0,0.3,True,True,baseline,352771.72255003714,328513.3625500371,337718.8770159761,314393.4970159762,0.0,0.0,0.0709252720738168,0.0,137.49769422651883,0.1192149910017191,314393.4970159762,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,c33cyjv9,sweep/ppo/sb3/cpu/default/a0.4/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/c33cyjv9,2026-03-16T05:38:08Z,8164.154912737,0,0,0,,0.4,100.0,0.0,0.15,True,True,baseline,314792.9405088838,293199.96050888376,304000.02795477153,283160.5079547715,0.0,0.0,0.0706474903672308,0.0,137.54347765167836,0.1134114537317883,283160.5079547715,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,i0pylqm1,sweep/ppo/sb3/cpu/default/a0.6/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/i0pylqm1,2026-03-16T05:54:46Z,7692.357589996,0,0,0,,0.6,100.0,0.0,0.15,True,True,baseline,293934.0132863448,273673.5532863448,278235.2158621181,259045.3158621181,0.0,0.0,0.0702286844227449,0.0,137.02187396075487,0.1108792101893818,259045.3158621181,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,p1lrhc1t,sweep/ppo/sb3/cpu/default/a0.5/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/p1lrhc1t,2026-03-16T06:06:24Z,7906.656203638,0,0,0,,0.5,100.0,0.0,0.15,True,True,baseline,304711.516143744,283789.716143744,290536.18598250934,270609.3259825093,0.0,0.0,0.0700712626186499,0.0,137.43043602946972,0.1112796769387625,270609.3259825093,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,lkhtnobk,sweep/ppo/sb3/cpu/default/a0.9/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/lkhtnobk,2026-03-16T06:25:11Z,7304.77470818,0,0,0,,0.9,100.0,0.0,0.3,True,True,baseline,269095.26288012683,250709.3028801269,257985.06236888352,240343.2023688835,0.0,0.0,0.0687681637998595,0.0,137.63174822647662,0.1040919495927453,240343.2023688835,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,dvf0av6p,sweep/ppo/sb3/cpu/default/a0/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/dvf0av6p,2026-03-16T06:34:22Z,8568.236301103,0,0,0,,0.0,100.0,0.0,0.3,True,True,baseline,331626.71399641165,307929.2839964116,301903.22363424243,278909.22363424255,0.0,0.0,0.0699106903089938,0.0,134.44341240328637,0.1239456985672444,278909.22363424255,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,k6dz4he1,sweep/ppo/sb3/cpu/default/a0/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/k6dz4he1,2026-03-16T06:38:33Z,8384.405275426,0,0,0,,0.0,100.0,0.0,0.05,True,True,baseline,331626.71399641165,307929.2839964116,301903.22363424243,278909.22363424255,0.0,0.0,0.0699106903089938,0.0,134.44341240328637,0.1239456985672444,278909.22363424255,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,3afj9zm5,sweep/ppo/sb3/cpu/default/a0.4/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/3afj9zm5,2026-03-16T06:51:33Z,7947.433015786,0,0,0,,0.4,100.0,0.0,0.3,True,True,baseline,313890.156459866,292317.566459866,301905.6061551721,281189.2661551722,0.0,0.0,0.0700585666613017,0.0,137.27393385978286,0.1140225013120235,281189.2661551722,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,lvlojvjv,sweep/ppo/sb3/cpu/default/a0.5/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/lvlojvjv,2026-03-16T07:17:09Z,8072.460782252,0,0,0,,0.5,100.0,0.0,0.05,True,True,baseline,305342.590984541,284402.02098454104,287794.11179162114,267934.8717916211,0.0,0.0,0.0698329564541014,0.0,137.34875112178105,0.1110975441706762,267934.8717916211,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,e6xtq7h5,sweep/ppo/sb3/cpu/default/a0.5/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/e6xtq7h5,2026-03-16T07:20:29Z,8062.476629606,0,0,0,,0.5,100.0,0.0,0.05,True,True,baseline,306631.1127310434,285624.6727310434,292140.0218133485,272205.32181334845,0.0,0.0,0.0706121906603894,0.0,137.48236407441985,0.112886126809283,272205.32181334845,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,6yrs8xci,sweep/ppo/sb3/cpu/default/a0.6/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/6yrs8xci,2026-03-16T07:50:01Z,7609.609823102,0,0,0,,0.6,100.0,0.0,0.15,True,True,baseline,293934.0132863448,273673.5532863448,278235.2158621181,259045.3158621181,0.0,0.0,0.0702286844227449,0.0,137.02187396075487,0.1108792101893818,259045.3158621181,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,16l3qjpm,sweep/ppo/sb3/cpu/default/a0/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/16l3qjpm,2026-03-16T07:50:41Z,8443.503878801,5,1004,1,,0.0,100.0,0.0,0.15,True,True,baseline,348861.1454509751,324713.0754509751,335967.6160126648,312660.3160126648,0.0,0.0,0.0674835742466741,0.0,136.8813175598437,0.118985751213389,312660.3160126648,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,rg98ht1b,sweep/ppo/sb3/cpu/default/a0/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/rg98ht1b,2026-03-16T07:55:36Z,8843.938343818,5,1004,1,,0.0,100.0,0.0,0.05,True,True,baseline,348861.1454509751,324713.0754509751,335967.6160126648,312660.3160126648,0.0,0.0,0.0674835742466741,0.0,136.8813175598437,0.118985751213389,312660.3160126648,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,mxd3i6wr,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/mxd3i6wr,2026-03-16T07:58:03Z,8393.28184472,0,0,0,,0.2,100.0,0.0,0.15,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,0xvyhpg2,sweep/ppo/sb3/cpu/default/a0.9/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/0xvyhpg2,2026-03-16T08:01:43Z,7441.092473369,0,0,0,,0.9,100.0,0.0,0.05,True,True,baseline,268129.28805568966,249777.98805568964,259354.03651639624,241657.8165163962,0.0,0.0,0.0692141212557269,0.0,137.56737533812094,0.1028102128114812,241657.8165163962,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,eull6lat,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/eull6lat,2026-03-16T08:03:08Z,8338.76018915,0,0,0,,0.2,100.0,0.0,0.05,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,5zekml75,sweep/ppo/sb3/cpu/default/a0.8/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/5zekml75,2026-03-16T08:06:29Z,7265.4990034,0,0,0,,0.8,100.0,0.0,0.15,True,True,baseline,277537.1135308166,258574.23353081665,260525.6140973399,242761.4740973399,0.0,0.0,0.0691119185711536,0.0,137.63850710873982,0.1055234893030045,242761.4740973399,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,fed0y4px,sweep/ppo/sb3/cpu/default/a0.7/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/fed0y4px,2026-03-16T08:13:55Z,7800.555020283,0,0,0,,0.7,100.0,0.0,0.05,True,True,baseline,286859.8032779717,267231.9932779717,273198.5349293896,254530.3349293896,0.0,0.0,0.0694378534785247,0.0,137.6169536272908,0.1086813731317916,254530.3349293896,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,byifn20j,sweep/ppo/sb3/cpu/default/a0.4/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/byifn20j,2026-03-16T08:20:55Z,8108.199462596,0,0,0,,0.4,100.0,0.0,0.3,True,True,baseline,316543.04043212667,294899.01043212664,299980.59649797506,279386.7564979751,0.0,0.0,0.067603468946279,0.0,137.7846896269947,0.1128739206843639,279386.7564979751,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,35rb8529,sweep/ppo/sb3/cpu/default/a0.5/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/35rb8529,2026-03-16T08:24:52Z,7749.649896228,0,0,0,,0.5,100.0,0.0,0.05,True,True,baseline,304711.516143744,283789.716143744,290536.18598250934,270609.3259825093,0.0,0.0,0.0700712626186499,0.0,137.43043602946972,0.1112796769387625,270609.3259825093,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,foinu2r1,sweep/ppo/sb3/cpu/default/a0.5/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/foinu2r1,2026-03-16T08:51:50Z,7924.351691656,0,0,0,,0.5,100.0,0.0,0.05,True,True,baseline,306631.1127310434,285624.6727310434,292140.0218133485,272205.32181334845,0.0,0.0,0.0706121906603894,0.0,137.48236407441985,0.112886126809283,272205.32181334845,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,nsg7m2ud,sweep/ppo/sb3/cpu/default/a0.5/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/nsg7m2ud,2026-03-16T09:06:10Z,7732.794663489,0,0,0,,0.5,100.0,0.0,0.3,True,True,baseline,303325.5596877454,282520.29968774534,291965.65710567136,271937.69710567134,0.0,0.0,0.0686525035124021,0.0,137.57073544790862,0.1132342695408356,271937.69710567134,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,gpririem,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/gpririem,2026-03-16T09:20:57Z,8532.119121611,0,0,0,,0.2,100.0,0.0,0.3,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,9bmbalnk,sweep/ppo/sb3/cpu/default/a0.7/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/9bmbalnk,2026-03-16T10:05:49Z,7576.93090345,0,0,0,,0.7,100.0,0.0,0.15,True,True,baseline,285875.15518050164,266287.2051805016,274356.50146499986,255620.24146499988,0.0,0.0,0.0711188680417482,0.0,137.42722406640746,0.1099719716550294,255620.24146499988,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,9ma76sch,sweep/ppo/sb3/cpu/default/a0.1/baseline/s1337,finished,https://wandb.ai/lusiana/capstone_tpu/runs/9ma76sch,2026-03-16T10:23:59Z,8544.8427845,0,0,0,,0.1,100.0,0.0,0.3,True,True,baseline,341404.1205957663,317885.0305957663,329505.50925893825,306817.3492589383,0.0,0.0,0.0685274095002656,0.0,137.33021724658855,0.1206998447923596,306817.3492589383,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,cvrztiyb,sweep/ppo/sb3/cpu/default/a0.2/baseline/s42,finished,https://wandb.ai/lusiana/capstone_tpu/runs/cvrztiyb,2026-03-16T10:27:26Z,8353.396268583,0,0,0,,0.2,100.0,0.0,0.3,True,True,baseline,333463.32883383776,310606.38883383776,322375.37087837915,300349.6308783791,0.0,0.0,0.0694238399850746,0.0,137.6206723870474,0.1176551945750585,300349.6308783791,baseline
|
||||
i88nw811,lusiana/capstone_tpu/i88nw811,7z9spcc6,sweep/ppo/sb3/cpu/default/a0/baseline/s7777,finished,https://wandb.ai/lusiana/capstone_tpu/runs/7z9spcc6,2026-03-16T10:29:46Z,8444.449882423,5,1004,1,,0.0,100.0,0.0,0.3,True,True,baseline,348861.1454509751,324713.0754509751,335967.6160126648,312660.3160126648,0.0,0.0,0.0674835742466741,0.0,136.8813175598437,0.118985751213389,312660.3160126648,baseline
|
||||
|
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"n": 95,
|
||||
"k": 2,
|
||||
"dof": 93,
|
||||
"df_t": 93,
|
||||
"cov_type": "hc1",
|
||||
"clusters": null,
|
||||
"r2": 0.9759651432807543,
|
||||
"adj_r2": 0.9757067039611925,
|
||||
"sse": 1872600419.7223544,
|
||||
"coefficients": [
|
||||
{
|
||||
"name": "intercept",
|
||||
"coef": 348823.4131652292,
|
||||
"std_error": 1383.3660823209932,
|
||||
"t_stat": 252.15553397115096,
|
||||
"p_value": 0.0,
|
||||
"ci95_low": 346076.3222890517,
|
||||
"ci95_high": 351570.5040414067
|
||||
},
|
||||
{
|
||||
"name": "alpha",
|
||||
"coef": -90140.52744561416,
|
||||
"std_error": 2185.134882447838,
|
||||
"t_stat": -41.25169945785529,
|
||||
"p_value": 0.0,
|
||||
"ci95_low": -94479.77225976942,
|
||||
"ci95_high": -85801.2826314589
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
sweep_id,n,alpha_coef,alpha_std_error,alpha_t_stat,alpha_p_value,alpha_ci95_low,alpha_ci95_high,r2
|
||||
i88nw811,95,-90140.52744561416,2185.134882447838,-41.25169945785529,0.0,-94479.77225976942,-85801.2826314589,0.9759651432807543
|
||||
|
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"bundle_dir": "/home/velocitatem/Documents/Projects/PHANTOM/engine/studies/results/wandb_sweep_bundles/bundle_20260317_122818",
|
||||
"git_commit": "e62e842faad79b143f5555d187075e85c8926363",
|
||||
"cohort_name": "original_n95_baseline_n100",
|
||||
"filters": {
|
||||
"sweep_id": [
|
||||
"i88nw811"
|
||||
],
|
||||
"mode": "baseline",
|
||||
"n_products": 100.0,
|
||||
"eta_ux": 0.0,
|
||||
"lambda_coi": null,
|
||||
"alpha_min": 0.0,
|
||||
"alpha_max": 1.0
|
||||
},
|
||||
"n_rows": 95,
|
||||
"n_sweeps": 1,
|
||||
"alpha_unique": [
|
||||
0.0,
|
||||
0.1,
|
||||
0.2,
|
||||
0.3,
|
||||
0.4,
|
||||
0.5,
|
||||
0.6,
|
||||
0.7,
|
||||
0.8,
|
||||
0.9,
|
||||
1.0
|
||||
],
|
||||
"rows_by_sweep": {
|
||||
"i88nw811": 95
|
||||
},
|
||||
"rows_by_mode": {
|
||||
"baseline": 95
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"n": 95,
|
||||
"k": 2,
|
||||
"dof": 93,
|
||||
"df_t": 93,
|
||||
"cov_type": "iid",
|
||||
"clusters": null,
|
||||
"r2": 0.9759651432807543,
|
||||
"adj_r2": 0.9757067039611925,
|
||||
"sse": 1872600419.7223544,
|
||||
"coefficients": [
|
||||
{
|
||||
"name": "intercept",
|
||||
"coef": 348823.4131652292,
|
||||
"std_error": 860.7176431608721,
|
||||
"t_stat": 405.2704344298337,
|
||||
"p_value": 0.0,
|
||||
"ci95_low": 347114.1985078009,
|
||||
"ci95_high": 350532.6278226575
|
||||
},
|
||||
{
|
||||
"name": "alpha",
|
||||
"coef": -90140.52744561416,
|
||||
"std_error": 1466.838282353916,
|
||||
"t_stat": -61.452259959401054,
|
||||
"p_value": 0.0,
|
||||
"ci95_low": -93053.37756806448,
|
||||
"ci95_high": -87227.67732316385
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
\includegraphics[width=0.98\linewidth]{chapters/figures/results/generated/final/plots/final_focus_coi_by_alpha.pdf}
|
||||
@@ -0,0 +1 @@
|
||||
\includegraphics[width=0.98\linewidth]{chapters/figures/results/generated/final/plots/final_focus_coi_preservation_grid.pdf}
|
||||
@@ -0,0 +1 @@
|
||||
\includegraphics[width=0.98\linewidth]{chapters/figures/results/generated/final/plots/final_focus_revenue_by_alpha.pdf}
|
||||
@@ -0,0 +1 @@
|
||||
\includegraphics[width=0.95\linewidth]{chapters/figures/results/generated/final/plots/final_focus_revenue_delta.pdf}
|
||||
@@ -0,0 +1 @@
|
||||
\includegraphics[width=0.95\linewidth]{chapters/figures/results/generated/final/plots/final_focus_risk_deltas.pdf}
|
||||
658
paper/src/chapters/figures/results/plot_wandb_export.py
Normal file
658
paper/src/chapters/figures/results/plot_wandb_export.py
Normal file
@@ -0,0 +1,658 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.ticker import FuncFormatter
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def _load_tikzplotlib():
|
||||
def _patch_webcolors() -> None:
|
||||
try:
|
||||
import webcolors
|
||||
|
||||
if hasattr(webcolors, "CSS3_HEX_TO_NAMES"):
|
||||
return
|
||||
css3 = getattr(webcolors, "CSS3", "css3")
|
||||
webcolors.CSS3_HEX_TO_NAMES = {
|
||||
webcolors.name_to_hex(name, spec=css3): name
|
||||
for name in webcolors.names(spec=css3)
|
||||
}
|
||||
except Exception:
|
||||
return
|
||||
|
||||
_patch_webcolors()
|
||||
|
||||
try:
|
||||
from matplotlib.legend import Legend
|
||||
|
||||
if not hasattr(Legend, "_ncol") and hasattr(Legend, "_ncols"):
|
||||
Legend._ncol = property(lambda self: self._ncols)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
import tikzplotlib as module
|
||||
|
||||
return module, None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
from matplotlib.backends import backend_pgf
|
||||
|
||||
if not hasattr(backend_pgf, "common_texification") and hasattr(
|
||||
backend_pgf, "_tex_escape"
|
||||
):
|
||||
backend_pgf.common_texification = backend_pgf._tex_escape
|
||||
|
||||
_patch_webcolors()
|
||||
|
||||
import tikzplotlib as module
|
||||
|
||||
return module, None
|
||||
except Exception as exc:
|
||||
return None, exc
|
||||
|
||||
|
||||
TIKZPLOTLIB, TIKZPLOTLIB_IMPORT_ERROR = _load_tikzplotlib()
|
||||
|
||||
|
||||
def _default_output_dir() -> Path:
|
||||
return Path(__file__).resolve().parent / "generated" / "wandb"
|
||||
|
||||
|
||||
def _default_plot_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "plots"
|
||||
|
||||
|
||||
def _sanitize(key: str) -> str:
|
||||
return key.replace("/", "_").replace("-", "_")
|
||||
|
||||
|
||||
def _configure_style() -> None:
|
||||
plt.rcParams.update(
|
||||
{
|
||||
"font.family": "serif",
|
||||
"font.size": 10,
|
||||
"axes.titlesize": 10,
|
||||
"axes.labelsize": 9,
|
||||
"legend.fontsize": 8,
|
||||
"xtick.labelsize": 8,
|
||||
"ytick.labelsize": 8,
|
||||
"figure.dpi": 220,
|
||||
"savefig.dpi": 320,
|
||||
"axes.spines.top": False,
|
||||
"axes.spines.right": False,
|
||||
"axes.grid": True,
|
||||
"grid.alpha": 0.22,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _fmt_thousands(value: float, _: int) -> str:
|
||||
return f"{int(value):,}"
|
||||
|
||||
|
||||
def _coerce_numeric(frame: pd.DataFrame, columns: Iterable[str]) -> None:
|
||||
for column in columns:
|
||||
if column in frame.columns:
|
||||
frame[column] = pd.to_numeric(frame[column], errors="coerce")
|
||||
|
||||
|
||||
def _extract_alpha(frame: pd.DataFrame) -> pd.Series:
|
||||
if "study/alpha" in frame.columns:
|
||||
return pd.to_numeric(frame["study/alpha"], errors="coerce")
|
||||
if "alpha" in frame.columns:
|
||||
return pd.to_numeric(frame["alpha"], errors="coerce")
|
||||
return pd.Series(np.nan, index=frame.index, dtype=float)
|
||||
|
||||
|
||||
def _extract_mode(frame: pd.DataFrame) -> pd.Series:
|
||||
if "study/mode" in frame.columns:
|
||||
mode = frame["study/mode"].astype(str).str.strip().str.lower()
|
||||
mapping = {
|
||||
"baseline": "baseline",
|
||||
"no_robust": "baseline",
|
||||
"defended": "defended",
|
||||
"robust": "defended",
|
||||
}
|
||||
return mode.map(mapping).fillna("")
|
||||
|
||||
if "study/no_robust" in frame.columns:
|
||||
no_robust = pd.to_numeric(frame["study/no_robust"], errors="coerce").fillna(0.0)
|
||||
return pd.Series(
|
||||
np.where(no_robust > 0.5, "baseline", "defended"),
|
||||
index=frame.index,
|
||||
dtype="object",
|
||||
)
|
||||
|
||||
if "no_robust" in frame.columns:
|
||||
no_robust = (
|
||||
frame["no_robust"].astype(str).str.lower().isin({"1", "true", "yes"})
|
||||
)
|
||||
return pd.Series(
|
||||
np.where(no_robust, "baseline", "defended"),
|
||||
index=frame.index,
|
||||
dtype="object",
|
||||
)
|
||||
|
||||
return pd.Series("", index=frame.index, dtype="object")
|
||||
|
||||
|
||||
def _prepare_frame(frame: pd.DataFrame, include_non_finished: bool) -> pd.DataFrame:
|
||||
data = frame.copy()
|
||||
if not include_non_finished and "State" in data.columns:
|
||||
data = data[data["State"].astype(str).str.lower() == "finished"].copy()
|
||||
|
||||
data["alpha"] = _extract_alpha(data)
|
||||
data["mode"] = _extract_mode(data)
|
||||
data = data[data["mode"].isin({"baseline", "defended"})]
|
||||
data = data[data["alpha"].notna()]
|
||||
|
||||
_coerce_numeric(
|
||||
data,
|
||||
[
|
||||
"eval/revenue_mean",
|
||||
"eval/reward_mean",
|
||||
"eval/coi_level_mean",
|
||||
"eval/coi_leakage_mean",
|
||||
"eval/volatility_mean",
|
||||
"eval/revenue_std",
|
||||
"eval/reward_std",
|
||||
"eval/margin_mean",
|
||||
"train/agent_prob",
|
||||
"train/alpha_adv",
|
||||
"lambda_coi",
|
||||
"ambiguity_radius",
|
||||
"n_products",
|
||||
],
|
||||
)
|
||||
|
||||
return data.sort_values(["alpha", "mode"]).reset_index(drop=True)
|
||||
|
||||
|
||||
def _summary_by_alpha_mode(frame: pd.DataFrame, metrics: list[str]) -> pd.DataFrame:
|
||||
agg_spec: dict[str, tuple[str, str]] = {"runs": ("mode", "size")}
|
||||
for metric in metrics:
|
||||
safe = _sanitize(metric)
|
||||
agg_spec[f"{safe}_mean"] = (metric, "mean")
|
||||
agg_spec[f"{safe}_std"] = (metric, "std")
|
||||
|
||||
return (
|
||||
frame.groupby(["alpha", "mode"], as_index=False)
|
||||
.agg(**agg_spec)
|
||||
.sort_values(["alpha", "mode"])
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
|
||||
|
||||
def _delta_by_alpha(summary: pd.DataFrame, metrics: list[str]) -> pd.DataFrame:
|
||||
rows: list[dict[str, float]] = []
|
||||
for alpha, alpha_group in summary.groupby("alpha", sort=True):
|
||||
defended = alpha_group[alpha_group["mode"] == "defended"]
|
||||
baseline = alpha_group[alpha_group["mode"] == "baseline"]
|
||||
if defended.empty or baseline.empty:
|
||||
continue
|
||||
|
||||
row: dict[str, float] = {
|
||||
"alpha": float(alpha),
|
||||
"runs_defended": float(defended["runs"].iloc[0]),
|
||||
"runs_baseline": float(baseline["runs"].iloc[0]),
|
||||
}
|
||||
for metric in metrics:
|
||||
safe = _sanitize(metric)
|
||||
defended_value = float(defended[f"{safe}_mean"].iloc[0])
|
||||
baseline_value = float(baseline[f"{safe}_mean"].iloc[0])
|
||||
delta = defended_value - baseline_value
|
||||
row[f"{safe}_defended"] = defended_value
|
||||
row[f"{safe}_baseline"] = baseline_value
|
||||
row[f"{safe}_delta"] = delta
|
||||
row[f"{safe}_delta_pct"] = (
|
||||
np.nan if baseline_value == 0 else 100.0 * delta / baseline_value
|
||||
)
|
||||
rows.append(row)
|
||||
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _summary_by_parameter(
|
||||
frame: pd.DataFrame, parameter: str, metrics: list[str]
|
||||
) -> pd.DataFrame:
|
||||
defended = frame[frame["mode"] == "defended"].copy()
|
||||
defended = defended[defended[parameter].notna()].copy()
|
||||
agg_spec: dict[str, tuple[str, str]] = {"runs": ("mode", "size")}
|
||||
for metric in metrics:
|
||||
safe = _sanitize(metric)
|
||||
agg_spec[f"{safe}_mean"] = (metric, "mean")
|
||||
agg_spec[f"{safe}_std"] = (metric, "std")
|
||||
|
||||
return (
|
||||
defended.groupby(["alpha", parameter], as_index=False)
|
||||
.agg(**agg_spec)
|
||||
.sort_values(["alpha", parameter])
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
|
||||
|
||||
def _save_table(frame: pd.DataFrame, path: Path) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
frame.to_csv(path, index=False)
|
||||
return path
|
||||
|
||||
|
||||
def _save_figure(fig: plt.Figure, pdf_path: Path, export_tikz: bool) -> list[Path]:
|
||||
pdf_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fig.savefig(pdf_path, bbox_inches="tight")
|
||||
written = [pdf_path]
|
||||
|
||||
if export_tikz:
|
||||
if TIKZPLOTLIB is None:
|
||||
raise RuntimeError(
|
||||
"tikzplotlib import failed. Install/upgrade tikzplotlib and matplotlib-compatible dependencies. "
|
||||
f"Original error: {TIKZPLOTLIB_IMPORT_ERROR}"
|
||||
)
|
||||
|
||||
try:
|
||||
from matplotlib.legend import Legend
|
||||
from matplotlib.lines import Line2D
|
||||
|
||||
for legend in fig.findobj(Legend):
|
||||
if not hasattr(legend, "_ncol") and hasattr(legend, "_ncols"):
|
||||
setattr(legend, "_ncol", legend._ncols)
|
||||
if not hasattr(legend, "legendHandles") and hasattr(
|
||||
legend, "legend_handles"
|
||||
):
|
||||
setattr(legend, "legendHandles", legend.legend_handles)
|
||||
|
||||
for line in fig.findobj(Line2D):
|
||||
if hasattr(line, "_us_dashSeq"):
|
||||
continue
|
||||
if not hasattr(line, "_dash_pattern"):
|
||||
continue
|
||||
dash_pattern = getattr(line, "_dash_pattern")
|
||||
if not isinstance(dash_pattern, tuple) or len(dash_pattern) != 2:
|
||||
continue
|
||||
setattr(line, "_us_dashOffset", dash_pattern[0])
|
||||
setattr(line, "_us_dashSeq", dash_pattern[1])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
tikz_path = pdf_path.with_suffix(".tikz.tex")
|
||||
TIKZPLOTLIB.save(str(tikz_path), figure=fig)
|
||||
written.append(tikz_path)
|
||||
|
||||
plt.close(fig)
|
||||
return written
|
||||
|
||||
|
||||
def _plot_alpha_curves(
|
||||
alpha_mode: pd.DataFrame, out_dir: Path, export_tikz: bool
|
||||
) -> list[Path]:
|
||||
fig, axes = plt.subplots(2, 2, figsize=(9.3, 6.4), constrained_layout=True)
|
||||
mode_colors = {"baseline": "#4C72B0", "defended": "#C44E52"}
|
||||
mode_labels = {"baseline": "Baseline", "defended": "Defended"}
|
||||
|
||||
panels = [
|
||||
("eval_revenue_mean", "Mean Episode Revenue", "Revenue"),
|
||||
("eval_reward_mean", "Mean Episode Reward", "Reward"),
|
||||
("eval_coi_leakage_mean", "Mean COI Leakage", "COI Leakage"),
|
||||
("eval_volatility_mean", "Mean Price Volatility", "Volatility"),
|
||||
]
|
||||
|
||||
for ax, (metric_prefix, title, ylabel) in zip(axes.flat, panels):
|
||||
mean_col = f"{metric_prefix}_mean"
|
||||
std_col = f"{metric_prefix}_std"
|
||||
for mode in ("baseline", "defended"):
|
||||
sub = alpha_mode[alpha_mode["mode"] == mode].sort_values("alpha")
|
||||
if sub.empty:
|
||||
continue
|
||||
x = sub["alpha"].to_numpy(dtype=float)
|
||||
y = sub[mean_col].to_numpy(dtype=float)
|
||||
ax.plot(
|
||||
x,
|
||||
y,
|
||||
marker="o",
|
||||
linewidth=1.8,
|
||||
markersize=4,
|
||||
color=mode_colors[mode],
|
||||
label=mode_labels[mode],
|
||||
)
|
||||
sigma = sub[std_col].fillna(0.0).to_numpy(dtype=float)
|
||||
ax.fill_between(
|
||||
x,
|
||||
y - sigma,
|
||||
y + sigma,
|
||||
color=mode_colors[mode],
|
||||
alpha=0.14,
|
||||
linewidth=0,
|
||||
)
|
||||
|
||||
ax.set_title(title)
|
||||
ax.set_xlabel(r"Contamination $\alpha$")
|
||||
ax.set_ylabel(ylabel)
|
||||
ax.set_xticks(sorted(alpha_mode["alpha"].unique()))
|
||||
if metric_prefix in {"eval_revenue_mean", "eval_reward_mean"}:
|
||||
ax.yaxis.set_major_formatter(FuncFormatter(_fmt_thousands))
|
||||
|
||||
handles, labels = axes.flat[0].get_legend_handles_labels()
|
||||
fig.legend(handles, labels, ncol=2, loc="upper center", bbox_to_anchor=(0.5, 1.02))
|
||||
return _save_figure(fig, out_dir / "wandb_alpha_curves.pdf", export_tikz)
|
||||
|
||||
|
||||
def _plot_delta_curves(
|
||||
deltas: pd.DataFrame, out_dir: Path, export_tikz: bool
|
||||
) -> list[Path]:
|
||||
fig, axes = plt.subplots(2, 1, figsize=(8.6, 6.0), constrained_layout=True)
|
||||
deltas = deltas.sort_values("alpha")
|
||||
x = deltas["alpha"].to_numpy(dtype=float)
|
||||
|
||||
top_metrics = [
|
||||
("eval_revenue_mean_delta_pct", "Revenue", "#4C72B0"),
|
||||
("eval_reward_mean_delta_pct", "Reward", "#8172B3"),
|
||||
]
|
||||
for col, label, color in top_metrics:
|
||||
axes[0].plot(
|
||||
x,
|
||||
deltas[col].to_numpy(dtype=float),
|
||||
marker="o",
|
||||
linewidth=1.8,
|
||||
markersize=4,
|
||||
color=color,
|
||||
label=label,
|
||||
)
|
||||
axes[0].axhline(0.0, color="#444444", linewidth=1.0, linestyle="--")
|
||||
axes[0].set_title("Defended Minus Baseline Delta by Contamination")
|
||||
axes[0].set_ylabel("Delta (%)")
|
||||
axes[0].set_xlabel(r"Contamination $\alpha$")
|
||||
axes[0].set_xticks(x)
|
||||
axes[0].legend(loc="lower left")
|
||||
|
||||
bottom_metrics = [
|
||||
("eval_coi_leakage_mean_delta_pct", "COI Leakage", "#55A868"),
|
||||
("eval_volatility_mean_delta_pct", "Volatility", "#DD8452"),
|
||||
]
|
||||
for col, label, color in bottom_metrics:
|
||||
axes[1].plot(
|
||||
x,
|
||||
deltas[col].to_numpy(dtype=float),
|
||||
marker="o",
|
||||
linewidth=1.8,
|
||||
markersize=4,
|
||||
color=color,
|
||||
label=label,
|
||||
)
|
||||
axes[1].axhline(0.0, color="#444444", linewidth=1.0, linestyle="--")
|
||||
axes[1].set_ylabel("Delta (%)")
|
||||
axes[1].set_xlabel(r"Contamination $\alpha$")
|
||||
axes[1].set_xticks(x)
|
||||
axes[1].legend(loc="lower left")
|
||||
|
||||
return _save_figure(fig, out_dir / "wandb_delta_curves.pdf", export_tikz)
|
||||
|
||||
|
||||
def _plot_tradeoff_scatter(
|
||||
deltas: pd.DataFrame, out_dir: Path, export_tikz: bool
|
||||
) -> list[Path]:
|
||||
fig, ax = plt.subplots(figsize=(6.4, 5.2), constrained_layout=True)
|
||||
data = deltas.sort_values("alpha")
|
||||
x = data["eval_coi_leakage_mean_delta_pct"].to_numpy(dtype=float)
|
||||
y = data["eval_revenue_mean_delta_pct"].to_numpy(dtype=float)
|
||||
alphas = data["alpha"].to_numpy(dtype=float)
|
||||
|
||||
scatter = ax.scatter(
|
||||
x,
|
||||
y,
|
||||
c=alphas,
|
||||
cmap="viridis",
|
||||
s=72,
|
||||
edgecolor="#222222",
|
||||
linewidth=0.5,
|
||||
)
|
||||
for x_i, y_i, alpha in zip(x, y, alphas):
|
||||
ax.annotate(
|
||||
rf"$\alpha={alpha:.2f}$",
|
||||
(x_i, y_i),
|
||||
textcoords="offset points",
|
||||
xytext=(5, 4),
|
||||
fontsize=8,
|
||||
)
|
||||
|
||||
ax.axhline(0.0, color="#555555", linewidth=1.0, linestyle="--")
|
||||
ax.axvline(0.0, color="#555555", linewidth=1.0, linestyle="--")
|
||||
ax.set_xlabel("COI Leakage Delta (%)")
|
||||
ax.set_ylabel("Revenue Delta (%)")
|
||||
ax.set_title("Defended Tradeoff Frontier")
|
||||
cbar = fig.colorbar(scatter, ax=ax)
|
||||
cbar.set_label(r"Contamination $\alpha$")
|
||||
|
||||
return _save_figure(fig, out_dir / "wandb_tradeoff_scatter.pdf", export_tikz)
|
||||
|
||||
|
||||
def _plot_reward_robustness(
|
||||
alpha_mode: pd.DataFrame, out_dir: Path, export_tikz: bool
|
||||
) -> list[Path]:
|
||||
fig, ax = plt.subplots(figsize=(7.6, 4.5), constrained_layout=True)
|
||||
mode_colors = {"baseline": "#4C72B0", "defended": "#C44E52"}
|
||||
mode_labels = {"baseline": "Baseline", "defended": "Defended"}
|
||||
|
||||
for mode in ("baseline", "defended"):
|
||||
sub = alpha_mode[alpha_mode["mode"] == mode].sort_values("alpha")
|
||||
x = sub["alpha"].to_numpy(dtype=float)
|
||||
y = sub["eval_reward_mean_std"].fillna(0.0).to_numpy(dtype=float)
|
||||
ax.plot(
|
||||
x,
|
||||
y,
|
||||
marker="o",
|
||||
linewidth=1.8,
|
||||
markersize=4,
|
||||
color=mode_colors[mode],
|
||||
label=mode_labels[mode],
|
||||
)
|
||||
|
||||
ax.set_title("Reward Robustness Across Contamination")
|
||||
ax.set_xlabel(r"Contamination $\alpha$")
|
||||
ax.set_ylabel("Reward Std Across Runs")
|
||||
ax.set_xticks(sorted(alpha_mode["alpha"].unique()))
|
||||
ax.yaxis.set_major_formatter(FuncFormatter(_fmt_thousands))
|
||||
ax.legend(loc="upper left")
|
||||
return _save_figure(fig, out_dir / "wandb_reward_robustness.pdf", export_tikz)
|
||||
|
||||
|
||||
def _plot_parameter_sensitivity(
|
||||
summary: pd.DataFrame,
|
||||
parameter: str,
|
||||
out_name: str,
|
||||
out_dir: Path,
|
||||
export_tikz: bool,
|
||||
) -> list[Path]:
|
||||
fig, axes = plt.subplots(1, 2, figsize=(10.0, 4.2), constrained_layout=True)
|
||||
values = sorted(summary[parameter].dropna().unique())
|
||||
cmap = plt.get_cmap("viridis")
|
||||
colors = [cmap(i) for i in np.linspace(0.1, 0.9, len(values))]
|
||||
|
||||
panels = [
|
||||
("eval_revenue_mean", "Revenue"),
|
||||
("eval_coi_leakage_mean", "COI Leakage"),
|
||||
]
|
||||
for ax, (metric_prefix, ylabel) in zip(axes, panels):
|
||||
mean_col = f"{metric_prefix}_mean"
|
||||
std_col = f"{metric_prefix}_std"
|
||||
for value, color in zip(values, colors):
|
||||
sub = summary[summary[parameter] == value].sort_values("alpha")
|
||||
if sub.empty:
|
||||
continue
|
||||
x = sub["alpha"].to_numpy(dtype=float)
|
||||
y = sub[mean_col].to_numpy(dtype=float)
|
||||
sigma = sub[std_col].fillna(0.0).to_numpy(dtype=float)
|
||||
ax.plot(
|
||||
x,
|
||||
y,
|
||||
marker="o",
|
||||
linewidth=1.6,
|
||||
markersize=3.6,
|
||||
color=color,
|
||||
label=f"{parameter}={value:.2f}",
|
||||
)
|
||||
ax.fill_between(
|
||||
x, y - sigma, y + sigma, color=color, alpha=0.10, linewidth=0
|
||||
)
|
||||
|
||||
ax.set_xlabel(r"Contamination $\alpha$")
|
||||
ax.set_ylabel(ylabel)
|
||||
ax.set_xticks(sorted(summary["alpha"].unique()))
|
||||
if metric_prefix == "eval_revenue_mean":
|
||||
ax.yaxis.set_major_formatter(FuncFormatter(_fmt_thousands))
|
||||
|
||||
axes[0].set_title(f"{parameter} Sensitivity (Defended)")
|
||||
axes[1].set_title("Leakage Side-Effect")
|
||||
handles, labels = axes[0].get_legend_handles_labels()
|
||||
fig.legend(
|
||||
handles,
|
||||
labels,
|
||||
ncol=max(1, len(values) // 2),
|
||||
loc="upper center",
|
||||
bbox_to_anchor=(0.5, 1.06),
|
||||
)
|
||||
|
||||
return _save_figure(fig, out_dir / f"{out_name}.pdf", export_tikz)
|
||||
|
||||
|
||||
def _plot_delta_summary(
|
||||
deltas: pd.DataFrame, out_dir: Path, export_tikz: bool
|
||||
) -> list[Path]:
|
||||
data = deltas.sort_values("alpha")
|
||||
x = np.arange(len(data))
|
||||
labels = [f"{alpha:.1f}" for alpha in data["alpha"].to_numpy(dtype=float)]
|
||||
|
||||
fig, axes = plt.subplots(1, 3, figsize=(11.0, 3.8), constrained_layout=True)
|
||||
panels = [
|
||||
("eval_revenue_mean_delta_pct", "Revenue Delta (%)", "#4C72B0"),
|
||||
("eval_reward_mean_delta_pct", "Reward Delta (%)", "#8172B3"),
|
||||
("eval_coi_leakage_mean_delta_pct", "COI Leakage Delta (%)", "#55A868"),
|
||||
]
|
||||
for ax, (column, title, color) in zip(axes, panels):
|
||||
values = data[column].to_numpy(dtype=float)
|
||||
ax.bar(x, values, color=color, alpha=0.85)
|
||||
ax.axhline(0.0, color="#444444", linewidth=1.0, linestyle="--")
|
||||
ax.set_xticks(x)
|
||||
ax.set_xticklabels(labels)
|
||||
ax.set_xlabel(r"$\alpha$")
|
||||
ax.set_title(title)
|
||||
|
||||
return _save_figure(fig, out_dir / "wandb_delta_summary.pdf", export_tikz)
|
||||
|
||||
|
||||
def build_artifacts(
|
||||
input_path: Path,
|
||||
output_dir: Path,
|
||||
plot_dir: Path,
|
||||
include_non_finished: bool,
|
||||
export_tikz: bool,
|
||||
) -> list[Path]:
|
||||
raw = pd.read_csv(input_path)
|
||||
frame = _prepare_frame(raw, include_non_finished=include_non_finished)
|
||||
|
||||
metrics = [
|
||||
metric
|
||||
for metric in (
|
||||
"eval/revenue_mean",
|
||||
"eval/reward_mean",
|
||||
"eval/coi_level_mean",
|
||||
"eval/coi_leakage_mean",
|
||||
"eval/volatility_mean",
|
||||
"eval/margin_mean",
|
||||
"train/agent_prob",
|
||||
"train/alpha_adv",
|
||||
)
|
||||
if metric in frame.columns
|
||||
]
|
||||
|
||||
alpha_mode = _summary_by_alpha_mode(frame, metrics)
|
||||
deltas = _delta_by_alpha(alpha_mode, metrics)
|
||||
lambda_summary = _summary_by_parameter(frame, "lambda_coi", metrics)
|
||||
radius_summary = _summary_by_parameter(frame, "ambiguity_radius", metrics)
|
||||
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
plot_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
written: list[Path] = []
|
||||
written.append(_save_table(alpha_mode, output_dir / "wandb_alpha_mode_summary.csv"))
|
||||
written.append(_save_table(deltas, output_dir / "wandb_alpha_deltas.csv"))
|
||||
written.append(
|
||||
_save_table(lambda_summary, output_dir / "wandb_lambda_alpha_summary.csv")
|
||||
)
|
||||
written.append(
|
||||
_save_table(radius_summary, output_dir / "wandb_radius_alpha_summary.csv")
|
||||
)
|
||||
|
||||
written.extend(_plot_alpha_curves(alpha_mode, plot_dir, export_tikz))
|
||||
written.extend(_plot_delta_curves(deltas, plot_dir, export_tikz))
|
||||
written.extend(_plot_tradeoff_scatter(deltas, plot_dir, export_tikz))
|
||||
written.extend(_plot_reward_robustness(alpha_mode, plot_dir, export_tikz))
|
||||
written.extend(
|
||||
_plot_parameter_sensitivity(
|
||||
summary=lambda_summary,
|
||||
parameter="lambda_coi",
|
||||
out_name="wandb_lambda_sensitivity",
|
||||
out_dir=plot_dir,
|
||||
export_tikz=export_tikz,
|
||||
)
|
||||
)
|
||||
written.extend(
|
||||
_plot_parameter_sensitivity(
|
||||
summary=radius_summary,
|
||||
parameter="ambiguity_radius",
|
||||
out_name="wandb_radius_sensitivity",
|
||||
out_dir=plot_dir,
|
||||
export_tikz=export_tikz,
|
||||
)
|
||||
)
|
||||
written.extend(_plot_delta_summary(deltas, plot_dir, export_tikz))
|
||||
return written
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate W&B sweep visualizations for PHANTOM results"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--input", type=Path, required=True, help="Path to W&B export CSV"
|
||||
)
|
||||
parser.add_argument("--output-dir", type=Path, default=_default_output_dir())
|
||||
parser.add_argument("--plot-dir", type=Path, default=None)
|
||||
parser.add_argument("--include-non-finished", action="store_true")
|
||||
parser.add_argument(
|
||||
"--export-tikz",
|
||||
action="store_true",
|
||||
help="Export matplotlib figures to TikZ via tikzplotlib",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
_configure_style()
|
||||
plot_dir = (
|
||||
args.plot_dir
|
||||
if args.plot_dir is not None
|
||||
else _default_plot_dir(args.output_dir)
|
||||
)
|
||||
|
||||
outputs = build_artifacts(
|
||||
input_path=args.input,
|
||||
output_dir=args.output_dir,
|
||||
plot_dir=plot_dir,
|
||||
include_non_finished=bool(args.include_non_finished),
|
||||
export_tikz=bool(args.export_tikz),
|
||||
)
|
||||
for path in outputs:
|
||||
print(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
704
paper/src/chapters/figures/results/process_final_sweeps.py
Normal file
704
paper/src/chapters/figures/results/process_final_sweeps.py
Normal file
@@ -0,0 +1,704 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from typing import Any
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def _project_root() -> Path:
|
||||
return Path(__file__).resolve().parents[5]
|
||||
|
||||
|
||||
def _default_bundle_dir() -> Path:
|
||||
base = _project_root() / "engine" / "studies" / "results" / "wandb_sweep_bundles"
|
||||
bundles = sorted(
|
||||
[path for path in base.glob("bundle_*") if path.is_dir()],
|
||||
key=lambda path: path.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
if not bundles:
|
||||
raise FileNotFoundError(f"No sweep bundle directories found in {base}")
|
||||
return bundles[0]
|
||||
|
||||
|
||||
def _default_output_dir() -> Path:
|
||||
return Path(__file__).resolve().parent / "generated" / "final"
|
||||
|
||||
|
||||
def _default_plot_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "plots"
|
||||
|
||||
|
||||
def _git_commit() -> str:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "rev-parse", "HEAD"],
|
||||
check=True,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
cwd=_project_root(),
|
||||
)
|
||||
except Exception:
|
||||
return "unknown"
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def _truthy(value: Any) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if value is None:
|
||||
return False
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _mode_of(row: pd.Series) -> str:
|
||||
mode_hint = str(row.get("study_mode", "")).strip().lower()
|
||||
if mode_hint in {"baseline", "no_robust"}:
|
||||
return "baseline"
|
||||
if mode_hint in {"defended", "robust"}:
|
||||
return "defended"
|
||||
if _truthy(row.get("baseline_mode")) or _truthy(row.get("no_robust")):
|
||||
return "baseline"
|
||||
return "defended"
|
||||
|
||||
|
||||
def _coerce_numeric(frame: pd.DataFrame, columns: list[str]) -> None:
|
||||
for column in columns:
|
||||
if column in frame.columns:
|
||||
frame[column] = pd.to_numeric(frame[column], errors="coerce")
|
||||
|
||||
|
||||
def _configure_style() -> None:
|
||||
plt.rcParams.update(
|
||||
{
|
||||
"font.family": "serif",
|
||||
"font.size": 10,
|
||||
"axes.titlesize": 10,
|
||||
"axes.labelsize": 9,
|
||||
"legend.fontsize": 8,
|
||||
"xtick.labelsize": 8,
|
||||
"ytick.labelsize": 8,
|
||||
"figure.dpi": 220,
|
||||
"savefig.dpi": 320,
|
||||
"axes.spines.top": False,
|
||||
"axes.spines.right": False,
|
||||
"axes.grid": True,
|
||||
"grid.alpha": 0.22,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _load_runs(bundle_dir: Path) -> pd.DataFrame:
|
||||
path = bundle_dir / "runs_finished.csv"
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Missing required file: {path}")
|
||||
frame = pd.read_csv(path)
|
||||
frame["mode"] = frame.apply(_mode_of, axis=1)
|
||||
_coerce_numeric(
|
||||
frame,
|
||||
[
|
||||
"alpha",
|
||||
"n_products",
|
||||
"eval_revenue_mean",
|
||||
"eval_reward_mean",
|
||||
"eval_supra_share_mean",
|
||||
"eval_volatility_mean",
|
||||
"eval_coi_level_mean",
|
||||
"eval_coi_leakage_mean",
|
||||
"objective_score",
|
||||
],
|
||||
)
|
||||
return frame
|
||||
|
||||
|
||||
def _focus_sweep(runs: pd.DataFrame) -> str:
|
||||
coverage = (
|
||||
runs.groupby("sweep_id", as_index=False)
|
||||
.agg(
|
||||
n_alpha=("alpha", lambda s: int(pd.Series(s).dropna().nunique())),
|
||||
max_alpha=("alpha", "max"),
|
||||
run_count=("run_id", "size"),
|
||||
)
|
||||
.sort_values(
|
||||
["n_alpha", "max_alpha", "run_count"], ascending=[False, False, False]
|
||||
)
|
||||
)
|
||||
if coverage.empty:
|
||||
raise ValueError("No sweep rows available in runs_finished.csv")
|
||||
return str(coverage.iloc[0]["sweep_id"])
|
||||
|
||||
|
||||
def _alpha_mode_summary(runs: pd.DataFrame) -> pd.DataFrame:
|
||||
return (
|
||||
runs.groupby(["alpha", "mode"], as_index=False)
|
||||
.agg(
|
||||
runs=("run_id", "size"),
|
||||
revenue_mean=("eval_revenue_mean", "mean"),
|
||||
reward_mean=("eval_reward_mean", "mean"),
|
||||
supra_mean=("eval_supra_share_mean", "mean"),
|
||||
volatility_mean=("eval_volatility_mean", "mean"),
|
||||
coi_leakage_mean=("eval_coi_leakage_mean", "mean"),
|
||||
coi_level_mean=("eval_coi_level_mean", "mean"),
|
||||
)
|
||||
.sort_values(["alpha", "mode"])
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
|
||||
|
||||
def _alpha_deltas(alpha_mode: pd.DataFrame) -> pd.DataFrame:
|
||||
rows: list[dict[str, float]] = []
|
||||
for alpha, group in alpha_mode.groupby("alpha", sort=True):
|
||||
defended = group[group["mode"] == "defended"]
|
||||
baseline = group[group["mode"] == "baseline"]
|
||||
if defended.empty or baseline.empty:
|
||||
continue
|
||||
d_rev = float(defended["revenue_mean"].iloc[0])
|
||||
b_rev = float(baseline["revenue_mean"].iloc[0])
|
||||
d_reward = float(defended["reward_mean"].iloc[0])
|
||||
b_reward = float(baseline["reward_mean"].iloc[0])
|
||||
d_vol = float(defended["volatility_mean"].iloc[0])
|
||||
b_vol = float(baseline["volatility_mean"].iloc[0])
|
||||
d_supra = float(defended["supra_mean"].iloc[0])
|
||||
b_supra = float(baseline["supra_mean"].iloc[0])
|
||||
d_coi_leak = float(defended["coi_leakage_mean"].iloc[0])
|
||||
b_coi_leak = float(baseline["coi_leakage_mean"].iloc[0])
|
||||
rows.append(
|
||||
{
|
||||
"alpha": float(alpha),
|
||||
"revenue_delta": d_rev - b_rev,
|
||||
"revenue_delta_pct": 0.0
|
||||
if b_rev == 0.0
|
||||
else 100.0 * (d_rev - b_rev) / b_rev,
|
||||
"reward_delta": d_reward - b_reward,
|
||||
"reward_delta_pct": 0.0
|
||||
if b_reward == 0.0
|
||||
else 100.0 * (d_reward - b_reward) / b_reward,
|
||||
"volatility_delta": d_vol - b_vol,
|
||||
"supra_delta": d_supra - b_supra,
|
||||
"coi_leakage_delta": d_coi_leak - b_coi_leak,
|
||||
}
|
||||
)
|
||||
return pd.DataFrame(rows).sort_values("alpha").reset_index(drop=True)
|
||||
|
||||
|
||||
def _zone_summary(alpha_deltas: pd.DataFrame) -> pd.DataFrame:
|
||||
if alpha_deltas.empty:
|
||||
return pd.DataFrame()
|
||||
data = alpha_deltas.copy()
|
||||
data["zone"] = np.where(
|
||||
data["alpha"] >= 0.7, "high_alpha_0_7_plus", "low_alpha_below_0_7"
|
||||
)
|
||||
return (
|
||||
data.groupby("zone", as_index=False)
|
||||
.agg(
|
||||
alpha_cells=("alpha", "size"),
|
||||
revenue_delta_pct_mean=("revenue_delta_pct", "mean"),
|
||||
reward_delta_pct_mean=("reward_delta_pct", "mean"),
|
||||
coi_leakage_delta_mean=("coi_leakage_delta", "mean"),
|
||||
volatility_delta_mean=("volatility_delta", "mean"),
|
||||
)
|
||||
.sort_values("zone")
|
||||
)
|
||||
|
||||
|
||||
def _alpha_product_coi_preservation(runs: pd.DataFrame) -> pd.DataFrame:
|
||||
grouped = (
|
||||
runs.groupby(["alpha", "n_products", "mode"], as_index=False)
|
||||
.agg(
|
||||
runs=("run_id", "size"),
|
||||
coi_level_mean=("eval_coi_level_mean", "mean"),
|
||||
)
|
||||
.sort_values(["alpha", "n_products", "mode"])
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
|
||||
rows: list[dict[str, float | int]] = []
|
||||
for (alpha, n_products), group in grouped.groupby(
|
||||
["alpha", "n_products"], sort=True
|
||||
):
|
||||
defended = group[group["mode"] == "defended"]
|
||||
baseline = group[group["mode"] == "baseline"]
|
||||
if defended.empty or baseline.empty:
|
||||
continue
|
||||
|
||||
d_coi = float(defended["coi_level_mean"].iloc[0])
|
||||
b_coi = float(baseline["coi_level_mean"].iloc[0])
|
||||
rows.append(
|
||||
{
|
||||
"alpha": float(alpha),
|
||||
"n_products": float(n_products),
|
||||
"baseline_runs": int(baseline["runs"].iloc[0]),
|
||||
"defended_runs": int(defended["runs"].iloc[0]),
|
||||
"baseline_coi_level_mean": b_coi,
|
||||
"defended_coi_level_mean": d_coi,
|
||||
"coi_preserved": d_coi - b_coi,
|
||||
"coi_preserved_pct": 0.0
|
||||
if b_coi == 0.0
|
||||
else 100.0 * (d_coi - b_coi) / b_coi,
|
||||
}
|
||||
)
|
||||
|
||||
return (
|
||||
pd.DataFrame(rows).sort_values(["alpha", "n_products"]).reset_index(drop=True)
|
||||
)
|
||||
|
||||
|
||||
def _save_plot(fig: plt.Figure, path: Path) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fig.savefig(path, bbox_inches="tight")
|
||||
plt.close(fig)
|
||||
return path
|
||||
|
||||
|
||||
def _smoothed_curve(
|
||||
x: np.ndarray,
|
||||
y: np.ndarray,
|
||||
*,
|
||||
window: int = 5,
|
||||
points: int = 320,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
x_values = np.asarray(x, dtype=float)
|
||||
y_values = np.asarray(y, dtype=float)
|
||||
mask = np.isfinite(x_values) & np.isfinite(y_values)
|
||||
x_values = x_values[mask]
|
||||
y_values = y_values[mask]
|
||||
if x_values.size == 0:
|
||||
return x_values, y_values
|
||||
|
||||
order = np.argsort(x_values)
|
||||
x_values = x_values[order]
|
||||
y_values = y_values[order]
|
||||
|
||||
unique_x = np.unique(x_values)
|
||||
if unique_x.size != x_values.size:
|
||||
dedup = (
|
||||
pd.DataFrame({"x": x_values, "y": y_values})
|
||||
.groupby("x", as_index=False)
|
||||
.agg(y=("y", "mean"))
|
||||
.sort_values("x")
|
||||
)
|
||||
x_values = dedup["x"].to_numpy(dtype=float)
|
||||
y_values = dedup["y"].to_numpy(dtype=float)
|
||||
|
||||
if x_values.size < 3:
|
||||
return x_values, y_values
|
||||
|
||||
win = int(max(3, window))
|
||||
if win % 2 == 0:
|
||||
win += 1
|
||||
if win > x_values.size:
|
||||
win = x_values.size if x_values.size % 2 == 1 else x_values.size - 1
|
||||
if win < 3:
|
||||
return x_values, y_values
|
||||
|
||||
half = win // 2
|
||||
offsets = np.arange(-half, half + 1, dtype=float)
|
||||
sigma = max(win / 3.0, 1.0)
|
||||
kernel = np.exp(-0.5 * (offsets / sigma) ** 2)
|
||||
kernel = kernel / np.sum(kernel)
|
||||
y_padded = np.pad(y_values, (half, half), mode="edge")
|
||||
y_smooth = np.convolve(y_padded, kernel, mode="valid")
|
||||
|
||||
n_points = max(int(points), x_values.size)
|
||||
x_dense = np.linspace(float(np.min(x_values)), float(np.max(x_values)), n_points)
|
||||
y_dense = np.interp(x_dense, x_values, y_smooth)
|
||||
return x_dense, y_dense
|
||||
|
||||
|
||||
def _plot_focus_revenue_by_alpha(alpha_mode: pd.DataFrame, out_path: Path) -> Path:
|
||||
fig, ax = plt.subplots(figsize=(7.8, 4.8), constrained_layout=True)
|
||||
for mode, color, label in (
|
||||
("baseline", "#4C72B0", "Baseline"),
|
||||
("defended", "#C44E52", "Defended"),
|
||||
):
|
||||
sub = alpha_mode[alpha_mode["mode"] == mode].sort_values("alpha")
|
||||
if sub.empty:
|
||||
continue
|
||||
ax.plot(
|
||||
sub["alpha"],
|
||||
sub["revenue_mean"],
|
||||
marker="o",
|
||||
linewidth=1.9,
|
||||
markersize=4,
|
||||
color=color,
|
||||
label=label,
|
||||
)
|
||||
ax.set_xlabel(r"Contamination $\alpha$")
|
||||
ax.set_ylabel("Mean episode revenue")
|
||||
ax.set_title("Final Cohort Revenue Curves")
|
||||
ax.legend(loc="lower left")
|
||||
return _save_plot(fig, out_path)
|
||||
|
||||
|
||||
def _plot_focus_coi_by_alpha(alpha_mode: pd.DataFrame, out_path: Path) -> Path:
|
||||
fig, ax = plt.subplots(figsize=(7.8, 4.8), constrained_layout=True)
|
||||
for mode, color, label in (
|
||||
("baseline", "#4C72B0", "Baseline"),
|
||||
("defended", "#C44E52", "Defended"),
|
||||
):
|
||||
sub = alpha_mode[alpha_mode["mode"] == mode].sort_values("alpha")
|
||||
if sub.empty:
|
||||
continue
|
||||
x_raw = sub["alpha"].to_numpy(dtype=float)
|
||||
y_raw = sub["coi_level_mean"].to_numpy(dtype=float)
|
||||
x_smooth, y_smooth = _smoothed_curve(x_raw, y_raw)
|
||||
ax.plot(
|
||||
x_smooth,
|
||||
y_smooth,
|
||||
linewidth=1.9,
|
||||
color=color,
|
||||
label=label,
|
||||
)
|
||||
ax.scatter(
|
||||
x_raw,
|
||||
y_raw,
|
||||
s=18,
|
||||
color=color,
|
||||
edgecolor="#FFFFFF",
|
||||
linewidth=0.45,
|
||||
zorder=3,
|
||||
)
|
||||
|
||||
paired = alpha_mode.pivot_table(
|
||||
index="alpha",
|
||||
columns="mode",
|
||||
values="coi_level_mean",
|
||||
aggfunc="mean",
|
||||
).sort_index()
|
||||
if {"baseline", "defended"}.issubset(set(paired.columns)):
|
||||
paired = paired.dropna(subset=["baseline", "defended"], how="any")
|
||||
if not paired.empty:
|
||||
x = paired.index.to_numpy(dtype=float)
|
||||
y_baseline = paired["baseline"].to_numpy(dtype=float)
|
||||
y_defended = paired["defended"].to_numpy(dtype=float)
|
||||
x_fill, y_baseline_smooth = _smoothed_curve(x, y_baseline)
|
||||
_, y_defended_smooth = _smoothed_curve(x, y_defended)
|
||||
ax.fill_between(
|
||||
x_fill,
|
||||
y_baseline_smooth,
|
||||
y_defended_smooth,
|
||||
color="#55A868",
|
||||
alpha=0.12,
|
||||
label="Gap",
|
||||
)
|
||||
|
||||
ax.set_xlabel(r"Contamination $\alpha$")
|
||||
ax.set_ylabel("Mean COI level")
|
||||
ax.set_title("Final Cohort COI Curves")
|
||||
ax.legend(loc="lower left")
|
||||
return _save_plot(fig, out_path)
|
||||
|
||||
|
||||
def _plot_focus_coi_preservation_grid(
|
||||
coi_preservation: pd.DataFrame, out_path: Path
|
||||
) -> Path:
|
||||
if coi_preservation.empty:
|
||||
raise ValueError("COI preservation grid requires at least one paired cell")
|
||||
|
||||
alpha_levels = sorted(coi_preservation["alpha"].dropna().unique().tolist())
|
||||
endpoint_targets = (0.0, 1.0)
|
||||
endpoint_levels = [
|
||||
alpha
|
||||
for target in endpoint_targets
|
||||
for alpha in alpha_levels
|
||||
if np.isclose(alpha, target, atol=1e-9)
|
||||
]
|
||||
if len(endpoint_levels) < 2 and alpha_levels:
|
||||
endpoint_levels = [alpha_levels[0], alpha_levels[-1]]
|
||||
endpoint_levels = sorted(set(endpoint_levels))
|
||||
|
||||
data = coi_preservation[coi_preservation["alpha"].isin(endpoint_levels)].copy()
|
||||
if data.empty:
|
||||
raise ValueError(
|
||||
"COI preservation grid has no rows for selected alpha endpoints"
|
||||
)
|
||||
|
||||
alpha_levels = sorted(data["alpha"].dropna().unique().tolist())
|
||||
product_levels = sorted(data["n_products"].dropna().unique().tolist())
|
||||
|
||||
bars = data.pivot_table(
|
||||
index="n_products",
|
||||
columns="alpha",
|
||||
values="coi_preserved",
|
||||
aggfunc="mean",
|
||||
).reindex(index=product_levels, columns=alpha_levels)
|
||||
|
||||
x = np.arange(len(product_levels), dtype=float)
|
||||
n_alpha = max(len(alpha_levels), 1)
|
||||
bar_width = min(0.78 / n_alpha, 0.35)
|
||||
offsets = (np.arange(n_alpha, dtype=float) - (n_alpha - 1) / 2.0) * bar_width
|
||||
palette = ["#4C72B0", "#C44E52", "#55A868", "#8172B3"]
|
||||
|
||||
fig, ax = plt.subplots(figsize=(7.8, 5.0), constrained_layout=True)
|
||||
for idx, alpha in enumerate(alpha_levels):
|
||||
values = bars[alpha].to_numpy(dtype=float)
|
||||
mask = np.isfinite(values)
|
||||
if not np.any(mask):
|
||||
continue
|
||||
xpos = x[mask] + offsets[idx]
|
||||
v = values[mask]
|
||||
ax.bar(
|
||||
xpos,
|
||||
v,
|
||||
width=bar_width * 0.96,
|
||||
color=palette[idx % len(palette)],
|
||||
label=rf"$\alpha={alpha:.1f}$",
|
||||
)
|
||||
for x_i, y_i in zip(xpos, v):
|
||||
ax.text(
|
||||
float(x_i),
|
||||
float(y_i) + (0.035 if y_i >= 0 else -0.035),
|
||||
f"{y_i:+.2f}",
|
||||
ha="center",
|
||||
va="bottom" if y_i >= 0 else "top",
|
||||
fontsize=7,
|
||||
)
|
||||
|
||||
valid = bars.to_numpy(dtype=float)
|
||||
valid = valid[np.isfinite(valid)]
|
||||
max_abs = float(np.max(np.abs(valid))) if valid.size else 1.0
|
||||
max_abs = max(max_abs * 1.22, 0.4)
|
||||
ax.set_ylim(-max_abs, max_abs)
|
||||
|
||||
ax.axhline(0.0, color="#444444", linewidth=1.0, linestyle="--")
|
||||
ax.set_xticks(x)
|
||||
ax.set_xticklabels([f"{int(v)}" for v in product_levels])
|
||||
ax.set_xlabel("Product count")
|
||||
ax.set_ylabel("COI preserved (defended minus baseline)")
|
||||
ax.set_title("COI Preservation by Product Count at $\\alpha=0.0$ vs $\\alpha=1.0$")
|
||||
ax.legend(loc="upper right")
|
||||
ax.grid(axis="y", alpha=0.22)
|
||||
return _save_plot(fig, out_path)
|
||||
|
||||
|
||||
def _plot_focus_revenue_delta(alpha_deltas: pd.DataFrame, out_path: Path) -> Path:
|
||||
fig, ax = plt.subplots(figsize=(7.8, 4.8), constrained_layout=True)
|
||||
x = alpha_deltas["alpha"].to_numpy(dtype=float)
|
||||
y = alpha_deltas["revenue_delta_pct"].to_numpy(dtype=float)
|
||||
ax.plot(x, y, marker="o", linewidth=2.0, markersize=4, color="#C44E52")
|
||||
ax.fill_between(x, y, 0.0, color="#C44E52", alpha=0.12)
|
||||
ax.axhline(0.0, color="#444444", linewidth=1.0, linestyle="--")
|
||||
high = alpha_deltas[alpha_deltas["alpha"] >= 0.7]
|
||||
if not high.empty:
|
||||
best = high.reindex(
|
||||
high["revenue_delta_pct"].abs().sort_values(ascending=False).index
|
||||
).iloc[0]
|
||||
ax.scatter(
|
||||
[best["alpha"]],
|
||||
[best["revenue_delta_pct"]],
|
||||
color="#1f77b4",
|
||||
s=45,
|
||||
zorder=3,
|
||||
)
|
||||
ax.annotate(
|
||||
f"high-alpha peak {best['revenue_delta_pct']:.2f}%",
|
||||
(float(best["alpha"]), float(best["revenue_delta_pct"])),
|
||||
textcoords="offset points",
|
||||
xytext=(6, 6),
|
||||
fontsize=8,
|
||||
)
|
||||
ax.set_xlabel(r"Contamination $\alpha$")
|
||||
ax.set_ylabel("Defended minus baseline revenue (%)")
|
||||
ax.set_title("Revenue Delta by Contamination (Final Cohort)")
|
||||
return _save_plot(fig, out_path)
|
||||
|
||||
|
||||
def _plot_focus_risk_deltas(alpha_deltas: pd.DataFrame, out_path: Path) -> Path:
|
||||
fig, ax = plt.subplots(figsize=(7.8, 4.8), constrained_layout=True)
|
||||
x = alpha_deltas["alpha"].to_numpy(dtype=float)
|
||||
ax.plot(
|
||||
x,
|
||||
alpha_deltas["coi_leakage_delta"].to_numpy(dtype=float),
|
||||
marker="o",
|
||||
linewidth=1.8,
|
||||
markersize=4,
|
||||
color="#55A868",
|
||||
label="COI leakage delta",
|
||||
)
|
||||
ax.plot(
|
||||
x,
|
||||
alpha_deltas["volatility_delta"].to_numpy(dtype=float),
|
||||
marker="s",
|
||||
linewidth=1.8,
|
||||
markersize=3.8,
|
||||
color="#8172B3",
|
||||
label="Volatility delta",
|
||||
)
|
||||
ax.axhline(0.0, color="#444444", linewidth=1.0, linestyle="--")
|
||||
ax.set_xlabel(r"Contamination $\alpha$")
|
||||
ax.set_ylabel("Defended minus baseline")
|
||||
ax.set_title("Leakage and Stability Deltas (Final Cohort)")
|
||||
ax.legend(loc="lower left")
|
||||
return _save_plot(fig, out_path)
|
||||
|
||||
|
||||
def _write_include(path: Path, figure_rel_path: str, width: str) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(f"\\includegraphics[width={width}]{{{figure_rel_path}}}\n")
|
||||
return path
|
||||
|
||||
|
||||
def run(
|
||||
bundle_dir: Path,
|
||||
output_dir: Path,
|
||||
plot_dir: Path,
|
||||
focus_sweep_id: str | None = None,
|
||||
) -> list[Path]:
|
||||
all_runs = _load_runs(bundle_dir)
|
||||
focus_id = str(focus_sweep_id) if focus_sweep_id else _focus_sweep(all_runs)
|
||||
if focus_id not in set(all_runs["sweep_id"].astype(str).unique()):
|
||||
raise ValueError(f"Requested focus sweep_id not found: {focus_id}")
|
||||
focus_runs = all_runs[all_runs["sweep_id"] == focus_id].copy()
|
||||
alpha_mode = _alpha_mode_summary(focus_runs)
|
||||
deltas = _alpha_deltas(alpha_mode)
|
||||
zones = _zone_summary(deltas)
|
||||
coi_preservation = _alpha_product_coi_preservation(focus_runs)
|
||||
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
plot_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
written: list[Path] = []
|
||||
alpha_mode_path = output_dir / "final_focus_alpha_mode_summary.csv"
|
||||
alpha_mode.to_csv(alpha_mode_path, index=False)
|
||||
written.append(alpha_mode_path)
|
||||
|
||||
delta_path = output_dir / "final_focus_alpha_deltas.csv"
|
||||
deltas.to_csv(delta_path, index=False)
|
||||
written.append(delta_path)
|
||||
|
||||
zone_path = output_dir / "final_focus_zone_summary.csv"
|
||||
zones.to_csv(zone_path, index=False)
|
||||
written.append(zone_path)
|
||||
|
||||
coi_grid_path = output_dir / "final_focus_coi_preservation_grid.csv"
|
||||
coi_preservation.to_csv(coi_grid_path, index=False)
|
||||
written.append(coi_grid_path)
|
||||
|
||||
headline = {
|
||||
"bundle": str(bundle_dir),
|
||||
"focus_cohort": "max_alpha_coverage",
|
||||
"focus_sweep_id": focus_id,
|
||||
"focus_run_count": int(len(focus_runs)),
|
||||
"git_commit": _git_commit(),
|
||||
"alpha_cells": int(deltas["alpha"].nunique()) if not deltas.empty else 0,
|
||||
"alpha_min": float(deltas["alpha"].min()) if not deltas.empty else None,
|
||||
"alpha_max": float(deltas["alpha"].max()) if not deltas.empty else None,
|
||||
"mean_revenue_delta_pct": float(deltas["revenue_delta_pct"].mean())
|
||||
if not deltas.empty
|
||||
else None,
|
||||
"mean_reward_delta_pct": float(deltas["reward_delta_pct"].mean())
|
||||
if not deltas.empty
|
||||
else None,
|
||||
"zone_summary": zones.to_dict(orient="records"),
|
||||
}
|
||||
headline_path = output_dir / "final_focus_headline_summary.json"
|
||||
headline_path.write_text(json.dumps(headline, indent=2) + "\n")
|
||||
written.append(headline_path)
|
||||
|
||||
written.append(
|
||||
_plot_focus_revenue_by_alpha(
|
||||
alpha_mode,
|
||||
plot_dir / "final_focus_revenue_by_alpha.pdf",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_plot_focus_coi_by_alpha(
|
||||
alpha_mode,
|
||||
plot_dir / "final_focus_coi_by_alpha.pdf",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_plot_focus_coi_preservation_grid(
|
||||
coi_preservation,
|
||||
plot_dir / "final_focus_coi_preservation_grid.pdf",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_plot_focus_revenue_delta(
|
||||
deltas,
|
||||
plot_dir / "final_focus_revenue_delta.pdf",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_plot_focus_risk_deltas(
|
||||
deltas,
|
||||
plot_dir / "final_focus_risk_deltas.pdf",
|
||||
)
|
||||
)
|
||||
|
||||
include_dir = Path(__file__).resolve().parent / "includes"
|
||||
written.append(
|
||||
_write_include(
|
||||
include_dir / "final_focus_revenue_by_alpha.tex",
|
||||
"chapters/figures/results/generated/final/plots/final_focus_revenue_by_alpha.pdf",
|
||||
"0.98\\linewidth",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_write_include(
|
||||
include_dir / "final_focus_coi_by_alpha.tex",
|
||||
"chapters/figures/results/generated/final/plots/final_focus_coi_by_alpha.pdf",
|
||||
"0.98\\linewidth",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_write_include(
|
||||
include_dir / "final_focus_coi_preservation_grid.tex",
|
||||
"chapters/figures/results/generated/final/plots/final_focus_coi_preservation_grid.pdf",
|
||||
"0.98\\linewidth",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_write_include(
|
||||
include_dir / "final_focus_revenue_delta.tex",
|
||||
"chapters/figures/results/generated/final/plots/final_focus_revenue_delta.pdf",
|
||||
"0.95\\linewidth",
|
||||
)
|
||||
)
|
||||
written.append(
|
||||
_write_include(
|
||||
include_dir / "final_focus_risk_deltas.tex",
|
||||
"chapters/figures/results/generated/final/plots/final_focus_risk_deltas.pdf",
|
||||
"0.95\\linewidth",
|
||||
)
|
||||
)
|
||||
return written
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate final paper figures/tables from the final sweep cohort"
|
||||
)
|
||||
parser.add_argument("--bundle-dir", type=Path, default=_default_bundle_dir())
|
||||
parser.add_argument("--output-dir", type=Path, default=_default_output_dir())
|
||||
parser.add_argument("--plot-dir", type=Path, default=None)
|
||||
parser.add_argument("--focus-sweep-id", type=str, default=None)
|
||||
args = parser.parse_args()
|
||||
|
||||
_configure_style()
|
||||
plot_dir = (
|
||||
args.plot_dir
|
||||
if args.plot_dir is not None
|
||||
else _default_plot_dir(args.output_dir)
|
||||
)
|
||||
outputs = run(
|
||||
bundle_dir=args.bundle_dir,
|
||||
output_dir=args.output_dir,
|
||||
plot_dir=plot_dir,
|
||||
focus_sweep_id=args.focus_sweep_id,
|
||||
)
|
||||
for path in outputs:
|
||||
print(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
454
paper/src/chapters/figures/results/revenue_alpha_analysis.py
Normal file
454
paper/src/chapters/figures/results/revenue_alpha_analysis.py
Normal file
@@ -0,0 +1,454 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import stats
|
||||
|
||||
|
||||
def _project_root() -> Path:
|
||||
return Path(__file__).resolve().parents[5]
|
||||
|
||||
|
||||
def _default_bundle_dir() -> Path:
|
||||
base = _project_root() / "engine" / "studies" / "results" / "wandb_sweep_bundles"
|
||||
bundles = sorted(
|
||||
[path for path in base.glob("bundle_*") if path.is_dir()],
|
||||
key=lambda path: path.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
if not bundles:
|
||||
raise FileNotFoundError(f"No sweep bundle directories found in {base}")
|
||||
return bundles[0]
|
||||
|
||||
|
||||
def _bundle_dir_from_id(bundle_id: str) -> Path:
|
||||
token = str(bundle_id).strip()
|
||||
name = token if token.startswith("bundle_") else f"bundle_{token}"
|
||||
path = (
|
||||
_project_root()
|
||||
/ "engine"
|
||||
/ "studies"
|
||||
/ "results"
|
||||
/ "wandb_sweep_bundles"
|
||||
/ name
|
||||
)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Bundle not found: {path}")
|
||||
return path
|
||||
|
||||
|
||||
def _default_output_dir() -> Path:
|
||||
return Path(__file__).resolve().parent / "generated" / "final"
|
||||
|
||||
|
||||
def _truthy(value: object) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if value is None:
|
||||
return False
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _mode_of(row: pd.Series) -> str:
|
||||
mode_hint = str(row.get("study_mode", "")).strip().lower()
|
||||
if mode_hint in {"baseline", "no_robust"}:
|
||||
return "baseline"
|
||||
if mode_hint in {"defended", "robust"}:
|
||||
return "defended"
|
||||
if _truthy(row.get("baseline_mode")) or _truthy(row.get("no_robust")):
|
||||
return "baseline"
|
||||
return "defended"
|
||||
|
||||
|
||||
def _coerce_numeric(frame: pd.DataFrame, columns: Iterable[str]) -> None:
|
||||
for column in columns:
|
||||
if column in frame.columns:
|
||||
frame[column] = pd.to_numeric(frame[column], errors="coerce")
|
||||
|
||||
|
||||
def _load_runs(bundle_dir: Path) -> pd.DataFrame:
|
||||
path = bundle_dir / "runs_finished.csv"
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Missing required file: {path}")
|
||||
frame = pd.read_csv(path)
|
||||
frame["mode"] = frame.apply(_mode_of, axis=1)
|
||||
_coerce_numeric(
|
||||
frame,
|
||||
[
|
||||
"alpha",
|
||||
"n_products",
|
||||
"eta_ux",
|
||||
"lambda_coi",
|
||||
"eval_revenue_mean",
|
||||
],
|
||||
)
|
||||
frame = frame[frame["mode"].isin({"baseline", "defended"})].copy()
|
||||
return frame
|
||||
|
||||
|
||||
def _get_git_commit() -> str:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "rev-parse", "HEAD"],
|
||||
check=True,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
cwd=_project_root(),
|
||||
)
|
||||
except Exception:
|
||||
return "unknown"
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def _apply_filters(frame: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
|
||||
data = frame.copy()
|
||||
if args.sweep_id:
|
||||
allowed = {str(value) for value in args.sweep_id}
|
||||
data = data[data["sweep_id"].astype(str).isin(allowed)]
|
||||
if args.mode != "all":
|
||||
data = data[data["mode"] == args.mode]
|
||||
if args.n_products is not None:
|
||||
data = data[data["n_products"] == float(args.n_products)]
|
||||
if args.eta_ux is not None:
|
||||
data = data[data["eta_ux"] == float(args.eta_ux)]
|
||||
if args.lambda_coi is not None:
|
||||
data = data[data["lambda_coi"] == float(args.lambda_coi)]
|
||||
data = data[data["alpha"].notna() & data["eval_revenue_mean"].notna()]
|
||||
data = data[data["alpha"] >= float(args.alpha_min)]
|
||||
data = data[data["alpha"] <= float(args.alpha_max)]
|
||||
return data.reset_index(drop=True)
|
||||
|
||||
|
||||
def _design_matrix(
|
||||
frame: pd.DataFrame,
|
||||
*,
|
||||
include_sweep_fixed_effects: bool,
|
||||
) -> tuple[np.ndarray, np.ndarray, list[str]]:
|
||||
y = frame["eval_revenue_mean"].to_numpy(dtype=float)
|
||||
x_alpha = frame["alpha"].to_numpy(dtype=float)
|
||||
columns = ["intercept", "alpha"]
|
||||
blocks = [np.ones_like(x_alpha), x_alpha]
|
||||
if include_sweep_fixed_effects:
|
||||
dummies = pd.get_dummies(
|
||||
frame["sweep_id"].astype(str), prefix="sweep", drop_first=True
|
||||
)
|
||||
if not dummies.empty:
|
||||
blocks.append(dummies.to_numpy(dtype=float).T)
|
||||
columns.extend(dummies.columns.tolist())
|
||||
X = np.vstack(blocks).T
|
||||
return X, y, columns
|
||||
|
||||
|
||||
def _covariance_hc1(X: np.ndarray, residuals: np.ndarray) -> np.ndarray:
|
||||
n, k = X.shape
|
||||
xtx_inv = np.linalg.pinv(X.T @ X)
|
||||
xr = X * residuals[:, None]
|
||||
meat = xr.T @ xr
|
||||
scale = float(n) / max(n - k, 1)
|
||||
return scale * (xtx_inv @ meat @ xtx_inv)
|
||||
|
||||
|
||||
def _covariance_cluster(
|
||||
X: np.ndarray, residuals: np.ndarray, groups: pd.Series
|
||||
) -> tuple[np.ndarray, int]:
|
||||
xtx_inv = np.linalg.pinv(X.T @ X)
|
||||
unique = pd.Series(groups).astype(str).dropna().unique().tolist()
|
||||
g = len(unique)
|
||||
n, k = X.shape
|
||||
if g <= 1:
|
||||
return _covariance_hc1(X, residuals), g
|
||||
meat = np.zeros((k, k), dtype=float)
|
||||
for value in unique:
|
||||
mask = pd.Series(groups).astype(str).to_numpy() == value
|
||||
Xg = X[mask]
|
||||
ug = residuals[mask]
|
||||
xu = Xg.T @ ug
|
||||
meat += np.outer(xu, xu)
|
||||
c = (g / (g - 1.0)) * ((n - 1.0) / max(n - k, 1.0))
|
||||
return c * (xtx_inv @ meat @ xtx_inv), g
|
||||
|
||||
|
||||
def _fit_ols(
|
||||
X: np.ndarray,
|
||||
y: np.ndarray,
|
||||
columns: list[str],
|
||||
*,
|
||||
cov_type: str,
|
||||
groups: pd.Series | None = None,
|
||||
) -> dict[str, object]:
|
||||
n, k = X.shape
|
||||
beta, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
|
||||
fitted = X @ beta
|
||||
residuals = y - fitted
|
||||
dof = max(n - k, 1)
|
||||
sse = float(np.sum(residuals**2))
|
||||
y_centered = y - float(np.mean(y))
|
||||
sst = float(np.sum(y_centered**2))
|
||||
r2 = float(1.0 - sse / sst) if sst > 0 else 0.0
|
||||
adj_r2 = float(1.0 - (1.0 - r2) * ((n - 1.0) / max(n - k, 1.0)))
|
||||
|
||||
if cov_type == "iid":
|
||||
sigma2 = sse / dof
|
||||
cov = sigma2 * np.linalg.pinv(X.T @ X)
|
||||
df_t = dof
|
||||
clusters = None
|
||||
elif cov_type == "hc1":
|
||||
cov = _covariance_hc1(X, residuals)
|
||||
df_t = dof
|
||||
clusters = None
|
||||
elif cov_type == "cluster":
|
||||
if groups is None:
|
||||
raise ValueError("groups are required when cov_type='cluster'")
|
||||
cov, clusters = _covariance_cluster(X, residuals, groups)
|
||||
df_t = max(clusters - 1, 1)
|
||||
else:
|
||||
raise ValueError(f"Unsupported cov_type: {cov_type}")
|
||||
|
||||
se = np.sqrt(np.clip(np.diag(cov), 0.0, np.inf))
|
||||
t_stats = np.divide(beta, se, out=np.zeros_like(beta), where=se > 0)
|
||||
p_values = 2.0 * (1.0 - stats.t.cdf(np.abs(t_stats), df=df_t))
|
||||
t_crit = float(stats.t.ppf(0.975, df=df_t))
|
||||
ci_low = beta - t_crit * se
|
||||
ci_high = beta + t_crit * se
|
||||
|
||||
coef_rows = []
|
||||
for idx, name in enumerate(columns):
|
||||
coef_rows.append(
|
||||
{
|
||||
"name": name,
|
||||
"coef": float(beta[idx]),
|
||||
"std_error": float(se[idx]),
|
||||
"t_stat": float(t_stats[idx]),
|
||||
"p_value": float(p_values[idx]),
|
||||
"ci95_low": float(ci_low[idx]),
|
||||
"ci95_high": float(ci_high[idx]),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"n": int(n),
|
||||
"k": int(k),
|
||||
"dof": int(dof),
|
||||
"df_t": int(df_t),
|
||||
"cov_type": cov_type,
|
||||
"clusters": int(clusters) if clusters is not None else None,
|
||||
"r2": r2,
|
||||
"adj_r2": adj_r2,
|
||||
"sse": sse,
|
||||
"coefficients": coef_rows,
|
||||
"residuals": residuals,
|
||||
"fitted": fitted,
|
||||
"beta": beta,
|
||||
}
|
||||
|
||||
|
||||
def _diagnostics(
|
||||
X: np.ndarray, y: np.ndarray, fit: dict[str, object]
|
||||
) -> dict[str, object]:
|
||||
residuals = np.asarray(fit["residuals"], dtype=float)
|
||||
n, k = X.shape
|
||||
if residuals.size < 8:
|
||||
normality = {"test": "jarque_bera", "available": False}
|
||||
else:
|
||||
jb_stat, jb_p = stats.jarque_bera(residuals)
|
||||
normality = {
|
||||
"test": "jarque_bera",
|
||||
"available": True,
|
||||
"statistic": float(jb_stat),
|
||||
"p_value": float(jb_p),
|
||||
}
|
||||
|
||||
if k <= 1:
|
||||
hetero = {"test": "breusch_pagan", "available": False}
|
||||
else:
|
||||
u2 = residuals**2
|
||||
aux = _fit_ols(X, u2, [f"x{i}" for i in range(k)], cov_type="iid")
|
||||
lm = float(len(u2) * float(aux["r2"]))
|
||||
df_bp = k - 1
|
||||
p_bp = float(1.0 - stats.chi2.cdf(lm, df_bp))
|
||||
hetero = {
|
||||
"test": "breusch_pagan",
|
||||
"available": True,
|
||||
"lm_stat": lm,
|
||||
"df": int(df_bp),
|
||||
"p_value": p_bp,
|
||||
}
|
||||
|
||||
xtx_inv = np.linalg.pinv(X.T @ X)
|
||||
leverages = np.sum((X @ xtx_inv) * X, axis=1)
|
||||
mse = float(np.sum(residuals**2) / max(n - k, 1))
|
||||
if mse <= 0:
|
||||
cooks = np.zeros(n, dtype=float)
|
||||
else:
|
||||
denom = np.clip((1.0 - leverages) ** 2, 1e-10, np.inf)
|
||||
cooks = ((residuals**2) / (k * mse)) * (leverages / denom)
|
||||
|
||||
return {
|
||||
"normality": normality,
|
||||
"heteroskedasticity": hetero,
|
||||
"influence": {
|
||||
"max_leverage": float(np.max(leverages)) if leverages.size else 0.0,
|
||||
"mean_leverage": float(np.mean(leverages)) if leverages.size else 0.0,
|
||||
"high_leverage_threshold": float(2.0 * k / max(n, 1)),
|
||||
"high_leverage_count": int(np.sum(leverages > (2.0 * k / max(n, 1)))),
|
||||
"max_cooks_distance": float(np.max(cooks)) if cooks.size else 0.0,
|
||||
"high_cooks_threshold": float(4.0 / max(n, 1)),
|
||||
"high_cooks_count": int(np.sum(cooks > (4.0 / max(n, 1)))),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: argparse.Namespace) -> list[Path]:
|
||||
output_dir = Path(args.output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
runs = _load_runs(Path(args.bundle_dir))
|
||||
filtered = _apply_filters(runs, args)
|
||||
if len(filtered) < 3:
|
||||
raise ValueError("Filtered cohort must contain at least 3 rows")
|
||||
if filtered["alpha"].nunique() < 2:
|
||||
raise ValueError("Filtered cohort must contain at least 2 unique alpha values")
|
||||
|
||||
filtered_csv = output_dir / "revenue_alpha_filtered.csv"
|
||||
filtered.to_csv(filtered_csv, index=False)
|
||||
|
||||
sample_accounting = {
|
||||
"bundle_dir": str(Path(args.bundle_dir)),
|
||||
"git_commit": _get_git_commit(),
|
||||
"cohort_name": str(args.cohort_name),
|
||||
"filters": {
|
||||
"sweep_id": args.sweep_id,
|
||||
"mode": args.mode,
|
||||
"n_products": args.n_products,
|
||||
"eta_ux": args.eta_ux,
|
||||
"lambda_coi": args.lambda_coi,
|
||||
"alpha_min": args.alpha_min,
|
||||
"alpha_max": args.alpha_max,
|
||||
},
|
||||
"n_rows": int(len(filtered)),
|
||||
"n_sweeps": int(filtered["sweep_id"].nunique()),
|
||||
"alpha_unique": sorted(
|
||||
float(v) for v in filtered["alpha"].dropna().unique().tolist()
|
||||
),
|
||||
"rows_by_sweep": filtered.groupby("sweep_id").size().astype(int).to_dict(),
|
||||
"rows_by_mode": filtered.groupby("mode").size().astype(int).to_dict(),
|
||||
}
|
||||
sample_path = output_dir / "revenue_alpha_sample_accounting.json"
|
||||
sample_path.write_text(json.dumps(sample_accounting, indent=2) + "\n")
|
||||
|
||||
X_simple, y, cols_simple = _design_matrix(
|
||||
filtered, include_sweep_fixed_effects=False
|
||||
)
|
||||
fit_simple = _fit_ols(X_simple, y, cols_simple, cov_type="iid")
|
||||
simple_path = output_dir / "revenue_alpha_simple_ols.json"
|
||||
simple_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
k: v
|
||||
for k, v in fit_simple.items()
|
||||
if k not in {"residuals", "fitted", "beta"}
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
|
||||
X_fe, y_fe, cols_fe = _design_matrix(filtered, include_sweep_fixed_effects=True)
|
||||
cov_type = "cluster" if filtered["sweep_id"].nunique() > 1 else "hc1"
|
||||
fit_fe = _fit_ols(
|
||||
X_fe, y_fe, cols_fe, cov_type=cov_type, groups=filtered["sweep_id"]
|
||||
)
|
||||
fe_path = output_dir / "revenue_alpha_fixed_effects.json"
|
||||
fe_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
k: v
|
||||
for k, v in fit_fe.items()
|
||||
if k not in {"residuals", "fitted", "beta"}
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
|
||||
per_sweep_rows: list[dict[str, float | str | int]] = []
|
||||
for sweep_id, group in filtered.groupby("sweep_id"):
|
||||
if len(group) < 3 or group["alpha"].nunique() < 2:
|
||||
continue
|
||||
X_sw, y_sw, cols_sw = _design_matrix(group, include_sweep_fixed_effects=False)
|
||||
fit_sw = _fit_ols(X_sw, y_sw, cols_sw, cov_type="hc1")
|
||||
alpha_row = next(
|
||||
row for row in fit_sw["coefficients"] if row["name"] == "alpha"
|
||||
)
|
||||
per_sweep_rows.append(
|
||||
{
|
||||
"sweep_id": str(sweep_id),
|
||||
"n": int(fit_sw["n"]),
|
||||
"alpha_coef": float(alpha_row["coef"]),
|
||||
"alpha_std_error": float(alpha_row["std_error"]),
|
||||
"alpha_t_stat": float(alpha_row["t_stat"]),
|
||||
"alpha_p_value": float(alpha_row["p_value"]),
|
||||
"alpha_ci95_low": float(alpha_row["ci95_low"]),
|
||||
"alpha_ci95_high": float(alpha_row["ci95_high"]),
|
||||
"r2": float(fit_sw["r2"]),
|
||||
}
|
||||
)
|
||||
per_sweep_frame = pd.DataFrame(per_sweep_rows)
|
||||
if not per_sweep_frame.empty:
|
||||
per_sweep_frame = per_sweep_frame.sort_values("sweep_id").reset_index(drop=True)
|
||||
per_sweep_path = output_dir / "revenue_alpha_per_sweep.csv"
|
||||
per_sweep_frame.to_csv(per_sweep_path, index=False)
|
||||
|
||||
fit_for_diagnostics = fit_fe if cov_type == "cluster" else fit_simple
|
||||
X_for_diagnostics = X_fe if cov_type == "cluster" else X_simple
|
||||
diagnostics = _diagnostics(X_for_diagnostics, y, fit_for_diagnostics)
|
||||
diagnostics_path = output_dir / "revenue_alpha_diagnostics.json"
|
||||
diagnostics_path.write_text(json.dumps(diagnostics, indent=2) + "\n")
|
||||
|
||||
return [
|
||||
filtered_csv,
|
||||
sample_path,
|
||||
simple_path,
|
||||
fe_path,
|
||||
per_sweep_path,
|
||||
diagnostics_path,
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Reproducible contamination-vs-revenue analysis from a sweep bundle"
|
||||
)
|
||||
parser.add_argument("--bundle-dir", type=Path, default=None)
|
||||
parser.add_argument("--bundle-id", type=str, default=None)
|
||||
parser.add_argument("--output-dir", type=Path, default=_default_output_dir())
|
||||
parser.add_argument("--cohort-name", type=str, default="custom")
|
||||
parser.add_argument("--sweep-id", action="append", default=[])
|
||||
parser.add_argument(
|
||||
"--mode", choices=["all", "baseline", "defended"], default="all"
|
||||
)
|
||||
parser.add_argument("--n-products", type=float, default=None)
|
||||
parser.add_argument("--eta-ux", type=float, default=None)
|
||||
parser.add_argument("--lambda-coi", type=float, default=None)
|
||||
parser.add_argument("--alpha-min", type=float, default=0.0)
|
||||
parser.add_argument("--alpha-max", type=float, default=1.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.bundle_id:
|
||||
args.bundle_dir = _bundle_dir_from_id(args.bundle_id)
|
||||
elif args.bundle_dir is None:
|
||||
args.bundle_dir = _default_bundle_dir()
|
||||
|
||||
outputs = run(args)
|
||||
for path in outputs:
|
||||
print(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
38
paper/src/chapters/figures/sigmoid_softmax_gap.tex
Normal file
38
paper/src/chapters/figures/sigmoid_softmax_gap.tex
Normal file
@@ -0,0 +1,38 @@
|
||||
\begin{tikzpicture}
|
||||
\begin{axis}[
|
||||
width=8.8cm,
|
||||
height=5.2cm,
|
||||
xmin=-4.6,
|
||||
xmax=4.6,
|
||||
ymin=-0.02,
|
||||
ymax=1.06,
|
||||
axis lines=left,
|
||||
xlabel={$\Delta_H - \Delta_A$},
|
||||
xlabel style={yshift=-1.5pt},
|
||||
ylabel={$f(\tau')$},
|
||||
xtick={-4,-2,0,2,4},
|
||||
ytick={0,0.5,1},
|
||||
tick label style={font=\small},
|
||||
label style={font=\small},
|
||||
line width=0.6pt,
|
||||
clip=false,
|
||||
enlarge x limits=false,
|
||||
]
|
||||
\addplot[
|
||||
thick,
|
||||
domain=-4.6:4.6,
|
||||
samples=201,
|
||||
smooth,
|
||||
] {1/(1+exp(-x))};
|
||||
\draw[dashed, line width=0.45pt, black!38]
|
||||
(axis cs:-2.15,0) -- (axis cs:-2.15,{1/(1+exp(2.15))});
|
||||
\draw[dashed, line width=0.45pt, black!38]
|
||||
(axis cs:2.15,0) -- (axis cs:2.15,{1/(1+exp(-2.15))});
|
||||
\addplot[only marks, mark=*, mark size=2.2pt, forget plot, draw=black!55, fill=black!55]
|
||||
coordinates {(-2.15, {1/(1+exp(2.15))})};
|
||||
\addplot[only marks, mark=*, mark size=2.2pt, forget plot, draw=black, fill=black]
|
||||
coordinates {(2.15, {1/(1+exp(-2.15))})};
|
||||
\node[font=\footnotesize, anchor=south, inner sep=11pt] at (axis cs:-2.15,{1/(1+exp(2.15))}) {$\Delta_H<\Delta_A$};
|
||||
\node[font=\footnotesize, anchor=south, inner sep=6pt] at (axis cs:2.15,{1/(1+exp(-2.15))}) {$\Delta_H>\Delta_A$};
|
||||
\end{axis}
|
||||
\end{tikzpicture}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user