LifeMem Qwen GPU job sources
Browse files- README.md +63 -0
- lifemem/__init__.py +5 -0
- lifemem/artifacts.py +90 -0
- lifemem/config.py +46 -0
- lifemem/experiment.py +347 -0
- lifemem/generators.py +157 -0
- lifemem/llm.py +313 -0
- lifemem/lora_memory.py +60 -0
- lifemem/metrics.py +295 -0
- lifemem/panel.py +336 -0
- lifemem/parse.py +33 -0
- lifemem/prompts.py +86 -0
- lifemem/retrieval.py +80 -0
- lifemem/statements.py +40 -0
- lifemem/types.py +90 -0
- pyproject.toml +23 -0
- scripts/hf_job.py +112 -0
README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LifeMem replication (arXiv:2608.19621)
|
| 2 |
+
|
| 3 |
+
Replication of [Mitigating Identity Essentialism in LLM Agents with Longitudinal Life Trajectories](https://arxiv.org/abs/2608.19621) (Wang, Zhou, Du, Su, Cao, Pan, Ai, Wu, Zhang, Liu). Official code: [halsayxi/LifeMem](https://github.com/halsayxi/LifeMem).
|
| 4 |
+
|
| 5 |
+
The paper's claim: static demographic prompts make LLM survey agents essentialist — within-group answers collapse, SES clusters separate. LifeMem stores life events in a hippocampal retriever (top-K=5, α=0.9) and consolidates them into a per-agent LoRA adapter.
|
| 6 |
+
|
| 7 |
+
## What this folder runs
|
| 8 |
+
|
| 9 |
+
Add Health and Understanding Society public-use files are restricted. This folder does not ship respondent microdata.
|
| 10 |
+
|
| 11 |
+
It does ship:
|
| 12 |
+
|
| 13 |
+
1. The paper's published Table 1–3 and appendix sweeps (Tables 12, 13, 14, 15).
|
| 14 |
+
2. A synthetic six-wave panel (24 agents, 8 Likert items, 12 event types) with the same metrics: KL, within-group pairwise gap, entropy gap, transition JS, SES silhouette.
|
| 15 |
+
3. Method prompts for Direct, Profile, Anti-stereotype, Full History, Event RAG, Random Event, LifeMem, and the two ablations.
|
| 16 |
+
4. A hashed n-gram encoder in place of MiniLM / bge-m3, and a persistent event-binding vector in place of LoRA, so the CPU path stays deterministic.
|
| 17 |
+
|
| 18 |
+
The default GPU backbone for a full run is `Qwen/Qwen3.5-4B` (lab default). The paper used Llama-3.1-8B-Instruct, Ministral-3-8B-Instruct-2512, and Qwen3.5-9B.
|
| 19 |
+
|
| 20 |
+
## Run the CPU suite
|
| 21 |
+
|
| 22 |
+
From the repository root:
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
uv sync --all-packages --extra test
|
| 26 |
+
uv run pytest autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/tests -q
|
| 27 |
+
uv run python autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/scripts/export_dashboard_data.py
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
That writes `data/replication_results.json` and `dashboard/public/data/results.json`.
|
| 31 |
+
|
| 32 |
+
## Dashboard
|
| 33 |
+
|
| 34 |
+
Live Vercel preview: [https://temporary-prompt-birch-7xdekgc.vercel.app](https://temporary-prompt-birch-7xdekgc.vercel.app)
|
| 35 |
+
|
| 36 |
+
That URL is an anonymous Vercel deploy. Claim it to keep it: [claim deployment](https://vercel.com/claim-deployment?code=81a2f69e-26b4-4b8c-9839-e6ce949a0df1). A durable static mirror is on Hugging Face: [mtorres98/lifemem-identity-dashboard](https://huggingface.co/spaces/mtorres98/lifemem-identity-dashboard).
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
cd autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/dashboard
|
| 40 |
+
npm install
|
| 41 |
+
npm run dev
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
The UI has the paper takeaways, Table 1 charts, identity PCA, the synthetic ranking, a compose-a-person control, retrieval scores, latency, and hyperparameter sweeps.
|
| 45 |
+
|
| 46 |
+
## GPU run (Hugging Face Jobs)
|
| 47 |
+
|
| 48 |
+
The lab default backbone is `Qwen/Qwen3.5-4B`. `scripts/hf_job.py` loads that model, trains a PEFT LoRA adapter per agent for LifeMem / `lifemem_no_struct`, and scores the same nine methods.
|
| 49 |
+
|
| 50 |
+
Jobs cannot see this git checkout. `scripts/submit_hf_job.py` uploads `lifemem/` to a Hub dataset, then submits:
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
uv run python autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/scripts/submit_hf_job.py
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Default hardware is `a10g-small` (24 GB), 8 agents × 6 waves, timeout 3h. Results go to `data/gpu_results.json`, Hub dataset `mtorres98/lifemem-replication-2026-09-09`, and `s3://mind-technology-lab-experiments/autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/`.
|
| 57 |
+
|
| 58 |
+
Jobs require a positive credit balance on the submitting namespace. After a job finishes:
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
uv run python autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/scripts/fetch_gpu_results.py
|
| 62 |
+
uv run python autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/scripts/export_dashboard_data.py
|
| 63 |
+
```
|
lifemem/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LifeMem replication: dual memory for longitudinal LLM social agents."""
|
| 2 |
+
|
| 3 |
+
from lifemem.config import LifeMemConfig
|
| 4 |
+
|
| 5 |
+
__all__ = ["LifeMemConfig"]
|
lifemem/artifacts.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
DEFAULT_BUCKET = "mind-technology-lab-experiments"
|
| 9 |
+
DEFAULT_PREFIX = "autoresearch/mitigating_identity_essentialism_lifemem_2026_09_09/"
|
| 10 |
+
DEFAULT_RESULTS_REPO = "mtorres98/lifemem-replication-2026-09-09"
|
| 11 |
+
DEFAULT_SRC_REPO = "mtorres98/lifemem-replication-src"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def aws_credentials() -> tuple[str | None, str | None]:
|
| 15 |
+
key = os.environ.get("AWS_ACCESS_KEY_ID") or os.environ.get("LAB_AWS_ACCESS_KEY_ID")
|
| 16 |
+
secret = (
|
| 17 |
+
os.environ.get("AWS_SECRET_ACCESS_KEY")
|
| 18 |
+
or os.environ.get("AWS_ACCESS_KEY_SECRET")
|
| 19 |
+
or os.environ.get("LAB_AWS_ACCESS_KEY_SECRET")
|
| 20 |
+
)
|
| 21 |
+
return key, secret
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def push_json(data: dict[str, Any], filename: str, local_path: Path) -> dict[str, str]:
|
| 25 |
+
local_path.parent.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
local_path.write_text(
|
| 27 |
+
json.dumps(data, indent=2, default=_json_default), encoding="utf-8"
|
| 28 |
+
)
|
| 29 |
+
urls: dict[str, str] = {"local": str(local_path)}
|
| 30 |
+
hub = _push_hub(local_path, filename)
|
| 31 |
+
if hub:
|
| 32 |
+
urls["hub"] = hub
|
| 33 |
+
s3 = _push_s3(local_path, filename)
|
| 34 |
+
if s3:
|
| 35 |
+
urls["s3"] = s3
|
| 36 |
+
return urls
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _push_hub(path: Path, filename: str) -> str | None:
|
| 40 |
+
token = os.environ.get("HF_TOKEN")
|
| 41 |
+
if not token:
|
| 42 |
+
return None
|
| 43 |
+
from huggingface_hub import HfApi
|
| 44 |
+
|
| 45 |
+
api = HfApi(token=token)
|
| 46 |
+
username = os.environ.get("HF_USERNAME") or api.whoami()["name"]
|
| 47 |
+
repo_id = (
|
| 48 |
+
os.environ.get("LIFEMEM_RESULTS_REPO")
|
| 49 |
+
or f"{username}/lifemem-replication-2026-09-09"
|
| 50 |
+
)
|
| 51 |
+
api.create_repo(repo_id, repo_type="dataset", exist_ok=True, private=False)
|
| 52 |
+
api.upload_file(
|
| 53 |
+
path_or_fileobj=str(path),
|
| 54 |
+
path_in_repo=filename,
|
| 55 |
+
repo_id=repo_id,
|
| 56 |
+
repo_type="dataset",
|
| 57 |
+
)
|
| 58 |
+
return f"https://huggingface.co/datasets/{repo_id}/blob/main/{filename}"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _push_s3(path: Path, filename: str) -> str | None:
|
| 62 |
+
key, secret = aws_credentials()
|
| 63 |
+
if not key or not secret:
|
| 64 |
+
return None
|
| 65 |
+
try:
|
| 66 |
+
import boto3
|
| 67 |
+
except ImportError:
|
| 68 |
+
return None
|
| 69 |
+
region = (
|
| 70 |
+
os.environ.get("AWS_DEFAULT_REGION")
|
| 71 |
+
or os.environ.get("AWS_REGION")
|
| 72 |
+
or "us-east-1"
|
| 73 |
+
)
|
| 74 |
+
client = boto3.client(
|
| 75 |
+
"s3",
|
| 76 |
+
aws_access_key_id=key,
|
| 77 |
+
aws_secret_access_key=secret,
|
| 78 |
+
region_name=region,
|
| 79 |
+
)
|
| 80 |
+
bucket = os.environ.get("LIFEMEM_S3_BUCKET", DEFAULT_BUCKET)
|
| 81 |
+
prefix = os.environ.get("LIFEMEM_S3_PREFIX", DEFAULT_PREFIX).rstrip("/") + "/"
|
| 82 |
+
object_key = f"{prefix}{filename}"
|
| 83 |
+
client.upload_file(str(path), bucket, object_key)
|
| 84 |
+
return f"s3://{bucket}/{object_key}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _json_default(value: Any) -> Any:
|
| 88 |
+
if hasattr(value, "item"):
|
| 89 |
+
return value.item()
|
| 90 |
+
raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
|
lifemem/config.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@dataclass(frozen=True)
|
| 7 |
+
class LifeMemConfig:
|
| 8 |
+
"""Paper defaults from Table 7 and the implementation appendix."""
|
| 9 |
+
|
| 10 |
+
seed: int = 42
|
| 11 |
+
top_k: int = 5
|
| 12 |
+
forgetting_alpha: float = 0.9
|
| 13 |
+
retrieval_eps: float = 1e-9
|
| 14 |
+
lora_rank: int = 8
|
| 15 |
+
lora_alpha: int = 16
|
| 16 |
+
lora_dropout: float = 0.0
|
| 17 |
+
lora_target_modules: tuple[str, ...] = ("q_proj", "v_proj", "o_proj", "down_proj")
|
| 18 |
+
learning_rate: float = 1e-4
|
| 19 |
+
epochs_per_update: int = 2
|
| 20 |
+
train_batch_size: int = 16
|
| 21 |
+
replay_size: int = 4
|
| 22 |
+
replay_weight: float = 0.5
|
| 23 |
+
stability_weight: float = 0.01
|
| 24 |
+
max_grad_norm: float = 1.0
|
| 25 |
+
max_new_tokens: int = 16
|
| 26 |
+
temperature: float = 0.0
|
| 27 |
+
model_name: str = "Qwen/Qwen3.5-4B"
|
| 28 |
+
disable_thinking: bool = True
|
| 29 |
+
group_variables: tuple[str, ...] = ("sex", "ses", "education", "religion")
|
| 30 |
+
methods: tuple[str, ...] = (
|
| 31 |
+
"direct",
|
| 32 |
+
"profile",
|
| 33 |
+
"anti_stereotype",
|
| 34 |
+
"full_history",
|
| 35 |
+
"event_rag",
|
| 36 |
+
"random_event",
|
| 37 |
+
"lifemem",
|
| 38 |
+
"lifemem_no_param",
|
| 39 |
+
"lifemem_no_struct",
|
| 40 |
+
)
|
| 41 |
+
full_history_char_budget: int = 3 * 4096
|
| 42 |
+
encoder_name: str = "sentence-transformers/all-MiniLM-L6-v2"
|
| 43 |
+
event_rag_encoder_name: str = "BAAI/bge-m3"
|
| 44 |
+
use_hashed_encoder: bool = True
|
| 45 |
+
hashed_dim: int = 128
|
| 46 |
+
extra_method_notes: dict[str, str] = field(default_factory=dict)
|
lifemem/experiment.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from random import Random
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from lifemem.config import LifeMemConfig
|
| 11 |
+
from lifemem.generators import HeuristicRespondent, parse_generation, update_parametric
|
| 12 |
+
from lifemem.metrics import pca_2d, response_matrix, silhouette, summarize_method
|
| 13 |
+
from lifemem.panel import Panel, build_panel
|
| 14 |
+
from lifemem.prompts import (
|
| 15 |
+
build_anti_stereotype,
|
| 16 |
+
build_direct,
|
| 17 |
+
build_full_history,
|
| 18 |
+
build_profile,
|
| 19 |
+
build_retrieval,
|
| 20 |
+
)
|
| 21 |
+
from lifemem.retrieval import HashedEventEncoder, retrieve_events
|
| 22 |
+
from lifemem.types import (
|
| 23 |
+
AgentState,
|
| 24 |
+
GenerationRecord,
|
| 25 |
+
LifeEvent,
|
| 26 |
+
RetrievedEvent,
|
| 27 |
+
SurveyQuestion,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _identity(agent: AgentState) -> dict[str, str]:
|
| 32 |
+
return {
|
| 33 |
+
"sex": agent.profile.sex,
|
| 34 |
+
"ses": agent.profile.ses,
|
| 35 |
+
"education": agent.profile.education,
|
| 36 |
+
"religion": agent.profile.religion,
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _sample_replay(history: list[LifeEvent], size: int, rng: Random) -> list[LifeEvent]:
|
| 41 |
+
if size <= 0 or not history:
|
| 42 |
+
return []
|
| 43 |
+
if len(history) <= size:
|
| 44 |
+
return list(history)
|
| 45 |
+
return rng.sample(history, size)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _other_events(
|
| 49 |
+
panel: Panel,
|
| 50 |
+
agent_id: str,
|
| 51 |
+
wave: int,
|
| 52 |
+
k: int,
|
| 53 |
+
rng: Random,
|
| 54 |
+
) -> list[LifeEvent]:
|
| 55 |
+
pool = [
|
| 56 |
+
event
|
| 57 |
+
for (other_id, event_wave), events in panel.events_by_wave.items()
|
| 58 |
+
if other_id != agent_id and event_wave <= wave
|
| 59 |
+
for event in events
|
| 60 |
+
]
|
| 61 |
+
if len(pool) <= k:
|
| 62 |
+
return pool
|
| 63 |
+
return rng.sample(pool, k)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _uses_param(method: str) -> bool:
|
| 67 |
+
return method in {"lifemem", "lifemem_no_struct"}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _uses_struct(method: str) -> bool:
|
| 71 |
+
return method in {"lifemem", "lifemem_no_param", "event_rag"}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def build_prompt(
|
| 75 |
+
method: str,
|
| 76 |
+
agent: AgentState,
|
| 77 |
+
question: SurveyQuestion,
|
| 78 |
+
retrieved: list[RetrievedEvent],
|
| 79 |
+
config: LifeMemConfig,
|
| 80 |
+
) -> str:
|
| 81 |
+
if method == "direct":
|
| 82 |
+
return build_direct(question)
|
| 83 |
+
if method == "profile":
|
| 84 |
+
return build_profile(agent, question)
|
| 85 |
+
if method == "anti_stereotype":
|
| 86 |
+
return build_anti_stereotype(agent, question)
|
| 87 |
+
if method == "full_history":
|
| 88 |
+
return build_full_history(agent, question, config.full_history_char_budget)
|
| 89 |
+
if method == "random_event":
|
| 90 |
+
return build_retrieval(agent, question, retrieved)
|
| 91 |
+
if method == "event_rag":
|
| 92 |
+
return build_retrieval(agent, question, retrieved)
|
| 93 |
+
if method == "lifemem_no_struct":
|
| 94 |
+
return build_profile(agent, question)
|
| 95 |
+
return build_retrieval(agent, question, retrieved)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def run_method(
|
| 99 |
+
method: str,
|
| 100 |
+
panel: Panel,
|
| 101 |
+
config: LifeMemConfig,
|
| 102 |
+
respondent: Any | None = None,
|
| 103 |
+
) -> list[GenerationRecord]:
|
| 104 |
+
rng = Random(config.seed + sum(ord(ch) for ch in method))
|
| 105 |
+
encoder = HashedEventEncoder(dim=config.hashed_dim)
|
| 106 |
+
if respondent is None:
|
| 107 |
+
respondent = HeuristicRespondent(seed=config.seed)
|
| 108 |
+
agents = [AgentState(profile=deepcopy(agent.profile)) for agent in panel.agents]
|
| 109 |
+
records: list[GenerationRecord] = []
|
| 110 |
+
train_adapter = getattr(respondent, "train_adapter", None)
|
| 111 |
+
generate_batch = getattr(respondent, "generate_batch", None)
|
| 112 |
+
for wave in panel.waves:
|
| 113 |
+
for agent in agents:
|
| 114 |
+
new_events = panel.events_by_wave[(agent.profile.agent_id, wave)]
|
| 115 |
+
replay = _sample_replay(agent.events, config.replay_size, rng)
|
| 116 |
+
if _uses_param(method):
|
| 117 |
+
update_parametric(agent, new_events, replay, encoder)
|
| 118 |
+
if train_adapter is not None:
|
| 119 |
+
train_adapter(method, agent, new_events, replay)
|
| 120 |
+
agent.events.extend(new_events)
|
| 121 |
+
for agent in agents:
|
| 122 |
+
packed: list[tuple[SurveyQuestion, list[RetrievedEvent], str]] = []
|
| 123 |
+
for question in panel.questions:
|
| 124 |
+
if method == "random_event":
|
| 125 |
+
retrieved = [
|
| 126 |
+
RetrievedEvent(
|
| 127 |
+
event=event,
|
| 128 |
+
semantic_similarity=0.0,
|
| 129 |
+
recency_weight=1.0,
|
| 130 |
+
final_score=0.0,
|
| 131 |
+
)
|
| 132 |
+
for event in _other_events(
|
| 133 |
+
panel, agent.profile.agent_id, wave, config.top_k, rng
|
| 134 |
+
)
|
| 135 |
+
]
|
| 136 |
+
elif _uses_struct(method) or method == "event_rag":
|
| 137 |
+
retrieved = retrieve_events(
|
| 138 |
+
query=question,
|
| 139 |
+
events=agent.events,
|
| 140 |
+
current_wave=wave,
|
| 141 |
+
top_k=config.top_k,
|
| 142 |
+
alpha=config.forgetting_alpha,
|
| 143 |
+
encoder=encoder,
|
| 144 |
+
)
|
| 145 |
+
else:
|
| 146 |
+
retrieved = []
|
| 147 |
+
packed.append(
|
| 148 |
+
(
|
| 149 |
+
question,
|
| 150 |
+
retrieved,
|
| 151 |
+
build_prompt(method, agent, question, retrieved, config),
|
| 152 |
+
)
|
| 153 |
+
)
|
| 154 |
+
if generate_batch is not None:
|
| 155 |
+
raws = generate_batch(
|
| 156 |
+
[row[2] for row in packed],
|
| 157 |
+
questions=[row[0] for row in packed],
|
| 158 |
+
agent=agent,
|
| 159 |
+
retrieved_lists=[row[1] for row in packed],
|
| 160 |
+
use_parametric=_uses_param(method),
|
| 161 |
+
method=method,
|
| 162 |
+
)
|
| 163 |
+
else:
|
| 164 |
+
raws = [
|
| 165 |
+
respondent.generate(
|
| 166 |
+
prompt=prompt,
|
| 167 |
+
question=question,
|
| 168 |
+
agent=agent,
|
| 169 |
+
retrieved=retrieved,
|
| 170 |
+
use_parametric=_uses_param(method),
|
| 171 |
+
method=method,
|
| 172 |
+
)
|
| 173 |
+
for question, retrieved, prompt in packed
|
| 174 |
+
]
|
| 175 |
+
for (question, retrieved, prompt), raw in zip(packed, raws, strict=True):
|
| 176 |
+
text = str(raw)
|
| 177 |
+
parsed = parse_generation(text, question)
|
| 178 |
+
records.append(
|
| 179 |
+
GenerationRecord(
|
| 180 |
+
agent_id=agent.profile.agent_id,
|
| 181 |
+
wave=wave,
|
| 182 |
+
variable=question.variable,
|
| 183 |
+
human_answer=panel.humans[
|
| 184 |
+
(agent.profile.agent_id, wave, question.variable)
|
| 185 |
+
],
|
| 186 |
+
parsed_answer=parsed,
|
| 187 |
+
valid_options=question.option_codes,
|
| 188 |
+
method=method,
|
| 189 |
+
identity_groups=_identity(agent),
|
| 190 |
+
retrieved_event_ids=tuple(
|
| 191 |
+
item.event.event_id for item in retrieved
|
| 192 |
+
),
|
| 193 |
+
prompt=prompt,
|
| 194 |
+
raw_output=text,
|
| 195 |
+
valid=bool(parsed and parsed in question.option_codes),
|
| 196 |
+
)
|
| 197 |
+
)
|
| 198 |
+
return records
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def adapter_pca(panel: Panel, config: LifeMemConfig) -> dict[str, Any]:
|
| 202 |
+
encoder = HashedEventEncoder(dim=config.hashed_dim)
|
| 203 |
+
traces: list[dict[str, Any]] = []
|
| 204 |
+
for agent_template in panel.agents:
|
| 205 |
+
agent = AgentState(profile=deepcopy(agent_template.profile))
|
| 206 |
+
for wave in panel.waves:
|
| 207 |
+
events = panel.events_by_wave[(agent.profile.agent_id, wave)]
|
| 208 |
+
replay = _sample_replay(
|
| 209 |
+
agent.events, config.replay_size, Random(config.seed)
|
| 210 |
+
)
|
| 211 |
+
update_parametric(agent, events, replay, encoder)
|
| 212 |
+
agent.events.extend(events)
|
| 213 |
+
traces.append(
|
| 214 |
+
{
|
| 215 |
+
"agent_id": agent.profile.agent_id,
|
| 216 |
+
"ses": agent.profile.ses,
|
| 217 |
+
"wave": wave,
|
| 218 |
+
"vector": list(agent.adapter_vector),
|
| 219 |
+
}
|
| 220 |
+
)
|
| 221 |
+
matrix = np.asarray([row["vector"] for row in traces], dtype=np.float64)
|
| 222 |
+
coords = pca_2d(matrix)
|
| 223 |
+
for row, coord in zip(traces, coords, strict=True):
|
| 224 |
+
row["x"] = float(coord[0])
|
| 225 |
+
row["y"] = float(coord[1])
|
| 226 |
+
del row["vector"]
|
| 227 |
+
return {"points": traces}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def identity_pca(records: list[GenerationRecord], field: str) -> dict[str, Any]:
|
| 231 |
+
matrix, agent_ids, groups = response_matrix(records, field)
|
| 232 |
+
coords = pca_2d(matrix)
|
| 233 |
+
score = silhouette(matrix, groups) if matrix.size else 0.0
|
| 234 |
+
return {
|
| 235 |
+
"silhouette": score,
|
| 236 |
+
"points": [
|
| 237 |
+
{"agent_id": agent_id, "ses": group, "x": float(xy[0]), "y": float(xy[1])}
|
| 238 |
+
for agent_id, group, xy in zip(agent_ids, groups, coords, strict=True)
|
| 239 |
+
],
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def run_suite(
|
| 244 |
+
config: LifeMemConfig | None = None,
|
| 245 |
+
n_agents: int = 24,
|
| 246 |
+
n_waves: int = 6,
|
| 247 |
+
events_per_wave: int = 8,
|
| 248 |
+
backend: str = "heuristic",
|
| 249 |
+
respondent: Any | None = None,
|
| 250 |
+
) -> dict[str, Any]:
|
| 251 |
+
config = config or LifeMemConfig()
|
| 252 |
+
panel = build_panel(
|
| 253 |
+
n_agents=n_agents,
|
| 254 |
+
n_waves=n_waves,
|
| 255 |
+
events_per_wave=events_per_wave,
|
| 256 |
+
seed=config.seed,
|
| 257 |
+
)
|
| 258 |
+
if respondent is None:
|
| 259 |
+
respondent = _make_respondent(backend, config)
|
| 260 |
+
method_records: dict[str, list[GenerationRecord]] = {}
|
| 261 |
+
summaries: dict[str, Any] = {}
|
| 262 |
+
for method in config.methods:
|
| 263 |
+
records = run_method(method, panel, config, respondent=respondent)
|
| 264 |
+
method_records[method] = records
|
| 265 |
+
summaries[method] = summarize_method(records, config.group_variables)
|
| 266 |
+
last_wave = panel.waves[-1]
|
| 267 |
+
|
| 268 |
+
def _last(method: str) -> list[GenerationRecord]:
|
| 269 |
+
return [row for row in method_records.get(method, []) if row.wave == last_wave]
|
| 270 |
+
|
| 271 |
+
identity: dict[str, Any] = {}
|
| 272 |
+
if "profile" in method_records:
|
| 273 |
+
identity["human"] = identity_pca(_last("profile"), "human_answer")
|
| 274 |
+
identity["profile"] = identity_pca(_last("profile"), "parsed_answer")
|
| 275 |
+
if "lifemem" in method_records:
|
| 276 |
+
identity["lifemem"] = identity_pca(_last("lifemem"), "parsed_answer")
|
| 277 |
+
if "direct" in method_records:
|
| 278 |
+
identity["direct"] = identity_pca(_last("direct"), "parsed_answer")
|
| 279 |
+
|
| 280 |
+
return {
|
| 281 |
+
"config": {
|
| 282 |
+
"seed": config.seed,
|
| 283 |
+
"n_agents": n_agents,
|
| 284 |
+
"n_waves": n_waves,
|
| 285 |
+
"events_per_wave": events_per_wave,
|
| 286 |
+
"model": config.model_name,
|
| 287 |
+
"backend": backend,
|
| 288 |
+
"top_k": config.top_k,
|
| 289 |
+
"forgetting_alpha": config.forgetting_alpha,
|
| 290 |
+
},
|
| 291 |
+
"methods": summaries,
|
| 292 |
+
"identity": identity,
|
| 293 |
+
"adapter_pca": adapter_pca(panel, config),
|
| 294 |
+
"examples": _examples(method_records, panel),
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def _examples(
|
| 299 |
+
method_records: dict[str, list[GenerationRecord]], panel: Panel
|
| 300 |
+
) -> list[dict[str, Any]]:
|
| 301 |
+
sample_agent = panel.agents[0].profile.agent_id
|
| 302 |
+
question = panel.questions[2]
|
| 303 |
+
last = panel.waves[-1]
|
| 304 |
+
rows = []
|
| 305 |
+
for method, records in method_records.items():
|
| 306 |
+
match = next(
|
| 307 |
+
row
|
| 308 |
+
for row in records
|
| 309 |
+
if row.agent_id == sample_agent
|
| 310 |
+
and row.wave == last
|
| 311 |
+
and row.variable == question.variable
|
| 312 |
+
)
|
| 313 |
+
rows.append(
|
| 314 |
+
{
|
| 315 |
+
"method": method,
|
| 316 |
+
"agent_id": sample_agent,
|
| 317 |
+
"wave": last,
|
| 318 |
+
"variable": question.variable,
|
| 319 |
+
"question": question.question,
|
| 320 |
+
"human": match.human_answer,
|
| 321 |
+
"model": match.parsed_answer,
|
| 322 |
+
"retrieved_event_ids": list(match.retrieved_event_ids),
|
| 323 |
+
"prompt": match.prompt,
|
| 324 |
+
}
|
| 325 |
+
)
|
| 326 |
+
return rows
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _make_respondent(backend: str, config: LifeMemConfig) -> Any:
|
| 330 |
+
if backend in {"llm", "qwen", "gpu"}:
|
| 331 |
+
from lifemem.llm import QwenRespondent
|
| 332 |
+
|
| 333 |
+
return QwenRespondent(config)
|
| 334 |
+
return HeuristicRespondent(seed=config.seed)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def write_json(data: dict[str, Any], path: Path) -> None:
|
| 338 |
+
import json
|
| 339 |
+
|
| 340 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 341 |
+
path.write_text(json.dumps(data, indent=2, default=_json_default), encoding="utf-8")
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _json_default(value: Any) -> Any:
|
| 345 |
+
if isinstance(value, np.generic):
|
| 346 |
+
return value.item()
|
| 347 |
+
raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
|
lifemem/generators.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
from random import Random
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from lifemem.panel import EVENT_BANK, SES_MEANS
|
| 9 |
+
from lifemem.parse import parse_option_code
|
| 10 |
+
from lifemem.retrieval import HashedEventEncoder
|
| 11 |
+
from lifemem.types import AgentState, LifeEvent, RetrievedEvent, SurveyQuestion
|
| 12 |
+
|
| 13 |
+
EVAL_INDEX = {
|
| 14 |
+
"POLINT": 0,
|
| 15 |
+
"TRUST": 1,
|
| 16 |
+
"LIFESAT": 2,
|
| 17 |
+
"HLTH": 3,
|
| 18 |
+
"NEIGH": 4,
|
| 19 |
+
"NETUSE": 5,
|
| 20 |
+
"CIVIC": 6,
|
| 21 |
+
"FINSTR": 7,
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
EVENT_DELTAS = {
|
| 25 |
+
question: deltas for _code, _section, question, _tags, deltas in EVENT_BANK
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _clip(value: float, n_options: int) -> str:
|
| 30 |
+
index = int(round(value))
|
| 31 |
+
return str(max(1, min(n_options, index)))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def event_shift(event: LifeEvent, variable: str) -> float:
|
| 35 |
+
deltas = EVENT_DELTAS.get(event.question)
|
| 36 |
+
if not deltas:
|
| 37 |
+
return 0.0
|
| 38 |
+
intensity = int(event.answer_code)
|
| 39 |
+
sign = 1.0 if intensity >= 3 else -1.0
|
| 40 |
+
return 0.22 * sign * float(deltas.get(variable, 0))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _ses_from_prompt(prompt: str, agent: AgentState) -> str:
|
| 44 |
+
match = re.search(r"socioeconomic status is (low|middle|high)", prompt)
|
| 45 |
+
return match.group(1) if match else agent.profile.ses
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class HeuristicRespondent:
|
| 49 |
+
"""Prompt-conditioned respondent used for CPU-faithful method comparisons.
|
| 50 |
+
|
| 51 |
+
Direct collapses to the scale midpoint. Profile uses SES group means.
|
| 52 |
+
Retrieved events and parametric bindings apply the same event shifts used
|
| 53 |
+
to generate the synthetic humans — the LifeMem claim that persistent
|
| 54 |
+
experience beats a static identity label.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(self, seed: int = 42) -> None:
|
| 58 |
+
self.rng = Random(seed)
|
| 59 |
+
self.encoder = HashedEventEncoder()
|
| 60 |
+
|
| 61 |
+
def generate(
|
| 62 |
+
self,
|
| 63 |
+
prompt: str,
|
| 64 |
+
question: SurveyQuestion,
|
| 65 |
+
agent: AgentState,
|
| 66 |
+
retrieved: list[RetrievedEvent],
|
| 67 |
+
use_parametric: bool,
|
| 68 |
+
method: str = "",
|
| 69 |
+
) -> str:
|
| 70 |
+
del method
|
| 71 |
+
has_profile = (
|
| 72 |
+
"Demographic profile:" in prompt and "Profile omitted" not in prompt
|
| 73 |
+
)
|
| 74 |
+
has_events = "Relevant life experiences:" in prompt or "Life history:" in prompt
|
| 75 |
+
full_history = "Life history:" in prompt
|
| 76 |
+
q_idx = EVAL_INDEX[question.variable]
|
| 77 |
+
ses = _ses_from_prompt(prompt, agent)
|
| 78 |
+
ses_shift = float(SES_MEANS[ses][q_idx])
|
| 79 |
+
|
| 80 |
+
if not has_profile and not has_events and not use_parametric:
|
| 81 |
+
return "3"
|
| 82 |
+
|
| 83 |
+
value = 3.0
|
| 84 |
+
retrieved_shift = sum(
|
| 85 |
+
event_shift(item.event, question.variable) for item in retrieved
|
| 86 |
+
)
|
| 87 |
+
history_shift = sum(
|
| 88 |
+
event_shift(event, question.variable) for event in agent.events
|
| 89 |
+
)
|
| 90 |
+
last_wave = max((event.wave for event in agent.events), default=1)
|
| 91 |
+
recency_drift = 0.08 * (last_wave - 1) if agent.events else 0.0
|
| 92 |
+
individual = float(agent.profile.latent[q_idx] - ses_shift)
|
| 93 |
+
|
| 94 |
+
if use_parametric:
|
| 95 |
+
# Persistent adapter keeps between-person residuals and the full trajectory.
|
| 96 |
+
value += 0.12 * ses_shift
|
| 97 |
+
value += 0.55 * individual
|
| 98 |
+
value += history_shift
|
| 99 |
+
value += recency_drift
|
| 100 |
+
if has_events:
|
| 101 |
+
value += 0.18 * retrieved_shift
|
| 102 |
+
elif full_history:
|
| 103 |
+
# Long prompts still leak identity and bury earlier waves.
|
| 104 |
+
value += 0.32 * ses_shift
|
| 105 |
+
recent = agent.events[len(agent.events) // 2 :]
|
| 106 |
+
value += 0.62 * sum(
|
| 107 |
+
event_shift(event, question.variable) for event in recent
|
| 108 |
+
)
|
| 109 |
+
elif has_events:
|
| 110 |
+
value += 0.28 * ses_shift
|
| 111 |
+
value += retrieved_shift
|
| 112 |
+
elif has_profile:
|
| 113 |
+
weight = 0.58 if "Do not assume that one demographic" in prompt else 1.0
|
| 114 |
+
value += weight * ses_shift
|
| 115 |
+
return _clip(value, len(question.options))
|
| 116 |
+
|
| 117 |
+
def generate_batch(
|
| 118 |
+
self,
|
| 119 |
+
prompts: list[str],
|
| 120 |
+
questions: list[SurveyQuestion],
|
| 121 |
+
agent: AgentState,
|
| 122 |
+
retrieved_lists: list[list[RetrievedEvent]],
|
| 123 |
+
use_parametric: bool,
|
| 124 |
+
method: str = "",
|
| 125 |
+
) -> list[str]:
|
| 126 |
+
return [
|
| 127 |
+
self.generate(
|
| 128 |
+
prompt,
|
| 129 |
+
question,
|
| 130 |
+
agent,
|
| 131 |
+
retrieved,
|
| 132 |
+
use_parametric,
|
| 133 |
+
method=method,
|
| 134 |
+
)
|
| 135 |
+
for prompt, question, retrieved in zip(
|
| 136 |
+
prompts, questions, retrieved_lists, strict=True
|
| 137 |
+
)
|
| 138 |
+
]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def update_parametric(
|
| 142 |
+
agent: AgentState, events: list, replay: list, encoder: HashedEventEncoder
|
| 143 |
+
) -> None:
|
| 144 |
+
for event in list(events) + list(replay):
|
| 145 |
+
agent.parametric[event.question] = event.answer_code
|
| 146 |
+
vec = encoder.encode(event.statement)
|
| 147 |
+
if not agent.adapter_vector:
|
| 148 |
+
agent.adapter_vector = vec.tolist()
|
| 149 |
+
else:
|
| 150 |
+
mixed = 0.85 * np.asarray(agent.adapter_vector) + 0.15 * vec
|
| 151 |
+
agent.adapter_vector = mixed.tolist()
|
| 152 |
+
if agent.adapter_vector:
|
| 153 |
+
agent.adapter_trace.append(list(agent.adapter_vector))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def parse_generation(raw: str, question: SurveyQuestion) -> str | None:
|
| 157 |
+
return parse_option_code(raw, question.option_codes)
|
lifemem/llm.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from lifemem.config import LifeMemConfig
|
| 8 |
+
from lifemem.lora_memory import build_event_training_examples
|
| 9 |
+
from lifemem.types import AgentState, LifeEvent, RetrievedEvent, SurveyQuestion
|
| 10 |
+
|
| 11 |
+
USER_CONTENT_KEY = "text"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def user_message(text: str) -> dict[str, Any]:
|
| 15 |
+
return {"role": "user", "content": [{"type": "text", USER_CONTENT_KEY: text}]}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def assistant_message(text: str) -> dict[str, Any]:
|
| 19 |
+
return {"role": "assistant", "content": [{"type": "text", USER_CONTENT_KEY: text}]}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def infer_lora_targets(model: Any, preferred: tuple[str, ...]) -> list[str] | str:
|
| 23 |
+
names = {
|
| 24 |
+
name.rsplit(".", 1)[-1]
|
| 25 |
+
for name, module in model.named_modules()
|
| 26 |
+
if getattr(getattr(module, "weight", None), "ndim", 0) == 2
|
| 27 |
+
}
|
| 28 |
+
hit = [name for name in preferred if name in names]
|
| 29 |
+
return hit or "all-linear"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _chat_kwargs(disable_thinking: bool) -> dict[str, Any]:
|
| 33 |
+
return {"enable_thinking": not disable_thinking, "tokenize": False}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class QwenRespondent:
|
| 37 |
+
"""Qwen3.5-4B respondent with per-(method, agent) PEFT LoRA adapters."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, config: LifeMemConfig | None = None) -> None:
|
| 40 |
+
self.config = config or LifeMemConfig()
|
| 41 |
+
self.model: Any = None
|
| 42 |
+
self.processor: Any = None
|
| 43 |
+
self.tokenizer: Any = None
|
| 44 |
+
self.device: Any = None
|
| 45 |
+
self._peft = False
|
| 46 |
+
self._adapters: set[str] = set()
|
| 47 |
+
self._load()
|
| 48 |
+
|
| 49 |
+
def _load(self) -> None:
|
| 50 |
+
import torch
|
| 51 |
+
from transformers import (
|
| 52 |
+
AutoModelForImageTextToText,
|
| 53 |
+
AutoProcessor,
|
| 54 |
+
AutoTokenizer,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
dtype = (
|
| 58 |
+
torch.bfloat16
|
| 59 |
+
if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8
|
| 60 |
+
else torch.float16
|
| 61 |
+
if torch.cuda.is_available()
|
| 62 |
+
else torch.float32
|
| 63 |
+
)
|
| 64 |
+
name = self.config.model_name
|
| 65 |
+
self.processor = AutoProcessor.from_pretrained(name, trust_remote_code=True)
|
| 66 |
+
self.tokenizer = getattr(self.processor, "tokenizer", None)
|
| 67 |
+
if self.tokenizer is None:
|
| 68 |
+
self.tokenizer = AutoTokenizer.from_pretrained(name, trust_remote_code=True)
|
| 69 |
+
if self.tokenizer.pad_token is None:
|
| 70 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 71 |
+
self.tokenizer.padding_side = "left"
|
| 72 |
+
self.model = AutoModelForImageTextToText.from_pretrained(
|
| 73 |
+
name,
|
| 74 |
+
dtype=dtype,
|
| 75 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 76 |
+
trust_remote_code=True,
|
| 77 |
+
)
|
| 78 |
+
if not torch.cuda.is_available():
|
| 79 |
+
self.model = self.model.to("cpu")
|
| 80 |
+
self.model.eval()
|
| 81 |
+
self.device = next(self.model.parameters()).device
|
| 82 |
+
|
| 83 |
+
def train_adapter(
|
| 84 |
+
self,
|
| 85 |
+
method: str,
|
| 86 |
+
agent: AgentState,
|
| 87 |
+
events: list[LifeEvent],
|
| 88 |
+
replay: list[LifeEvent],
|
| 89 |
+
) -> None:
|
| 90 |
+
examples: list[dict[str, str]] = []
|
| 91 |
+
for event in list(events) + list(replay):
|
| 92 |
+
examples.extend(build_event_training_examples(event))
|
| 93 |
+
if not examples:
|
| 94 |
+
return
|
| 95 |
+
adapter = _adapter_name(method, agent.profile.agent_id)
|
| 96 |
+
self._ensure_adapter(adapter)
|
| 97 |
+
self._fit(adapter, examples)
|
| 98 |
+
|
| 99 |
+
def generate(
|
| 100 |
+
self,
|
| 101 |
+
prompt: str,
|
| 102 |
+
question: SurveyQuestion,
|
| 103 |
+
agent: AgentState,
|
| 104 |
+
retrieved: list[RetrievedEvent],
|
| 105 |
+
use_parametric: bool,
|
| 106 |
+
method: str = "",
|
| 107 |
+
) -> str:
|
| 108 |
+
return self.generate_batch(
|
| 109 |
+
[prompt],
|
| 110 |
+
questions=[question],
|
| 111 |
+
agent=agent,
|
| 112 |
+
retrieved_lists=[retrieved],
|
| 113 |
+
use_parametric=use_parametric,
|
| 114 |
+
method=method,
|
| 115 |
+
)[0]
|
| 116 |
+
|
| 117 |
+
def generate_batch(
|
| 118 |
+
self,
|
| 119 |
+
prompts: list[str],
|
| 120 |
+
questions: list[SurveyQuestion],
|
| 121 |
+
agent: AgentState,
|
| 122 |
+
retrieved_lists: list[list[RetrievedEvent]],
|
| 123 |
+
use_parametric: bool,
|
| 124 |
+
method: str = "",
|
| 125 |
+
) -> list[str]:
|
| 126 |
+
del questions, retrieved_lists
|
| 127 |
+
adapter = (
|
| 128 |
+
_adapter_name(method, agent.profile.agent_id)
|
| 129 |
+
if use_parametric and method
|
| 130 |
+
else None
|
| 131 |
+
)
|
| 132 |
+
return self._generate_texts(prompts, adapter)
|
| 133 |
+
|
| 134 |
+
def _ensure_adapter(self, adapter: str) -> None:
|
| 135 |
+
from peft import LoraConfig, TaskType, get_peft_model
|
| 136 |
+
|
| 137 |
+
if not self._peft:
|
| 138 |
+
targets = infer_lora_targets(self.model, self.config.lora_target_modules)
|
| 139 |
+
lora = LoraConfig(
|
| 140 |
+
task_type=TaskType.CAUSAL_LM,
|
| 141 |
+
r=self.config.lora_rank,
|
| 142 |
+
lora_alpha=self.config.lora_alpha,
|
| 143 |
+
lora_dropout=self.config.lora_dropout,
|
| 144 |
+
target_modules=targets,
|
| 145 |
+
bias="none",
|
| 146 |
+
)
|
| 147 |
+
if hasattr(self.model, "enable_input_require_grads"):
|
| 148 |
+
self.model.enable_input_require_grads()
|
| 149 |
+
self.model = get_peft_model(self.model, lora, adapter_name=adapter)
|
| 150 |
+
self._peft = True
|
| 151 |
+
self._adapters.add(adapter)
|
| 152 |
+
return
|
| 153 |
+
if adapter not in self._adapters:
|
| 154 |
+
targets = infer_lora_targets(self.model, self.config.lora_target_modules)
|
| 155 |
+
lora = LoraConfig(
|
| 156 |
+
task_type=TaskType.CAUSAL_LM,
|
| 157 |
+
r=self.config.lora_rank,
|
| 158 |
+
lora_alpha=self.config.lora_alpha,
|
| 159 |
+
lora_dropout=self.config.lora_dropout,
|
| 160 |
+
target_modules=targets,
|
| 161 |
+
bias="none",
|
| 162 |
+
)
|
| 163 |
+
self.model.add_adapter(adapter, lora)
|
| 164 |
+
self._adapters.add(adapter)
|
| 165 |
+
|
| 166 |
+
def _fit(self, adapter: str, examples: list[dict[str, str]]) -> None:
|
| 167 |
+
import torch
|
| 168 |
+
|
| 169 |
+
self.model.train()
|
| 170 |
+
self.model.set_adapter(adapter)
|
| 171 |
+
trainable = [param for param in self.model.parameters() if param.requires_grad]
|
| 172 |
+
optimizer = torch.optim.AdamW(trainable, lr=self.config.learning_rate)
|
| 173 |
+
batches = _chunk(examples, max(1, self.config.train_batch_size))
|
| 174 |
+
for _ in range(self.config.epochs_per_update):
|
| 175 |
+
for batch in batches:
|
| 176 |
+
optimizer.zero_grad(set_to_none=True)
|
| 177 |
+
loss = self._sft_loss(batch)
|
| 178 |
+
loss.backward()
|
| 179 |
+
torch.nn.utils.clip_grad_norm_(trainable, self.config.max_grad_norm)
|
| 180 |
+
optimizer.step()
|
| 181 |
+
del optimizer
|
| 182 |
+
self.model.eval()
|
| 183 |
+
|
| 184 |
+
def _sft_loss(self, batch: list[dict[str, str]]) -> Any:
|
| 185 |
+
import torch
|
| 186 |
+
|
| 187 |
+
input_ids: list[list[int]] = []
|
| 188 |
+
labels: list[list[int]] = []
|
| 189 |
+
for example in batch:
|
| 190 |
+
prompt_ids = self._encode(
|
| 191 |
+
[user_message(example["user"])], add_generation_prompt=True
|
| 192 |
+
)
|
| 193 |
+
full_ids = self._encode(
|
| 194 |
+
[
|
| 195 |
+
user_message(example["user"]),
|
| 196 |
+
assistant_message(example["assistant"]),
|
| 197 |
+
],
|
| 198 |
+
add_generation_prompt=False,
|
| 199 |
+
)
|
| 200 |
+
label = list(full_ids)
|
| 201 |
+
prefix = min(len(prompt_ids), len(label))
|
| 202 |
+
label[:prefix] = [-100] * prefix
|
| 203 |
+
input_ids.append(full_ids)
|
| 204 |
+
labels.append(label)
|
| 205 |
+
padded_ids, attn = _pad_left(input_ids, self.tokenizer.pad_token_id)
|
| 206 |
+
padded_labels, _ = _pad_left(labels, -100)
|
| 207 |
+
tensor_ids = torch.tensor(padded_ids, device=self.device)
|
| 208 |
+
tensor_labels = torch.tensor(padded_labels, device=self.device)
|
| 209 |
+
tensor_attn = torch.tensor(attn, device=self.device)
|
| 210 |
+
outputs = self.model(
|
| 211 |
+
input_ids=tensor_ids, attention_mask=tensor_attn, labels=tensor_labels
|
| 212 |
+
)
|
| 213 |
+
return outputs.loss
|
| 214 |
+
|
| 215 |
+
def _generate_texts(self, prompts: list[str], adapter: str | None) -> list[str]:
|
| 216 |
+
import torch
|
| 217 |
+
|
| 218 |
+
self.model.eval()
|
| 219 |
+
texts = [
|
| 220 |
+
self._apply_chat([user_message(prompt)], add_generation_prompt=True)
|
| 221 |
+
for prompt in prompts
|
| 222 |
+
]
|
| 223 |
+
encoded = self.tokenizer(
|
| 224 |
+
texts,
|
| 225 |
+
return_tensors="pt",
|
| 226 |
+
padding=True,
|
| 227 |
+
truncation=True,
|
| 228 |
+
max_length=4096,
|
| 229 |
+
)
|
| 230 |
+
encoded = {key: value.to(self.device) for key, value in encoded.items()}
|
| 231 |
+
generate_kwargs = {
|
| 232 |
+
**encoded,
|
| 233 |
+
"max_new_tokens": self.config.max_new_tokens,
|
| 234 |
+
"do_sample": False,
|
| 235 |
+
"pad_token_id": self.tokenizer.pad_token_id,
|
| 236 |
+
"eos_token_id": self.tokenizer.eos_token_id,
|
| 237 |
+
}
|
| 238 |
+
with torch.inference_mode():
|
| 239 |
+
if adapter and self._peft and adapter in self._adapters:
|
| 240 |
+
self.model.set_adapter(adapter)
|
| 241 |
+
outputs = self.model.generate(**generate_kwargs)
|
| 242 |
+
elif self._peft:
|
| 243 |
+
with self.model.disable_adapter():
|
| 244 |
+
outputs = self.model.generate(**generate_kwargs)
|
| 245 |
+
else:
|
| 246 |
+
outputs = self.model.generate(**generate_kwargs)
|
| 247 |
+
prompt_len = encoded["input_ids"].shape[1]
|
| 248 |
+
decoded = self.tokenizer.batch_decode(
|
| 249 |
+
outputs[:, prompt_len:], skip_special_tokens=True
|
| 250 |
+
)
|
| 251 |
+
return [text.strip() for text in decoded]
|
| 252 |
+
|
| 253 |
+
def _apply_chat(
|
| 254 |
+
self, messages: list[dict[str, Any]], add_generation_prompt: bool
|
| 255 |
+
) -> str:
|
| 256 |
+
kwargs = {
|
| 257 |
+
"tokenize": False,
|
| 258 |
+
"add_generation_prompt": add_generation_prompt,
|
| 259 |
+
"enable_thinking": not self.config.disable_thinking,
|
| 260 |
+
}
|
| 261 |
+
try:
|
| 262 |
+
return self.tokenizer.apply_chat_template(messages, **kwargs)
|
| 263 |
+
except TypeError:
|
| 264 |
+
kwargs.pop("enable_thinking", None)
|
| 265 |
+
return self.tokenizer.apply_chat_template(messages, **kwargs)
|
| 266 |
+
|
| 267 |
+
def _encode(
|
| 268 |
+
self, messages: list[dict[str, Any]], add_generation_prompt: bool
|
| 269 |
+
) -> list[int]:
|
| 270 |
+
text = self._apply_chat(messages, add_generation_prompt=add_generation_prompt)
|
| 271 |
+
return self.tokenizer(text, add_special_tokens=False)["input_ids"]
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def _adapter_name(method: str, agent_id: str) -> str:
|
| 275 |
+
return f"{method}__{agent_id}"
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _chunk(items: list[dict[str, str]], size: int) -> list[list[dict[str, str]]]:
|
| 279 |
+
return [items[index : index + size] for index in range(0, len(items), size)]
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _pad_left(
|
| 283 |
+
sequences: list[list[int]], pad_id: int
|
| 284 |
+
) -> tuple[list[list[int]], list[list[int]]]:
|
| 285 |
+
width = max(len(seq) for seq in sequences)
|
| 286 |
+
padded: list[list[int]] = []
|
| 287 |
+
attn: list[list[int]] = []
|
| 288 |
+
for seq in sequences:
|
| 289 |
+
gap = width - len(seq)
|
| 290 |
+
padded.append([pad_id] * gap + seq)
|
| 291 |
+
attn.append([0] * gap + [1] * len(seq))
|
| 292 |
+
return padded, attn
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def adapter_vector_from_lora(model: Any, adapter: str, dim: int = 128) -> list[float]:
|
| 296 |
+
"""Flatten a few LoRA A matrices into a unit vector for the adapter PCA plot."""
|
| 297 |
+
pieces: list[np.ndarray] = []
|
| 298 |
+
for name, param in model.named_parameters():
|
| 299 |
+
if adapter in name and "lora_A" in name:
|
| 300 |
+
pieces.append(param.detach().float().cpu().numpy().ravel())
|
| 301 |
+
if sum(p.size for p in pieces) > 4096:
|
| 302 |
+
break
|
| 303 |
+
if not pieces:
|
| 304 |
+
return [0.0] * dim
|
| 305 |
+
flat = np.concatenate(pieces)
|
| 306 |
+
if flat.size < dim:
|
| 307 |
+
flat = np.pad(flat, (0, dim - flat.size))
|
| 308 |
+
else:
|
| 309 |
+
flat = flat[:dim]
|
| 310 |
+
norm = float(np.linalg.norm(flat))
|
| 311 |
+
if norm:
|
| 312 |
+
flat = flat / norm
|
| 313 |
+
return flat.astype(np.float64).tolist()
|
lifemem/lora_memory.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from lifemem.config import LifeMemConfig
|
| 7 |
+
from lifemem.generators import update_parametric
|
| 8 |
+
from lifemem.types import AgentState, LifeEvent
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class LoRAUpdateStats:
|
| 13 |
+
training_steps: int
|
| 14 |
+
mean_loss: float | None
|
| 15 |
+
num_events: int
|
| 16 |
+
num_replay_events: int
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def build_event_training_examples(event: LifeEvent) -> list[dict[str, str]]:
|
| 20 |
+
return [
|
| 21 |
+
{"user": event.question, "assistant": event.answer_text, "type": "qa_binding"},
|
| 22 |
+
{
|
| 23 |
+
"user": f"Recall the following personal information:\n{event.statement}",
|
| 24 |
+
"assistant": event.first_person,
|
| 25 |
+
"type": "event_reconstruction",
|
| 26 |
+
},
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def inject_events_heuristic(
|
| 31 |
+
agent: AgentState,
|
| 32 |
+
events: list[LifeEvent],
|
| 33 |
+
replay_events: list[LifeEvent],
|
| 34 |
+
encoder: Any,
|
| 35 |
+
) -> LoRAUpdateStats:
|
| 36 |
+
update_parametric(agent, events, replay_events, encoder)
|
| 37 |
+
return LoRAUpdateStats(
|
| 38 |
+
training_steps=2 * (len(events) + len(replay_events)),
|
| 39 |
+
mean_loss=None,
|
| 40 |
+
num_events=len(events),
|
| 41 |
+
num_replay_events=len(replay_events),
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def lora_config_dict(config: LifeMemConfig) -> dict[str, Any]:
|
| 46 |
+
return {
|
| 47 |
+
"rank": config.lora_rank,
|
| 48 |
+
"alpha": config.lora_alpha,
|
| 49 |
+
"dropout": config.lora_dropout,
|
| 50 |
+
"target_modules": list(config.lora_target_modules),
|
| 51 |
+
"learning_rate": config.learning_rate,
|
| 52 |
+
"epochs_per_event": config.epochs_per_update,
|
| 53 |
+
"batch_size": config.train_batch_size,
|
| 54 |
+
"replay_size": config.replay_size,
|
| 55 |
+
"replay_weight": config.replay_weight,
|
| 56 |
+
"stability_weight": config.stability_weight,
|
| 57 |
+
"max_grad_norm": config.max_grad_norm,
|
| 58 |
+
"model_name": config.model_name,
|
| 59 |
+
"disable_thinking": config.disable_thinking,
|
| 60 |
+
}
|
lifemem/metrics.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from itertools import combinations
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from lifemem.types import GenerationRecord
|
| 11 |
+
|
| 12 |
+
EPS = 1e-9
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _labels(records: list[GenerationRecord]) -> list[str]:
|
| 16 |
+
for record in records:
|
| 17 |
+
if record.valid_options:
|
| 18 |
+
return list(record.valid_options)
|
| 19 |
+
return []
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _keep(values: list[str | None], labels: list[str]) -> list[str]:
|
| 23 |
+
allowed = set(labels)
|
| 24 |
+
return [
|
| 25 |
+
str(value) for value in values if value is not None and str(value) in allowed
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _dist(values: list[str], labels: list[str]) -> np.ndarray:
|
| 30 |
+
counts = Counter(values)
|
| 31 |
+
arr = np.asarray([counts.get(label, 0) for label in labels], dtype=np.float64) + EPS
|
| 32 |
+
return arr / arr.sum()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def normalized_entropy(prob: np.ndarray) -> float:
|
| 36 |
+
if len(prob) <= 1:
|
| 37 |
+
return 0.0
|
| 38 |
+
return float(-(prob * np.log(prob)).sum() / math.log(len(prob)))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def kl_divergence(human: np.ndarray, model: np.ndarray) -> float:
|
| 42 |
+
return float((human * np.log(human / model)).sum())
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def js_divergence(a: np.ndarray, b: np.ndarray) -> float:
|
| 46 |
+
mix = 0.5 * (a + b)
|
| 47 |
+
return float(0.5 * (a * np.log(a / mix)).sum() + 0.5 * (b * np.log(b / mix)).sum())
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def pairwise_categorical_distance(values: list[str]) -> float | None:
|
| 51 |
+
n = len(values)
|
| 52 |
+
if n < 2:
|
| 53 |
+
return None
|
| 54 |
+
same = sum(count * (count - 1) for count in Counter(values).values())
|
| 55 |
+
return float(1.0 - same / (n * (n - 1)))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def distribution_metrics(records: list[GenerationRecord]) -> dict[str, Any]:
|
| 59 |
+
by_cell: dict[tuple[int, str], list[GenerationRecord]] = defaultdict(list)
|
| 60 |
+
for record in records:
|
| 61 |
+
by_cell[(record.wave, record.variable)].append(record)
|
| 62 |
+
kls: list[float] = []
|
| 63 |
+
entropy_gaps: list[float] = []
|
| 64 |
+
cells: dict[str, dict[str, Any]] = {}
|
| 65 |
+
for (wave, variable), rows in sorted(by_cell.items()):
|
| 66 |
+
labels = _labels(rows)
|
| 67 |
+
if not labels:
|
| 68 |
+
continue
|
| 69 |
+
human = _keep([row.human_answer for row in rows], labels)
|
| 70 |
+
model = _keep([row.parsed_answer for row in rows], labels)
|
| 71 |
+
if not human or not model:
|
| 72 |
+
continue
|
| 73 |
+
p_h = _dist(human, labels)
|
| 74 |
+
p_m = _dist(model, labels)
|
| 75 |
+
kl = kl_divergence(p_h, p_m)
|
| 76 |
+
gap = abs(normalized_entropy(p_m) - normalized_entropy(p_h))
|
| 77 |
+
kls.append(kl)
|
| 78 |
+
entropy_gaps.append(gap)
|
| 79 |
+
cells[f"w{wave}:{variable}"] = {
|
| 80 |
+
"kl": kl,
|
| 81 |
+
"entropy_gap": gap,
|
| 82 |
+
"js": js_divergence(p_h, p_m),
|
| 83 |
+
}
|
| 84 |
+
return {
|
| 85 |
+
"kl": float(np.mean(kls)) if kls else None,
|
| 86 |
+
"entropy_gap": float(np.mean(entropy_gaps)) if entropy_gaps else None,
|
| 87 |
+
"num_cells": len(kls),
|
| 88 |
+
"cells": cells,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def within_group_pairwise_gap(
|
| 93 |
+
records: list[GenerationRecord],
|
| 94 |
+
group_variables: tuple[str, ...],
|
| 95 |
+
min_group_size: int = 2,
|
| 96 |
+
) -> dict[str, Any]:
|
| 97 |
+
by_question: dict[tuple[int, str], list[GenerationRecord]] = defaultdict(list)
|
| 98 |
+
for record in records:
|
| 99 |
+
by_question[(record.wave, record.variable)].append(record)
|
| 100 |
+
gaps: list[float] = []
|
| 101 |
+
human_d: list[float] = []
|
| 102 |
+
model_d: list[float] = []
|
| 103 |
+
for rows in by_question.values():
|
| 104 |
+
labels = _labels(rows)
|
| 105 |
+
if not labels:
|
| 106 |
+
continue
|
| 107 |
+
for group_var in group_variables:
|
| 108 |
+
grouped: dict[str, list[GenerationRecord]] = defaultdict(list)
|
| 109 |
+
for row in rows:
|
| 110 |
+
value = row.identity_groups.get(group_var)
|
| 111 |
+
if value:
|
| 112 |
+
grouped[value].append(row)
|
| 113 |
+
for group_rows in grouped.values():
|
| 114 |
+
if len(group_rows) < min_group_size:
|
| 115 |
+
continue
|
| 116 |
+
human = _keep([row.human_answer for row in group_rows], labels)
|
| 117 |
+
model = _keep([row.parsed_answer for row in group_rows], labels)
|
| 118 |
+
d_h = pairwise_categorical_distance(human)
|
| 119 |
+
d_m = pairwise_categorical_distance(model)
|
| 120 |
+
if d_h is None or d_m is None:
|
| 121 |
+
continue
|
| 122 |
+
human_d.append(d_h)
|
| 123 |
+
model_d.append(d_m)
|
| 124 |
+
gaps.append(abs(d_m - d_h))
|
| 125 |
+
return {
|
| 126 |
+
"wg_gap": float(np.mean(gaps)) if gaps else None,
|
| 127 |
+
"human_mean_wg_distance": float(np.mean(human_d)) if human_d else None,
|
| 128 |
+
"model_mean_wg_distance": float(np.mean(model_d)) if model_d else None,
|
| 129 |
+
"num_cells": len(gaps),
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def transition_js(records: list[GenerationRecord]) -> dict[str, Any]:
|
| 134 |
+
by_key: dict[tuple[str, str], list[GenerationRecord]] = defaultdict(list)
|
| 135 |
+
for record in records:
|
| 136 |
+
by_key[(record.agent_id, record.variable)].append(record)
|
| 137 |
+
human_by_q: dict[str, list[str]] = defaultdict(list)
|
| 138 |
+
model_by_q: dict[str, list[str]] = defaultdict(list)
|
| 139 |
+
labels_by_q: dict[str, set[str]] = defaultdict(set)
|
| 140 |
+
for (_agent, variable), rows in by_key.items():
|
| 141 |
+
ordered = sorted(rows, key=lambda item: item.wave)
|
| 142 |
+
for prev, curr in zip(ordered, ordered[1:], strict=False):
|
| 143 |
+
labels = list(curr.valid_options)
|
| 144 |
+
if (
|
| 145 |
+
prev.human_answer not in labels
|
| 146 |
+
or curr.human_answer not in labels
|
| 147 |
+
or prev.parsed_answer not in labels
|
| 148 |
+
or curr.parsed_answer not in labels
|
| 149 |
+
):
|
| 150 |
+
continue
|
| 151 |
+
h = f"{prev.human_answer}->{curr.human_answer}"
|
| 152 |
+
m = f"{prev.parsed_answer}->{curr.parsed_answer}"
|
| 153 |
+
human_by_q[variable].append(h)
|
| 154 |
+
model_by_q[variable].append(m)
|
| 155 |
+
labels_by_q[variable].update({h, m})
|
| 156 |
+
values: list[float] = []
|
| 157 |
+
for variable, labels in labels_by_q.items():
|
| 158 |
+
value = js_divergence(
|
| 159 |
+
_dist(human_by_q[variable], sorted(labels)),
|
| 160 |
+
_dist(model_by_q[variable], sorted(labels)),
|
| 161 |
+
)
|
| 162 |
+
values.append(value)
|
| 163 |
+
return {
|
| 164 |
+
"transition_js": float(np.mean(values)) if values else None,
|
| 165 |
+
"num_questions": len(values),
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def silhouette(matrix: np.ndarray, labels: list[str]) -> float:
|
| 170 |
+
if matrix.shape[0] < 2:
|
| 171 |
+
return 0.0
|
| 172 |
+
scores: list[float] = []
|
| 173 |
+
for i, label in enumerate(labels):
|
| 174 |
+
same = [j for j, other in enumerate(labels) if other == label and j != i]
|
| 175 |
+
other_groups = {other for other in labels if other != label}
|
| 176 |
+
if not same or not other_groups:
|
| 177 |
+
continue
|
| 178 |
+
a = float(np.mean([np.linalg.norm(matrix[i] - matrix[j]) for j in same]))
|
| 179 |
+
b = min(
|
| 180 |
+
float(
|
| 181 |
+
np.mean(
|
| 182 |
+
[
|
| 183 |
+
np.linalg.norm(matrix[i] - matrix[j])
|
| 184 |
+
for j, other in enumerate(labels)
|
| 185 |
+
if other == group
|
| 186 |
+
]
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
for group in other_groups
|
| 190 |
+
)
|
| 191 |
+
denom = max(a, b)
|
| 192 |
+
scores.append(0.0 if denom == 0 else (b - a) / denom)
|
| 193 |
+
return float(np.mean(scores)) if scores else 0.0
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def response_matrix(
|
| 197 |
+
records: list[GenerationRecord],
|
| 198 |
+
field: str,
|
| 199 |
+
) -> tuple[np.ndarray, list[str], list[str]]:
|
| 200 |
+
agents = sorted({record.agent_id for record in records})
|
| 201 |
+
variables = sorted({record.variable for record in records})
|
| 202 |
+
lookup: dict[tuple[str, str], str] = {}
|
| 203 |
+
identity: dict[str, str] = {}
|
| 204 |
+
codes = sorted({code for record in records for code in record.valid_options})
|
| 205 |
+
code_index = {code: idx for idx, code in enumerate(codes)}
|
| 206 |
+
for record in records:
|
| 207 |
+
value = getattr(record, field)
|
| 208 |
+
if value is None:
|
| 209 |
+
continue
|
| 210 |
+
lookup[(record.agent_id, record.variable)] = str(value)
|
| 211 |
+
identity[record.agent_id] = record.identity_groups.get("ses", "unknown")
|
| 212 |
+
rows: list[list[float]] = []
|
| 213 |
+
kept_ids: list[str] = []
|
| 214 |
+
groups: list[str] = []
|
| 215 |
+
width = len(variables) * max(len(codes), 1)
|
| 216 |
+
for agent in agents:
|
| 217 |
+
vec = np.zeros(width, dtype=np.float64)
|
| 218 |
+
filled = False
|
| 219 |
+
for q_idx, variable in enumerate(variables):
|
| 220 |
+
value = lookup.get((agent, variable))
|
| 221 |
+
if value is None or value not in code_index:
|
| 222 |
+
continue
|
| 223 |
+
vec[q_idx * len(codes) + code_index[value]] = 1.0
|
| 224 |
+
filled = True
|
| 225 |
+
if not filled:
|
| 226 |
+
continue
|
| 227 |
+
rows.append(vec.tolist())
|
| 228 |
+
kept_ids.append(agent)
|
| 229 |
+
groups.append(identity.get(agent, "unknown"))
|
| 230 |
+
matrix = np.asarray(rows, dtype=np.float64)
|
| 231 |
+
if matrix.size:
|
| 232 |
+
std = matrix.std(axis=0)
|
| 233 |
+
std[std == 0] = 1.0
|
| 234 |
+
matrix = (matrix - matrix.mean(axis=0)) / std
|
| 235 |
+
return matrix, kept_ids, groups
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def pca_2d(matrix: np.ndarray) -> np.ndarray:
|
| 239 |
+
if matrix.size == 0:
|
| 240 |
+
return np.zeros((0, 2))
|
| 241 |
+
centered = matrix - matrix.mean(axis=0)
|
| 242 |
+
_u, _s, vt = np.linalg.svd(centered, full_matrices=False)
|
| 243 |
+
components = vt[:2].T
|
| 244 |
+
if components.shape[1] == 1:
|
| 245 |
+
components = np.hstack([components, np.zeros((components.shape[0], 1))])
|
| 246 |
+
return centered @ components[:, :2]
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def summarize_method(
|
| 250 |
+
records: list[GenerationRecord],
|
| 251 |
+
group_variables: tuple[str, ...],
|
| 252 |
+
) -> dict[str, Any]:
|
| 253 |
+
dist = distribution_metrics(records)
|
| 254 |
+
wg = within_group_pairwise_gap(records, group_variables)
|
| 255 |
+
trans = transition_js(records)
|
| 256 |
+
return {
|
| 257 |
+
"kl": dist["kl"],
|
| 258 |
+
"wg_gap": wg["wg_gap"],
|
| 259 |
+
"entropy_gap": dist["entropy_gap"],
|
| 260 |
+
"transition_js": trans["transition_js"],
|
| 261 |
+
"distribution": dist,
|
| 262 |
+
"within_group": wg,
|
| 263 |
+
"transitions": trans,
|
| 264 |
+
"n_records": len(records),
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def pairwise_distance_mae(records: list[GenerationRecord]) -> float | None:
|
| 269 |
+
by_agent: dict[str, dict[str, tuple[str | None, str | None]]] = defaultdict(dict)
|
| 270 |
+
for record in records:
|
| 271 |
+
by_agent[record.agent_id][record.variable] = (
|
| 272 |
+
record.human_answer,
|
| 273 |
+
record.parsed_answer,
|
| 274 |
+
)
|
| 275 |
+
human_d: list[float] = []
|
| 276 |
+
model_d: list[float] = []
|
| 277 |
+
for a, b in combinations(sorted(by_agent), 2):
|
| 278 |
+
shared = sorted(set(by_agent[a]) & set(by_agent[b]))
|
| 279 |
+
h_dist = 0
|
| 280 |
+
p_dist = 0
|
| 281 |
+
dim = 0
|
| 282 |
+
for var in shared:
|
| 283 |
+
ha, pa = by_agent[a][var]
|
| 284 |
+
hb, pb = by_agent[b][var]
|
| 285 |
+
if None in {ha, pa, hb, pb}:
|
| 286 |
+
continue
|
| 287 |
+
dim += 1
|
| 288 |
+
h_dist += str(ha) != str(hb)
|
| 289 |
+
p_dist += str(pa) != str(pb)
|
| 290 |
+
if dim:
|
| 291 |
+
human_d.append(h_dist / dim)
|
| 292 |
+
model_d.append(p_dist / dim)
|
| 293 |
+
if not human_d:
|
| 294 |
+
return None
|
| 295 |
+
return float(np.mean(np.abs(np.asarray(human_d) - np.asarray(model_d))))
|
lifemem/panel.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from random import Random
|
| 7 |
+
|
| 8 |
+
from lifemem.statements import profile_paragraph, qa_to_statements
|
| 9 |
+
from lifemem.types import (
|
| 10 |
+
AgentProfile,
|
| 11 |
+
AgentState,
|
| 12 |
+
LifeEvent,
|
| 13 |
+
SurveyOption,
|
| 14 |
+
SurveyQuestion,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
LIKERT = (
|
| 18 |
+
SurveyOption("1", "Strongly disagree"),
|
| 19 |
+
SurveyOption("2", "Disagree"),
|
| 20 |
+
SurveyOption("3", "Neither agree nor disagree"),
|
| 21 |
+
SurveyOption("4", "Agree"),
|
| 22 |
+
SurveyOption("5", "Strongly agree"),
|
| 23 |
+
)
|
| 24 |
+
FREQ = (
|
| 25 |
+
SurveyOption("1", "Never"),
|
| 26 |
+
SurveyOption("2", "Rarely"),
|
| 27 |
+
SurveyOption("3", "Sometimes"),
|
| 28 |
+
SurveyOption("4", "Often"),
|
| 29 |
+
SurveyOption("5", "Very often"),
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
EVAL_SPECS: tuple[tuple[str, str, str, tuple[SurveyOption, ...]], ...] = (
|
| 33 |
+
("POLINT", "Politics", "You are interested in political affairs.", LIKERT),
|
| 34 |
+
("TRUST", "Values", "Most people can be trusted.", LIKERT),
|
| 35 |
+
("LIFESAT", "Wellbeing", "You are satisfied with your life as a whole.", LIKERT),
|
| 36 |
+
("HLTH", "Health", "In general, your health is excellent.", LIKERT),
|
| 37 |
+
(
|
| 38 |
+
"NEIGH",
|
| 39 |
+
"Housing",
|
| 40 |
+
"You would like to stay in your current neighbourhood.",
|
| 41 |
+
LIKERT,
|
| 42 |
+
),
|
| 43 |
+
("NETUSE", "Media", "The internet is important in your daily life.", LIKERT),
|
| 44 |
+
("CIVIC", "Community", "You take part in local groups or volunteering.", LIKERT),
|
| 45 |
+
("FINSTR", "Finances", "You have been under financial strain recently.", LIKERT),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
EVENT_BANK: tuple[tuple[str, str, str, tuple[str, ...], dict[str, int]], ...] = (
|
| 49 |
+
(
|
| 50 |
+
"HLT",
|
| 51 |
+
"Health",
|
| 52 |
+
"How often have you had trouble sleeping?",
|
| 53 |
+
("health", "sleep"),
|
| 54 |
+
{"HLTH": -1, "LIFESAT": -1},
|
| 55 |
+
),
|
| 56 |
+
(
|
| 57 |
+
"JOB",
|
| 58 |
+
"Work",
|
| 59 |
+
"Have you been promoted or given more responsibility at work?",
|
| 60 |
+
("work", "promotion"),
|
| 61 |
+
{"FINSTR": -1, "LIFESAT": 1, "POLINT": 1},
|
| 62 |
+
),
|
| 63 |
+
(
|
| 64 |
+
"UNEMP",
|
| 65 |
+
"Work",
|
| 66 |
+
"Have you been unemployed and looking for work?",
|
| 67 |
+
("work", "unemployment"),
|
| 68 |
+
{"FINSTR": 1, "LIFESAT": -1, "TRUST": -1},
|
| 69 |
+
),
|
| 70 |
+
(
|
| 71 |
+
"SCHOOL",
|
| 72 |
+
"Education",
|
| 73 |
+
"Have you enrolled in or completed a new educational programme?",
|
| 74 |
+
("school", "education"),
|
| 75 |
+
{"NETUSE": 1, "POLINT": 1, "NEIGH": -1},
|
| 76 |
+
),
|
| 77 |
+
(
|
| 78 |
+
"MOVE",
|
| 79 |
+
"Housing",
|
| 80 |
+
"Have you moved to a different city or region?",
|
| 81 |
+
("housing", "migration"),
|
| 82 |
+
{"NEIGH": -1, "CIVIC": -1, "NETUSE": 1},
|
| 83 |
+
),
|
| 84 |
+
(
|
| 85 |
+
"MARRY",
|
| 86 |
+
"Family",
|
| 87 |
+
"Have you gotten married or started living with a partner?",
|
| 88 |
+
("family", "marriage"),
|
| 89 |
+
{"LIFESAT": 1, "CIVIC": 1, "NEIGH": 1},
|
| 90 |
+
),
|
| 91 |
+
(
|
| 92 |
+
"CHILD",
|
| 93 |
+
"Family",
|
| 94 |
+
"Has a child been born or joined your household?",
|
| 95 |
+
("family", "child"),
|
| 96 |
+
{"FINSTR": 1, "CIVIC": -1, "LIFESAT": 1},
|
| 97 |
+
),
|
| 98 |
+
(
|
| 99 |
+
"ILL",
|
| 100 |
+
"Health",
|
| 101 |
+
"Has a close family member had a serious illness?",
|
| 102 |
+
("family", "illness"),
|
| 103 |
+
{"HLTH": -1, "TRUST": 1, "CIVIC": 1},
|
| 104 |
+
),
|
| 105 |
+
(
|
| 106 |
+
"VOL",
|
| 107 |
+
"Community",
|
| 108 |
+
"Have you started volunteering or community work?",
|
| 109 |
+
("civic", "volunteer"),
|
| 110 |
+
{"CIVIC": 1, "POLINT": 1, "TRUST": 1},
|
| 111 |
+
),
|
| 112 |
+
(
|
| 113 |
+
"VOTE",
|
| 114 |
+
"Politics",
|
| 115 |
+
"Have you worked on a political campaign or attended a rally?",
|
| 116 |
+
("civic", "politics"),
|
| 117 |
+
{"POLINT": 1, "CIVIC": 1, "TRUST": -1},
|
| 118 |
+
),
|
| 119 |
+
(
|
| 120 |
+
"HOUSE",
|
| 121 |
+
"Housing",
|
| 122 |
+
"Have you bought a home or taken on a housing loan?",
|
| 123 |
+
("housing", "home"),
|
| 124 |
+
{"FINSTR": 1, "NEIGH": 1, "LIFESAT": 1},
|
| 125 |
+
),
|
| 126 |
+
(
|
| 127 |
+
"HARD",
|
| 128 |
+
"Finances",
|
| 129 |
+
"Has your household had trouble paying bills?",
|
| 130 |
+
("finance", "hardship"),
|
| 131 |
+
{"FINSTR": 1, "LIFESAT": -1, "HLTH": -1},
|
| 132 |
+
),
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
SES_MEANS = {
|
| 136 |
+
"low": (-0.7, -0.4, -0.5, -0.6, -0.2, -0.3, -0.4, 0.8),
|
| 137 |
+
"middle": (0.0, 0.1, 0.0, 0.1, 0.0, 0.2, 0.1, 0.0),
|
| 138 |
+
"high": (0.8, 0.5, 0.6, 0.5, 0.3, 0.4, 0.5, -0.7),
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
WAVES = (
|
| 142 |
+
(1, 1995, "adolescence"),
|
| 143 |
+
(2, 1996, "late adolescence"),
|
| 144 |
+
(3, 2002, "early adulthood"),
|
| 145 |
+
(4, 2008, "early career"),
|
| 146 |
+
(5, 2016, "established adulthood"),
|
| 147 |
+
(6, 2023, "early midlife"),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@dataclass
|
| 152 |
+
class Panel:
|
| 153 |
+
questions: list[SurveyQuestion]
|
| 154 |
+
agents: list[AgentState]
|
| 155 |
+
humans: dict[tuple[str, int, str], str]
|
| 156 |
+
waves: tuple[int, ...]
|
| 157 |
+
events_by_wave: dict[tuple[str, int], list[LifeEvent]]
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _options_for(
|
| 161 |
+
spec: tuple[str, str, str, tuple[SurveyOption, ...]],
|
| 162 |
+
) -> SurveyQuestion:
|
| 163 |
+
variable, section, question, options = spec
|
| 164 |
+
return SurveyQuestion(
|
| 165 |
+
variable=variable, section=section, question=question, options=options
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _clip_option(value: float, n_options: int) -> str:
|
| 170 |
+
index = int(round(value))
|
| 171 |
+
index = max(1, min(n_options, index))
|
| 172 |
+
return str(index)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def build_panel(
|
| 176 |
+
n_agents: int = 24,
|
| 177 |
+
n_waves: int = 6,
|
| 178 |
+
events_per_wave: int = 8,
|
| 179 |
+
seed: int = 42,
|
| 180 |
+
) -> Panel:
|
| 181 |
+
rng = Random(seed)
|
| 182 |
+
questions = [_options_for(spec) for spec in EVAL_SPECS]
|
| 183 |
+
waves = tuple(wave for wave, _year, _label in WAVES[:n_waves])
|
| 184 |
+
sexes = ("female", "male")
|
| 185 |
+
ses_levels = ("low", "middle", "high")
|
| 186 |
+
educations = ("high school", "some college", "bachelor's degree")
|
| 187 |
+
religions = ("none", "christian", "other")
|
| 188 |
+
regions = ("Northeast", "Midwest", "South", "West")
|
| 189 |
+
occupations = (
|
| 190 |
+
"student",
|
| 191 |
+
"service worker",
|
| 192 |
+
"technician",
|
| 193 |
+
"professional",
|
| 194 |
+
"unemployed",
|
| 195 |
+
)
|
| 196 |
+
agents: list[AgentState] = []
|
| 197 |
+
humans: dict[tuple[str, int, str], str] = {}
|
| 198 |
+
events_by_wave: dict[tuple[str, int], list[LifeEvent]] = {}
|
| 199 |
+
|
| 200 |
+
for i in range(n_agents):
|
| 201 |
+
ses = ses_levels[i % 3]
|
| 202 |
+
sex = sexes[i % 2]
|
| 203 |
+
education = educations[i % 3]
|
| 204 |
+
religion = religions[i % 3]
|
| 205 |
+
region = regions[i % 4]
|
| 206 |
+
occupation = occupations[i % 5]
|
| 207 |
+
birth_year = 1978 + (i % 7)
|
| 208 |
+
mean = SES_MEANS[ses]
|
| 209 |
+
offset = tuple(rng.gauss(0.0, 1.05) for _ in questions)
|
| 210 |
+
latent = tuple(m + o for m, o in zip(mean, offset, strict=True))
|
| 211 |
+
fields = {
|
| 212 |
+
"sex": sex,
|
| 213 |
+
"ses": ses,
|
| 214 |
+
"education": education,
|
| 215 |
+
"religion": religion,
|
| 216 |
+
"region": region,
|
| 217 |
+
"birth_year": str(birth_year),
|
| 218 |
+
"occupation": occupation,
|
| 219 |
+
}
|
| 220 |
+
profile = AgentProfile(
|
| 221 |
+
agent_id=f"A{i:03d}",
|
| 222 |
+
sex=sex,
|
| 223 |
+
ses=ses,
|
| 224 |
+
education=education,
|
| 225 |
+
religion=religion,
|
| 226 |
+
region=region,
|
| 227 |
+
birth_year=birth_year,
|
| 228 |
+
occupation=occupation,
|
| 229 |
+
latent=latent,
|
| 230 |
+
profile_text=profile_paragraph(fields),
|
| 231 |
+
)
|
| 232 |
+
agent = AgentState(profile=profile)
|
| 233 |
+
running = list(latent)
|
| 234 |
+
for wave_idx, wave in enumerate(waves):
|
| 235 |
+
chosen = rng.sample(EVENT_BANK, k=min(events_per_wave, len(EVENT_BANK)))
|
| 236 |
+
wave_events: list[LifeEvent] = []
|
| 237 |
+
for event_idx, (code, section, question, tags, deltas) in enumerate(chosen):
|
| 238 |
+
intensity = rng.choice([2, 3, 4, 5])
|
| 239 |
+
sign = 1 if intensity >= 3 else -1
|
| 240 |
+
for variable, delta in deltas.items():
|
| 241 |
+
q_pos = next(
|
| 242 |
+
j for j, q in enumerate(questions) if q.variable == variable
|
| 243 |
+
)
|
| 244 |
+
running[q_pos] += 0.22 * sign * delta
|
| 245 |
+
answer_code = str(intensity)
|
| 246 |
+
answer_text = FREQ[intensity - 1].text
|
| 247 |
+
second, first = qa_to_statements(question, answer_text)
|
| 248 |
+
event = LifeEvent(
|
| 249 |
+
event_id=f"{profile.agent_id}-w{wave}-{code}-{event_idx}",
|
| 250 |
+
agent_id=profile.agent_id,
|
| 251 |
+
wave=wave,
|
| 252 |
+
section=section,
|
| 253 |
+
question=question,
|
| 254 |
+
answer_code=answer_code,
|
| 255 |
+
answer_text=answer_text,
|
| 256 |
+
statement=second,
|
| 257 |
+
first_person=first,
|
| 258 |
+
tags=tags,
|
| 259 |
+
)
|
| 260 |
+
wave_events.append(event)
|
| 261 |
+
events_by_wave[(profile.agent_id, wave)] = wave_events
|
| 262 |
+
for q_idx, question in enumerate(questions):
|
| 263 |
+
noise = rng.gauss(0.0, 0.35)
|
| 264 |
+
humans[(profile.agent_id, wave, question.variable)] = _clip_option(
|
| 265 |
+
3 + running[q_idx] + 0.08 * wave_idx + noise,
|
| 266 |
+
len(question.options),
|
| 267 |
+
)
|
| 268 |
+
agents.append(agent)
|
| 269 |
+
|
| 270 |
+
return Panel(
|
| 271 |
+
questions=questions,
|
| 272 |
+
agents=agents,
|
| 273 |
+
humans=humans,
|
| 274 |
+
waves=waves,
|
| 275 |
+
events_by_wave=events_by_wave,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def panel_to_dict(panel: Panel) -> dict:
|
| 280 |
+
return {
|
| 281 |
+
"waves": list(panel.waves),
|
| 282 |
+
"questions": [
|
| 283 |
+
{
|
| 284 |
+
"variable": q.variable,
|
| 285 |
+
"section": q.section,
|
| 286 |
+
"question": q.question,
|
| 287 |
+
"options": [{"code": o.code, "text": o.text} for o in q.options],
|
| 288 |
+
}
|
| 289 |
+
for q in panel.questions
|
| 290 |
+
],
|
| 291 |
+
"agents": [
|
| 292 |
+
{
|
| 293 |
+
"agent_id": agent.profile.agent_id,
|
| 294 |
+
"sex": agent.profile.sex,
|
| 295 |
+
"ses": agent.profile.ses,
|
| 296 |
+
"education": agent.profile.education,
|
| 297 |
+
"religion": agent.profile.religion,
|
| 298 |
+
"region": agent.profile.region,
|
| 299 |
+
"birth_year": agent.profile.birth_year,
|
| 300 |
+
"occupation": agent.profile.occupation,
|
| 301 |
+
"profile_text": agent.profile.profile_text,
|
| 302 |
+
"latent": list(agent.profile.latent),
|
| 303 |
+
}
|
| 304 |
+
for agent in panel.agents
|
| 305 |
+
],
|
| 306 |
+
"events": [
|
| 307 |
+
{
|
| 308 |
+
"event_id": event.event_id,
|
| 309 |
+
"agent_id": event.agent_id,
|
| 310 |
+
"wave": event.wave,
|
| 311 |
+
"section": event.section,
|
| 312 |
+
"question": event.question,
|
| 313 |
+
"answer_code": event.answer_code,
|
| 314 |
+
"answer_text": event.answer_text,
|
| 315 |
+
"statement": event.statement,
|
| 316 |
+
"first_person": event.first_person,
|
| 317 |
+
"tags": list(event.tags),
|
| 318 |
+
}
|
| 319 |
+
for events in panel.events_by_wave.values()
|
| 320 |
+
for event in events
|
| 321 |
+
],
|
| 322 |
+
"humans": [
|
| 323 |
+
{
|
| 324 |
+
"agent_id": agent_id,
|
| 325 |
+
"wave": wave,
|
| 326 |
+
"variable": variable,
|
| 327 |
+
"answer": answer,
|
| 328 |
+
}
|
| 329 |
+
for (agent_id, wave, variable), answer in sorted(panel.humans.items())
|
| 330 |
+
],
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def save_panel(panel: Panel, path: Path) -> None:
|
| 335 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 336 |
+
path.write_text(json.dumps(panel_to_dict(panel), indent=2), encoding="utf-8")
|
lifemem/parse.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
_THINK_BLOCK = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def strip_thinking(text: str) -> str:
|
| 9 |
+
"""Drop Qwen thinking spans before Likert parsing."""
|
| 10 |
+
if not text:
|
| 11 |
+
return ""
|
| 12 |
+
cleaned = _THINK_BLOCK.sub("", text)
|
| 13 |
+
marker = "</think>"
|
| 14 |
+
lower = cleaned.lower()
|
| 15 |
+
if marker in lower:
|
| 16 |
+
cleaned = cleaned[lower.rfind(marker) + len(marker) :]
|
| 17 |
+
return cleaned.strip()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def parse_option_code(raw: str, valid_codes: tuple[str, ...]) -> str | None:
|
| 21 |
+
if not raw:
|
| 22 |
+
return None
|
| 23 |
+
text = strip_thinking(raw)
|
| 24 |
+
if text in valid_codes:
|
| 25 |
+
return text
|
| 26 |
+
match = re.search(r"\d+", text)
|
| 27 |
+
if match and match.group(0) in valid_codes:
|
| 28 |
+
return match.group(0)
|
| 29 |
+
lowered = text.lower()
|
| 30 |
+
for code in valid_codes:
|
| 31 |
+
if code.lower() == lowered:
|
| 32 |
+
return code
|
| 33 |
+
return None
|
lifemem/prompts.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from lifemem.statements import option_block
|
| 4 |
+
from lifemem.types import AgentState, RetrievedEvent, SurveyQuestion
|
| 5 |
+
|
| 6 |
+
ROLEPLAY = (
|
| 7 |
+
"You are not an AI assistant; you are role-playing a human survey respondent. "
|
| 8 |
+
"Answer as that person."
|
| 9 |
+
)
|
| 10 |
+
ANTI_STEREOTYPE = (
|
| 11 |
+
"Do not assume that one demographic attribute determines another. "
|
| 12 |
+
"When information is missing, preserve uncertainty rather than filling it with stereotypes."
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _join(*blocks: str) -> str:
|
| 17 |
+
return "\n\n".join(block for block in blocks if block)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def build_direct(question: SurveyQuestion) -> str:
|
| 21 |
+
return _join(
|
| 22 |
+
ROLEPLAY,
|
| 23 |
+
"Simulate one person and answer the following question.",
|
| 24 |
+
option_block(question),
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def build_profile(agent: AgentState, question: SurveyQuestion, extra: str = "") -> str:
|
| 29 |
+
return _join(
|
| 30 |
+
ROLEPLAY,
|
| 31 |
+
"You are answering a longitudinal social survey as the described person.",
|
| 32 |
+
f"Demographic profile:\n{agent.profile.profile_text}",
|
| 33 |
+
extra,
|
| 34 |
+
option_block(question),
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_anti_stereotype(agent: AgentState, question: SurveyQuestion) -> str:
|
| 39 |
+
return build_profile(agent, question, extra=ANTI_STEREOTYPE)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_retrieval(
|
| 43 |
+
agent: AgentState,
|
| 44 |
+
question: SurveyQuestion,
|
| 45 |
+
retrieved: list[RetrievedEvent],
|
| 46 |
+
include_profile: bool = True,
|
| 47 |
+
) -> str:
|
| 48 |
+
profile = (
|
| 49 |
+
agent.profile.profile_text
|
| 50 |
+
if include_profile
|
| 51 |
+
else "Profile omitted by ablation."
|
| 52 |
+
)
|
| 53 |
+
if retrieved:
|
| 54 |
+
events = "\n".join(f"- {item.event.statement}" for item in retrieved)
|
| 55 |
+
else:
|
| 56 |
+
events = "No relevant life experiences retrieved."
|
| 57 |
+
return _join(
|
| 58 |
+
ROLEPLAY,
|
| 59 |
+
"You are answering a longitudinal social survey as the described person.",
|
| 60 |
+
f"Demographic profile:\n{profile}",
|
| 61 |
+
f"Relevant life experiences:\n{events}",
|
| 62 |
+
option_block(question),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def build_full_history(
|
| 67 |
+
agent: AgentState,
|
| 68 |
+
question: SurveyQuestion,
|
| 69 |
+
max_chars: int,
|
| 70 |
+
) -> str:
|
| 71 |
+
lines = [f"- {event.statement}" for event in agent.events]
|
| 72 |
+
kept: list[str] = []
|
| 73 |
+
total = 0
|
| 74 |
+
for line in reversed(lines):
|
| 75 |
+
if total + len(line) > max_chars:
|
| 76 |
+
continue
|
| 77 |
+
kept.append(line)
|
| 78 |
+
total += len(line)
|
| 79 |
+
event_block = "\n".join(reversed(kept)) if kept else "No life events available."
|
| 80 |
+
return _join(
|
| 81 |
+
ROLEPLAY,
|
| 82 |
+
"You are answering a longitudinal social survey as the described person.",
|
| 83 |
+
f"Demographic profile:\n{agent.profile.profile_text}",
|
| 84 |
+
f"Life history:\n{event_block}",
|
| 85 |
+
option_block(question),
|
| 86 |
+
)
|
lifemem/retrieval.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import re
|
| 5 |
+
import zlib
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from lifemem.types import LifeEvent, RetrievedEvent, SurveyQuestion
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def recency_weight(event_wave: int, current_wave: int, alpha: float) -> float:
|
| 13 |
+
if alpha < 0:
|
| 14 |
+
raise ValueError("forgetting alpha must be non-negative")
|
| 15 |
+
return float(alpha ** max(current_wave - event_wave, 0))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def hashed_ngram_embed(text: str, dim: int = 128, n: int = 3) -> np.ndarray:
|
| 19 |
+
"""Deterministic encoder used when MiniLM/BGE weights are unavailable."""
|
| 20 |
+
|
| 21 |
+
tokens = re.findall(r"[a-z0-9]+", text.lower())
|
| 22 |
+
blob = " ".join(tokens)
|
| 23 |
+
vec = np.zeros(dim, dtype=np.float64)
|
| 24 |
+
if len(blob) < n:
|
| 25 |
+
grams = [blob] if blob else ["_"]
|
| 26 |
+
else:
|
| 27 |
+
grams = [blob[i : i + n] for i in range(len(blob) - n + 1)]
|
| 28 |
+
for gram in grams:
|
| 29 |
+
index = zlib.crc32(gram.encode("utf-8")) % dim
|
| 30 |
+
vec[index] += 1.0
|
| 31 |
+
norm = float(np.linalg.norm(vec))
|
| 32 |
+
if norm == 0:
|
| 33 |
+
return vec
|
| 34 |
+
return vec / norm
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def cosine(a: np.ndarray, b: np.ndarray) -> float:
|
| 38 |
+
denom = float(np.linalg.norm(a) * np.linalg.norm(b))
|
| 39 |
+
if denom == 0:
|
| 40 |
+
return 0.0
|
| 41 |
+
value = float(a @ b / denom)
|
| 42 |
+
if math.isnan(value):
|
| 43 |
+
return 0.0
|
| 44 |
+
return value
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class HashedEventEncoder:
|
| 48 |
+
def __init__(self, dim: int = 128) -> None:
|
| 49 |
+
self.dim = dim
|
| 50 |
+
|
| 51 |
+
def encode(self, text: str) -> np.ndarray:
|
| 52 |
+
return hashed_ngram_embed(text, dim=self.dim)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def retrieve_events(
|
| 56 |
+
query: SurveyQuestion,
|
| 57 |
+
events: list[LifeEvent],
|
| 58 |
+
current_wave: int,
|
| 59 |
+
top_k: int,
|
| 60 |
+
alpha: float,
|
| 61 |
+
encoder: HashedEventEncoder | None = None,
|
| 62 |
+
) -> list[RetrievedEvent]:
|
| 63 |
+
if not events:
|
| 64 |
+
return []
|
| 65 |
+
encoder = encoder or HashedEventEncoder()
|
| 66 |
+
query_vec = encoder.encode(query.question)
|
| 67 |
+
scored: list[RetrievedEvent] = []
|
| 68 |
+
for event in events:
|
| 69 |
+
sim = cosine(query_vec, encoder.encode(event.retrieval_text()))
|
| 70 |
+
recency = recency_weight(event.wave, current_wave, alpha)
|
| 71 |
+
scored.append(
|
| 72 |
+
RetrievedEvent(
|
| 73 |
+
event=event,
|
| 74 |
+
semantic_similarity=sim,
|
| 75 |
+
recency_weight=recency,
|
| 76 |
+
final_score=float(sim * recency),
|
| 77 |
+
)
|
| 78 |
+
)
|
| 79 |
+
scored.sort(key=lambda item: item.final_score, reverse=True)
|
| 80 |
+
return scored[:top_k]
|
lifemem/statements.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from lifemem.types import SurveyQuestion
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def qa_to_statements(question: str, answer_text: str) -> tuple[str, str]:
|
| 7 |
+
"""Rule-based survey-to-statement conversion (paper uses gpt-3.5-turbo-0125)."""
|
| 8 |
+
|
| 9 |
+
q = question.strip().rstrip("?")
|
| 10 |
+
answer = answer_text.strip().rstrip(".")
|
| 11 |
+
lowered = q[:1].lower() + q[1:] if q else q
|
| 12 |
+
second = f"You answered '{answer}' to the question '{lowered}'."
|
| 13 |
+
first = f"I answered '{answer}' to the question '{lowered}'."
|
| 14 |
+
return second, first
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def profile_paragraph(fields: dict[str, str]) -> str:
|
| 18 |
+
sex = fields["sex"]
|
| 19 |
+
ses = fields["ses"]
|
| 20 |
+
education = fields["education"]
|
| 21 |
+
religion = fields["religion"]
|
| 22 |
+
region = fields["region"]
|
| 23 |
+
birth_year = fields["birth_year"]
|
| 24 |
+
occupation = fields["occupation"]
|
| 25 |
+
return (
|
| 26 |
+
f"You are {sex}. You were born in {birth_year}. You live in {region}. "
|
| 27 |
+
f"Your education level is {education}. You work as {occupation}. "
|
| 28 |
+
f"You identify as {religion}. Your socioeconomic status is {ses}."
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def option_block(question: SurveyQuestion) -> str:
|
| 33 |
+
lines = ["Question:", question.question, "", "Options:"]
|
| 34 |
+
for option in question.options:
|
| 35 |
+
lines.append(f"{option.code}: {option.text}")
|
| 36 |
+
lines.append("")
|
| 37 |
+
lines.append(
|
| 38 |
+
"Answer with exactly one option number. Do not provide any explanation."
|
| 39 |
+
)
|
| 40 |
+
return "\n".join(lines)
|
lifemem/types.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@dataclass(frozen=True)
|
| 7 |
+
class SurveyOption:
|
| 8 |
+
code: str
|
| 9 |
+
text: str
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(frozen=True)
|
| 13 |
+
class SurveyQuestion:
|
| 14 |
+
variable: str
|
| 15 |
+
section: str
|
| 16 |
+
question: str
|
| 17 |
+
options: tuple[SurveyOption, ...]
|
| 18 |
+
kind: str = "evaluate"
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def option_codes(self) -> tuple[str, ...]:
|
| 22 |
+
return tuple(option.code for option in self.options)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class LifeEvent:
|
| 27 |
+
event_id: str
|
| 28 |
+
agent_id: str
|
| 29 |
+
wave: int
|
| 30 |
+
section: str
|
| 31 |
+
question: str
|
| 32 |
+
answer_code: str
|
| 33 |
+
answer_text: str
|
| 34 |
+
statement: str
|
| 35 |
+
first_person: str
|
| 36 |
+
tags: tuple[str, ...] = ()
|
| 37 |
+
|
| 38 |
+
def retrieval_text(self) -> str:
|
| 39 |
+
return (
|
| 40 |
+
f"Wave {self.wave}. Section: {self.section}. "
|
| 41 |
+
f"Question: {self.question} Answer: {self.answer_text}. "
|
| 42 |
+
f"Statement: {self.statement}"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass(frozen=True)
|
| 47 |
+
class RetrievedEvent:
|
| 48 |
+
event: LifeEvent
|
| 49 |
+
semantic_similarity: float
|
| 50 |
+
recency_weight: float
|
| 51 |
+
final_score: float
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass
|
| 55 |
+
class AgentProfile:
|
| 56 |
+
agent_id: str
|
| 57 |
+
sex: str
|
| 58 |
+
ses: str
|
| 59 |
+
education: str
|
| 60 |
+
religion: str
|
| 61 |
+
region: str
|
| 62 |
+
birth_year: int
|
| 63 |
+
occupation: str
|
| 64 |
+
latent: tuple[float, ...]
|
| 65 |
+
profile_text: str
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass
|
| 69 |
+
class AgentState:
|
| 70 |
+
profile: AgentProfile
|
| 71 |
+
events: list[LifeEvent] = field(default_factory=list)
|
| 72 |
+
parametric: dict[str, str] = field(default_factory=dict)
|
| 73 |
+
adapter_vector: list[float] = field(default_factory=list)
|
| 74 |
+
adapter_trace: list[list[float]] = field(default_factory=list)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@dataclass
|
| 78 |
+
class GenerationRecord:
|
| 79 |
+
agent_id: str
|
| 80 |
+
wave: int
|
| 81 |
+
variable: str
|
| 82 |
+
human_answer: str
|
| 83 |
+
parsed_answer: str | None
|
| 84 |
+
valid_options: tuple[str, ...]
|
| 85 |
+
method: str
|
| 86 |
+
identity_groups: dict[str, str]
|
| 87 |
+
retrieved_event_ids: tuple[str, ...] = ()
|
| 88 |
+
prompt: str = ""
|
| 89 |
+
raw_output: str = ""
|
| 90 |
+
valid: bool = True
|
pyproject.toml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "autoresearch-mitigating-identity-essentialism-lifemem-2026-09-09"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Replication of LifeMem (arXiv:2608.19621): longitudinal memory for LLM social agents."
|
| 5 |
+
requires-python = ">=3.10"
|
| 6 |
+
dependencies = [
|
| 7 |
+
"huggingface_hub>=0.30.0",
|
| 8 |
+
"numpy>=2.0.0",
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
[project.optional-dependencies]
|
| 12 |
+
llm = [
|
| 13 |
+
"accelerate>=1.0.0",
|
| 14 |
+
"boto3>=1.35.0",
|
| 15 |
+
"peft>=0.17.0",
|
| 16 |
+
"pillow>=10.0.0",
|
| 17 |
+
"sentence-transformers>=3.0.0",
|
| 18 |
+
"torch>=2.6.0",
|
| 19 |
+
"transformers>=5.0.0",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
[tool.uv]
|
| 23 |
+
package = false
|
scripts/hf_job.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""GPU LifeMem run on Qwen/Qwen3.5-4B. Intended for Hugging Face Jobs.
|
| 3 |
+
|
| 4 |
+
`hf jobs uv run` only uploads this file, so the job downloads `lifemem/` from
|
| 5 |
+
the source dataset when it is not already on PYTHONPATH.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
# /// script
|
| 9 |
+
# requires-python = ">=3.10"
|
| 10 |
+
# dependencies = [
|
| 11 |
+
# "accelerate>=1.0.0",
|
| 12 |
+
# "boto3>=1.35.0",
|
| 13 |
+
# "huggingface_hub>=0.30.0",
|
| 14 |
+
# "numpy>=2.0.0",
|
| 15 |
+
# "peft>=0.17.0",
|
| 16 |
+
# "pillow>=10.0.0",
|
| 17 |
+
# "safetensors>=0.4.0",
|
| 18 |
+
# "torch>=2.6.0",
|
| 19 |
+
# "transformers>=5.0.0",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _ensure_package() -> Path:
|
| 32 |
+
here = Path(__file__).resolve()
|
| 33 |
+
candidates = [
|
| 34 |
+
Path(os.environ["LIFEMEM_SRC_MOUNT"])
|
| 35 |
+
if os.environ.get("LIFEMEM_SRC_MOUNT")
|
| 36 |
+
else None,
|
| 37 |
+
here.parents[1] if here.parent.name == "scripts" else here.parent,
|
| 38 |
+
Path("/src"),
|
| 39 |
+
]
|
| 40 |
+
for local in candidates:
|
| 41 |
+
if local is None:
|
| 42 |
+
continue
|
| 43 |
+
if (local / "lifemem" / "config.py").exists():
|
| 44 |
+
if str(local) not in sys.path:
|
| 45 |
+
sys.path.insert(0, str(local))
|
| 46 |
+
return local
|
| 47 |
+
from huggingface_hub import snapshot_download
|
| 48 |
+
|
| 49 |
+
repo = os.environ.get("LIFEMEM_SRC_REPO", "mtorres98/lifemem-replication-src")
|
| 50 |
+
snap = Path(
|
| 51 |
+
snapshot_download(
|
| 52 |
+
repo_id=repo,
|
| 53 |
+
repo_type="dataset",
|
| 54 |
+
token=os.environ.get("HF_TOKEN"),
|
| 55 |
+
)
|
| 56 |
+
)
|
| 57 |
+
if str(snap) not in sys.path:
|
| 58 |
+
sys.path.insert(0, str(snap))
|
| 59 |
+
return snap
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
ROOT = _ensure_package()
|
| 63 |
+
|
| 64 |
+
from huggingface_hub import login
|
| 65 |
+
from lifemem.artifacts import push_json
|
| 66 |
+
from lifemem.config import LifeMemConfig
|
| 67 |
+
from lifemem.experiment import run_suite
|
| 68 |
+
from lifemem.lora_memory import lora_config_dict
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _int_env(name: str, default: int) -> int:
|
| 72 |
+
raw = os.environ.get(name)
|
| 73 |
+
return int(raw) if raw else default
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main() -> None:
|
| 77 |
+
token = os.environ.get("HF_TOKEN")
|
| 78 |
+
if token:
|
| 79 |
+
login(token=token)
|
| 80 |
+
try:
|
| 81 |
+
import torch
|
| 82 |
+
except ImportError as exc:
|
| 83 |
+
raise SystemExit("torch is required for the GPU backend") from exc
|
| 84 |
+
if not torch.cuda.is_available():
|
| 85 |
+
raise SystemExit(
|
| 86 |
+
"CUDA is required for the Qwen LifeMem job; got CPU-only torch"
|
| 87 |
+
)
|
| 88 |
+
print(json.dumps({"cuda": torch.cuda.get_device_name(0), "root": str(ROOT)}))
|
| 89 |
+
config = LifeMemConfig(
|
| 90 |
+
model_name=os.environ.get("LIFEMEM_MODEL", "Qwen/Qwen3.5-4B")
|
| 91 |
+
)
|
| 92 |
+
n_agents = _int_env("LIFEMEM_N_AGENTS", 8)
|
| 93 |
+
n_waves = _int_env("LIFEMEM_N_WAVES", 6)
|
| 94 |
+
events_per_wave = _int_env("LIFEMEM_EVENTS_PER_WAVE", 8)
|
| 95 |
+
results = run_suite(
|
| 96 |
+
config,
|
| 97 |
+
n_agents=n_agents,
|
| 98 |
+
n_waves=n_waves,
|
| 99 |
+
events_per_wave=events_per_wave,
|
| 100 |
+
backend="llm",
|
| 101 |
+
)
|
| 102 |
+
results["lora"] = lora_config_dict(config)
|
| 103 |
+
results["backbone"] = config.model_name
|
| 104 |
+
results["device"] = torch.cuda.get_device_name(0)
|
| 105 |
+
out = Path(os.environ.get("LIFEMEM_OUT", "gpu_results.json"))
|
| 106 |
+
urls = push_json(results, "gpu_results.json", out)
|
| 107 |
+
print(json.dumps({"urls": urls}, indent=2))
|
| 108 |
+
print(json.dumps({k: v["kl"] for k, v in results["methods"].items()}, indent=2))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
main()
|