Dataset Viewer

The dataset viewer is not available because its heuristics could not detect any supported data files. You can try uploading some data files, or configuring the data files location manually.

YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

Actor-Critic Cognitive Reframing

Anonymous code and data artifact for a manuscript under review.

This repository contains the main version-2 workflow: structured user modeling, an actor that proposes reframes, and a critic that supplies CBT scores and targeted feedback. It supports commercial APIs and self-hosted open-weight models through the same workflow. There is no model training or weight update.

Protocol

Each sample receives five sequential loops with five candidates per loop. The user-modeling message is computed once using the actor model. The actor sees the situation, thought, that message, the supplied five reference examples, and the current incumbent's feedback. The critic sees only the original situation, thought, and one candidate. Identical candidate text within a sample reuses the first valid critic response.

The reported utility has exactly three components:

CBT      = sum(five critic questionnaire scores) / 9
semantic = cosine(MiniLM(situation), MiniLM(candidate))
style    = mean over the five reference reframes of:
           1 - (abs(polarity_candidate - polarity_reference)/2
                + abs(subjectivity_candidate - subjectivity_reference))/2

utility  = 0.5 * CBT + 0.3 * semantic + 0.2 * style

The critic dimensions are evidence sensitivity (0-2), alternative explanations (0-2), distortion regulation (0-2), balanced self-evaluation (0-2), and cognitive flexibility (0-1). MiniLM embeddings use a fixed model revision. Polarity and subjectivity are computed with TextBlob. Raw semantic cosine is not rescaled; utility has a theoretical range of [-0.3, 1].

All items use the reframe task. Unsafe candidates cannot replace a safe incumbent. A new, different response replaces the incumbent only when its utility improves by more than 0.01. A sample with no safe first-loop candidate is recorded as failed. Otherwise, all five loops run, including when the utility plateaus.

new_candidate is the best eligible candidate of the current loop; if none is eligible, the best attempted candidate is exported with candidate_safe=false. incumbent is the retained safe response. Its utility cannot decrease by the selection rule. These are internal optimization scores, not independent LLM-judge evaluations or evidence of clinical effectiveness. There is no BLEU/ROUGE or independent judge call in this release.

Files

run.py                    Command-line entry point
run_experiment.ipynb      Optional notebook using the same entry point
configs/                  Commercial, open-model, and mixed-provider examples
data/                     CR (300 samples), PR (1,000 samples), and checksums
reframing/config.py       Validated model and experiment settings
reframing/prompts.py      All prompts and revision strategies
reframing/schemas.py      Structured actor and critic responses
reframing/providers.py    API routing, validation, retries, and request cache
reframing/data.py         CSV loading and supplied reference lookup
reframing/features.py     Remote or optional local MiniLM/TextBlob features
reframing/scoring.py      Utility and incumbent selection
reframing/workflow.py     Five-loop execution and sample concurrency
reframing/reporting.py    CSV summaries and utility plots
serving/modal_features.py Optional remote feature service
tests/                    Offline tests; no credentials required

Installation

Use Python 3.11 or 3.12. From this directory:

python -m venv .venv

Activate with .venv\Scripts\Activate.ps1 in PowerShell, or source .venv/bin/activate on Linux/macOS. Then:

python -m pip install -r requirements.txt

Copy .env.example to .env and fill in the credentials you need. Credentials are read only from this release's .env or the process environment. Environment variables take precedence. Configuration JSON contains environment-variable names, never API key values. The distribution includes no populated .env.

For a notebook kernel, additionally install ipykernel and open run_experiment.ipynb with the extracted release directory as the working directory. On Kaggle, enable Internet, extract the whole release under /kaggle/working, and populate os.environ from Kaggle Secrets before calling main. The notebook and CLI share the same configuration and checkpoints.

Feature computation

The default is remote features so the client machine needs no PyTorch or GPU. Set EMBEDDING_API_URL to the full feature POST endpoint and EMBEDDING_API_TOKEN to its bearer token. The client verifies the embedding model, revision, vector dimension, normalization, and sentiment ranges.

An optional Modal service is included. Install requirements-modal.txt, configure your own Modal account, and create a Modal secret named reframing-feature-auth containing EMBEDDING_API_TOKEN. Deploy with:

modal deploy serving/modal_features.py

Copy the resulting endpoint into your private .env. The service uses one T4 for MiniLM, runs TextBlob on CPU, and scales down after 60 seconds of inactivity. The first deployment downloads the pinned embedding checkpoint. This service is for features; open-weight LLM serving is configured separately below.

Alternatively, compute features locally:

python -m pip install -r requirements-local.txt
python run.py --dataset CR --max-samples 3 --features local --device cpu

Use --device cuda when a compatible GPU/PyTorch setup is available. The optional feature requirements pin the same library versions used in the Modal image. CPU and GPU inference can have small numerical differences; the backend is recorded in the run manifest.

Commercial models

Set OPENAI_API_KEY and GEMINI_API_KEY. The default actor is gpt-4o-mini-2024-07-18, and the critic is gemini-2.5-flash.

Validate the complete data and configuration without any API call:

python run.py --config configs/closed_models.json --dataset CR --dry-run

Run a small integration check, then the full datasets:

python run.py --config configs/closed_models.json --dataset CR --max-samples 3
python run.py --config configs/closed_models.json --dataset CR
python run.py --config configs/closed_models.json --dataset PR

Use --dataset ALL for one run over both datasets. A full sample uses at most 51 logical LLM calls: one user-modeling call, 25 actor calls, and 25 critic calls, before retries and reuse of identical candidate scores. API availability and account access must be checked for the chosen model IDs.

To swap models, change the whole actor and critic configurations, including provider. Set the actor temperature to 0.7 and critic temperature to 0.0 for the default protocol. Routing is explicit and independent for each role.

Open-weight and mixed models

Serve instruction-tuned checkpoints on GPU machines using an OpenAI-compatible chat-completions server, for example vLLM. Illustrative server commands are:

vllm serve Qwen/Qwen2.5-7B-Instruct --served-model-name open-actor --port 8000 --generation-config vllm
vllm serve mistralai/Mistral-7B-Instruct-v0.3 --served-model-name open-critic --port 8001 --generation-config vllm

Provision each server on a GPU/host with sufficient memory. Install the serving software in its own environment, separate from the lightweight client. Choose checkpoints and licenses appropriate to your experiment; these examples do not claim equivalent quality across models. Record exact checkpoint revisions, quantization, serving version, and GPU details alongside reported experiments.

Set ACTOR_BASE_URL and CRITIC_BASE_URL to the respective /v1 API base URLs. The example values point to localhost; replace them for remote servers. Set ACTOR_API_KEY and CRITIC_API_KEY if authentication is enabled. Empty keys are allowed for compatible servers without authentication. Run:

python run.py --config configs/open_models.json --dataset CR --max-samples 3
python run.py --config configs/open_models.json --dataset PR
python run.py --config configs/mixed_models.json --dataset CR

mixed_models.json uses an open-weight actor and Gemini critic. Any role can use openai, gemini, or compatible. User modeling always uses the actor endpoint. For Ollama or another compatible implementation, set model to the server's exact model ID and use its /v1 URL. Local LLM inference is not performed by this client.

The default response_format is json_schema. If a compatible endpoint only supports JSON mode, set response_format to json_object. If it has no structured output parameter, select prompt, which places the schema in the prompt. All three modes still validate every response locally; malformed responses fail after bounded retries. Set send_seed=false if the endpoint rejects seeds. These choices affect generation and are recorded in the manifest. The client does not silently switch models or output modes after a failure.

Resume, concurrency, and failures

By default, runs are written under outputs/<dataset>-<config-name>/. Use --run-dir outputs/my-run to choose a different directory. Repeating a command resumes completed calls and loops. Use one process per run directory.

python run.py --dataset PR --sample-workers 2 --candidate-workers 2
python run.py --dataset PR --retry-failed
python run.py --dataset PR --report-only

Loops remain sequential within a sample. Maximum candidate-task concurrency is sample_workers * candidate_workers. Failed samples are logged and skipped so other samples continue; --retry-failed explicitly retries previously failed samples. --fail-fast stops scheduling new samples on the first error. Exit code 2 indicates that some selected samples were not completed.

Retries are bounded. Refusals, explicit safety blocks, and invalid model access are not bypassed. No client output-token cap is sent; provider context/output limits still apply. Gemini 2.5 Flash requests disable thinking, matching the main protocol. Gemini decoding recovery can change the seed and raise temperature to 0.8 after a failed decoding; every attempt records the effective settings. Seeds are best-effort API requests, not guarantees of deterministic results.

The manifest rejects changes to code, prompts, models, data, scoring, or endpoint fingerprints within an existing run. Use a fresh directory for a new experiment. This clean release has its own manifest version; historical development checkpoints must not be merged into its runs.

Outputs and interpretation

  • manifest.json: protocol, prompts, config, dataset/reference hashes, and backend.
  • items/*.json: sample state, all candidates, critic feedback, and selections.
  • calls/*.json: first valid response cache; attempts/*.json: request audit.
  • errors/*.json: sample IDs and error types, without raw exception messages.
  • final_scores.csv: final incumbent scores for complete samples.
  • loop_scores.csv: both trajectories for samples completing all five loops.
  • loop_means.csv: per-dataset means; ALL pools samples by count when applicable.
  • run_status.csv: completion counts and cumulative active wall time per sample.
  • usage.csv: reported input/output tokens and API request durations, including retries.
  • <dataset>_utility.png/pdf: line plots of saved internal utility.

Plotting/reporting never calls a model. All five-loop means use the same complete sample cohort. Concurrent request durations must not be added to obtain wall time. Active sample wall time includes each invocation and its retries but excludes time between stopped and resumed runs. No cost or runtime estimate is invented.

Data and anonymity

data/300wTop5v2.csv contains 300 CR samples; data/1000wTop5v2.csv contains 1,000 PR samples. Both files are copied byte-for-byte from the supplied benchmark files. All original columns and all five top_5_similar references remain unchanged. data/checksums.json records file checksums and row counts.

Reference entries can overlap evaluation gold reframes, including a sample's own gold. The manifest records overlap counts; no references are filtered, split, or retrieved again. Gold is not passed as a separate prompt field, but references can contain the same answer. Report this limitation when describing the experiment. Original dataset terms continue to apply; this bundle does not assign them a new license.

The review distribution omits author/affiliation/contact fields, personal account URLs, development paths, private credentials, Git history, and previous outputs. Notebook outputs are empty. Public model identifiers and scientific terminology remain necessary for reproducibility. Benchmark narratives are preserved, not represented as a newly de-identified dataset. Newly generated outputs and private endpoint settings require their own review before sharing.

Offline checks

python -m unittest discover -s tests -v
python run.py --dataset ALL --dry-run

Tests use mock HTTP endpoints and small synthetic feature vectors. They cover provider routing, JSON validation, caching, retries, scoring, selection, parallel execution, resume, dataset integrity, and score export. They do not certify live provider availability or the quality of any model's outputs.

API format references: OpenAI structured outputs, vLLM compatible server, and Ollama compatibility.

Downloads last month
19