Skip to content

Repository files navigation

THETA Logo

THETA (θ)

PlatformHuggingFacePaper

English | 中文

THETA (θ) is a low-barrier, high-performance agent-native topic analysis platform for social science research.


Table of Contents

  1. Quick Start: 5-Minute Setup
  2. Agent Workflow Skill: THETA Workflow
  3. Data Format Requirements
  4. Configuration System: From Hardware to Experiments
  5. Running Modes: Beginner vs Expert
  6. Output Map: Where Are the Results?
  7. Scientific Evaluation Standards
  8. Supported Models
  9. Training Parameters Reference
  10. FAQ

Quick Start: 5-Minute Setup

Step 1: Clone Repository

git clone https://github.com/CodeSoul-co/THETA.git
cd THETA

Step 2: Environment Isolation (Conda)

conda create -n theta python=3.10 -y
conda activate theta

Step 3: Install Dependencies + Download Models

bash scripts/env_setup.sh

Step 4: Configure Environment Variables

# Copy configuration template
cp .env.example .env
# Edit .env file to configure model paths# At minimum, configure: QWEN_MODEL_0_6B and SBERT_MODEL_PATH

Step 5: Load Environment Variables

# If you encounter "$'\r': command not found" error, fix Windows line endings first
sed -i 's/\r$//' scripts/env_setup.sh
# Load environment variables to current shell (required for subsequent scripts)source scripts/env_setup.sh

Model Download Links:

ModelPurposeDownload Link
Qwen3-Embedding-0.6BTHETA document embeddingModelScope
all-MiniLM-L6-v2CTM/SBERT embeddingHuggingFace

Place downloaded models in the models/ directory:

models/
├── qwen3_embedding_0.6B/
└── sbert/sentence-transformers/all-MiniLM-L6-v2/

Automatic Model Download

THETA supports automatic detection and download of missing model weight files during training.

Automatic Download (Recommended): Simply run the training command, and the system will automatically detect and download missing models:

# CTM/BERTopic training - auto-download SBERT
bash scripts/train_baseline.sh ctm --dataset your_dataset --num_topics 20
# THETA training - auto-download Qwen
bash scripts/train_theta.sh --dataset your_dataset --model_size 0.6B

Note: The first run may take a few minutes to download models. If automatic download fails due to network issues, please manually download from the links above.


Agent Workflow Skill: THETA Workflow

This repository includes a portable agent workflow skill at skills/theta-workflow/. A standalone public copy is published at CodeSoul-co/theta-skill for agents that want to install the workflow without cloning the full THETA project. The standalone repository also links back to CodeSoul-co/THETA, so both publication surfaces point to each other. Use it when you want an agent to guide the full THETA process: repository check, data confirmation, environment preflight, embedding selection, model recommendation, command review, training confirmation, result analysis, tuning, and reporting. The skill is plain Markdown plus a read-only Python helper, so it does not require Codex-specific APIs. It also includes separate Chinese and English user-question and confirmation flows.

Generic usage:

  1. Point your agent at skills/theta-workflow/SKILL.md, or install/copy the whole skills/theta-workflow/ folder into your agent's skill directory.
  2. Ask the agent to use the THETA Workflow skill or instructions:
Use the THETA Workflow skill in skills/theta-workflow to help me run THETA topic modeling on a policy-text dataset.

If your agent runtime supports named skill invocation, this can also be called as $theta-workflow.

To install from the standalone repository instead of this THETA checkout:

git clone https://github.com/CodeSoul-co/theta-skill.git
cp -R theta-skill/theta-workflow "<AGENT_SKILLS_DIR>/theta-workflow"

Generic folder-based install:

mkdir -p "<AGENT_SKILLS_DIR>"
cp -R skills/theta-workflow "<AGENT_SKILLS_DIR>/theta-workflow"

Optional Codex-compatible local install:

mkdir -p "${CODEX_HOME:-$HOME/.codex}/skills"
cp -R skills/theta-workflow "${CODEX_HOME:-$HOME/.codex}/skills/theta-workflow"

Restart or reload your agent runtime after installation if it caches available skills.

The standalone repository includes sync scripts for maintainers. Use scripts/sync_from_theta.sh there to pull updates from this THETA copy, or scripts/sync_to_theta.sh to push standalone edits back into skills/theta-workflow/.

When the skill is active, it first checks whether the current workspace is a usable THETA repository. If no repository is found, the first confirmed step is cloning https://github.com/CodeSoul-co/THETA.git; it will not configure the environment, inspect data, or generate training commands before the repository exists.

Run the read-only preflight helper before changing local files or launching training:

python skills/theta-workflow/scripts/inspect_theta_env.py \
--dataset path/to/data.csv \
--text-column text \
--mode zero_shot

The skill enforces explicit confirmation before writing files, installing dependencies, editing .env, calling cloud embedding APIs, downloading models, running training, overwriting results, deleting files, or changing git state. Cloud embedding is only allowed for zero_shot; supervised or unsupervised finetune-capable workflows must use local models.


Data Format Requirements

THETA uses a strict column naming convention for data files.

Column Naming Convention

PurposeColumn NameRequired ForFormat
TexttextAll modelsString
TimestamptimestampDTM2026, 2026-10-17, or 2026-10-17 14:30:00
Covariatescov_*STMPrefix with cov_ (e.g., cov_province)
LabellabelSupervisedString or integer

Model-Specific Requirements

ModelRequired Columns
DTMtext, timestamp
STMtext, cov_*

DTM Note: Only supports year-level granularity. Dates like 2026-10-17 are converted to 2026.

STM Note: All covariate columns must use the cov_ prefix.

See example/DATA_FORMAT_TEMPLATE.md for CSV templates.


Configuration System: From Hardware to Experiments

THETA uses a layered configuration architecture for flexible control from hardware paths to experiment parameters.

Core Configuration File .env (Hardware Physical Paths)

Create a .env file (refer to .env.example) with required settings:

# Default for zero_shot: cloud embedding service
EMBEDDING_PROVIDER=cloud
EMBEDDING_CLOUD_PROVIDER=openai
OPENAI_API_KEY=your-openai-api-key
# Optional: EMBEDDING_MODEL=text-embedding-3-small# Required for supervised/unsupervised modes because fine-tuning needs local weights# EMBEDDING_PROVIDER=local# QWEN_MODEL_0_6B=./models/qwen3_embedding_0.6B# Required: SBERT model path (needed for CTM/BERTopic)
SBERT_MODEL_PATH=./models/sbert/sentence-transformers/all-MiniLM-L6-v2
# Required: Data and result directories
DATA_DIR=./data
WORKSPACE_DIR=./data/workspace
RESULT_DIR=./result

Experiment Parameters config/default.yaml (Default Hyperparameters)

This file stores default training parameters for all models:

# Common training parameterstraining:
epochs: 100batch_size: 64learning_rate: 0.002# THETA-specific parameterstheta:
num_topics: 20hidden_dim: 512model_size: 0.6B# Visualization settingsvisualization:
language: en # English visualizationdpi: 150

Priority Rule

Parameter priority order:

CLI arguments > YAML defaults > Code fallback values

Example:

  • --num_topics 50 overrides num_topics: 20 in YAML
  • If neither CLI nor YAML specifies a value, code defaults are used

Running Modes: Beginner vs Expert

Beginner Mode: One-Click Automation (Bash Scripts)

Just prepare your data, and the script will automatically complete cleaning → preprocessing → training → evaluation → visualization:

# One-click training (specify language parameter)
bash scripts/quick_start.sh my_dataset --language chinese
bash scripts/quick_start.sh my_dataset --language english

Data Preparation Requirements:

  • Place raw documents in data/{dataset}/ directory
  • Supported formats: .txt, .csv, .docx, .pdf

Expert Mode: Surgical-Level Tuning (Python CLI)

Directly call Python scripts with precise control over every parameter:

# Train LDA, override default parameters
python src/models/run_pipeline.py \
--dataset my_dataset \
--models lda \
--num_topics 50 \
--learning_rate 0.01 \
--language chinese
# Train THETA with 4B model
python src/models/run_pipeline.py \
--dataset my_dataset \
--models theta \
--model_size 4B \
--num_topics 30 \
--epochs 200

Key Module Entry Points:

ModuleEntry ScriptFunction
Data Cleaningsrc/models/dataclean/main.pyText cleaning, tokenization, stopword removal
Data Preprocessingsrc/models/prepare_data.pyGenerate BOW matrix and embedding vectors
Model Trainingsrc/models/run_pipeline.pyTraining, evaluation, visualization all-in-one

Output Map: Where Are the Results?

THETA model and baseline model result paths are different, please note the distinction:

THETA Model Results

result/{dataset}/{model_size}/theta/exp_{timestamp}/
├── config.json # Experiment configuration
├── metrics.json # 7 evaluation metrics
├── data/ # Preprocessed data
│ ├── bow/ # BOW matrix
│ │ ├── bow_matrix.npy
│ │ ├── vocab.txt
│ │ ├── vocab.json
│ │ └── vocab_embeddings.npy
│ └── embeddings/ # Qwen document embeddings
│ ├── embeddings.npy
│ └── metadata.json
├── theta/ # Model parameters (fixed filenames, no timestamp)
│ ├── theta.npy # Document-topic distribution (D × K)
│ ├── beta.npy # Topic-word distribution (K × V)
│ ├── topic_embeddings.npy # Topic embedding vectors
│ ├── topic_words.json # Topic word list
│ ├── training_history.json # Training history
│ └── etm_model.pt # PyTorch model
└── {lang}/ # Visualization output (zh or en)
├── global/ # Global charts
│ ├── topic_table.csv
│ ├── topic_network.png
│ ├── topic_similarity.png
│ ├── topic_wordcloud.png
│ ├── 7_core_metrics.png
│ └── ...
└── topic/ # Topic details
├── topic_1/
│ └── word_importance.png
└── ...

Baseline Model Results (LDA, CTM, BTM, etc.)

result/{dataset}/{user_id}/{model}/exp_{timestamp}/
├── config.json # Experiment configuration
├── metrics_k{K}.json # 7 evaluation metrics
├── {model}/ # Model parameters
│ ├── theta_k{K}.npy # Document-topic distribution
│ ├── beta_k{K}.npy # Topic-word distribution
│ ├── model_k{K}.pkl # Model file
│ └── topic_words_k{K}.json
├── {lang}/ # Visualization directory (zh or en)
│ ├── global/ # Global comparison charts
│ │ ├── topic_network.png
│ │ ├── topic_similarity.png
│ │ └── ...
│ └── topic/ # Topic details
│ ├── topic_0/
│ │ ├── wordcloud.png
│ │ └── word_distribution.png
│ └── ...
└── README.md # Experiment summary

Path Summary

Model TypeResult Path
THETAresult/{dataset}/{model_size}/theta/exp_{timestamp}/
Baseline Modelsresult/{dataset}/{user_id}/{model}/exp_{timestamp}/

Scientific Evaluation Standards

THETA enforces 7 Gold Standard Metrics to ensure evaluation alignment across all models (THETA and 12 baselines):

MetricFull NameDescriptionIdeal Value
TDTopic DiversityTopic diversity, measures uniqueness of topic words↑ Higher is better
iRBOInverse Rank-Biased OverlapInverse rank-biased overlap, measures inter-topic differences↑ Higher is better
NPMINormalized PMINormalized pointwise mutual information, measures topic word co-occurrence↑ Higher is better
C_VC_V CoherenceSliding window-based coherence↑ Higher is better
UMassUMass CoherenceDocument co-occurrence-based coherence↑ Higher is better (negative)
ExclusivityTopic ExclusivityTopic exclusivity, whether words belong to single topics↑ Higher is better
PPLPerplexityPerplexity, model fitting ability↓ Lower is better

Note: Significance data is only used for visualization, not included in core evaluation metrics.


Supported Models

Model Overview

ModelTypeDescriptionAuto TopicsBest Use Case
thetaNeuralTHETA model with Qwen embeddingsNoGeneral purpose, high quality
ldaTraditionalLatent Dirichlet AllocationNoFast baseline, highly interpretable
hdpTraditionalHierarchical Dirichlet ProcessYesUnknown topic count
stmTraditionalStructural Topic ModelNoRequires covariates
btmTraditionalBiterm Topic ModelNoShort texts (tweets, titles)
etmNeuralEmbedded Topic ModelNoWord embedding integration
ctmNeuralContextualized Topic ModelNoSemantic understanding
dtmNeuralDynamic Topic ModelNoTime series analysis
nvdmNeuralNeural Variational Document ModelNoVAE baseline
gsmNeuralGaussian Softmax ModelNoBetter topic separation
prodldaNeuralProduct of Experts LDANoState-of-the-art neural LDA
bertopicNeuralBERT-based topic modelingYesClustering-based topics

Model Selection Guide

┌─────────────────────────────────────────────────────────────────┐
│ Do you know the number of topics? │
│ ├─ No → Use HDP or BERTopic (auto-detect topic count) │
│ └─ Yes → Continue below │
├─────────────────────────────────────────────────────────────────┤
│ What is your text length? │
│ ├─ Short texts (tweets, titles) → Use BTM │
│ └─ Normal/Long texts → Continue below │
├─────────────────────────────────────────────────────────────────┤
│ Do you have document-level metadata (covariates)? │
│ ├─ Yes → Use STM (models how metadata affects topics) │
│ └─ No → Continue below │
├─────────────────────────────────────────────────────────────────┤
│ Do you have time series data? │
│ ├─ Yes → Use DTM │
│ └─ No → Continue below │
├─────────────────────────────────────────────────────────────────┤
│ What is your priority? │
│ ├─ Speed → Use LDA (fastest) │
│ ├─ Quality → Use THETA (best with Qwen embeddings) │
│ └─ Comparison → Use multiple models: lda,nvdm,prodlda,theta │
└─────────────────────────────────────────────────────────────────┘

Training Parameters Reference

Common Parameters

Shared across all or most models. Parameters marked * apply to neural network–based models only.

ParameterTypeDefaultRangeDescription
--num_topicsint205–100Number of topics K (upper bound for HDP; optional for BERTopic)
--vocab_sizeint50001000–20000Vocabulary size
--epochs *int10010–500Training epochs
--batch_size *int648–512Mini-batch size
--learning_rate *float0.0021e-5–0.1Learning rate
--dropout *float0.20–0.9Encoder dropout rate
--hidden_dim *int512128–2048Hidden units per layer (NVDM/GSM/ProdLDA default: 256)
--num_layers *int21–5Number of encoder hidden layers
--patience *int101–50Early stopping patience

Model-Specific Additional Parameters

THETA

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--model_sizestr0.6B0.6B / 4B / 8BQwen model size
--embedding-providerstrcloud for zero_shotcloud / local / provider presetEmbedding provider; supervised/unsupervised require local Qwen
--embedding-cloud-providerstropenaiopenai / dashscope / siliconflow / zhipu / volcengine / openai_compatibleCloud embedding preset
--modestrzero_shotzero_shot / supervised / unsupervisedEmbedding mode
--kl_startfloat0.00–1KL annealing start weight
--kl_endfloat1.00–1KL annealing end weight
--kl_warmupint500–epochsKL warmup epochs
--languagestrzhen / zhVisualization language

LDA

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--max_iterint10010–500Maximum EM iterations
--alphafloat1/K (auto)>0Document-topic Dirichlet prior

HDP

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--max_topicsint15050–300Upper bound on number of topics (replaces --num_topics)
--alphafloat1.0>0Document-level concentration parameter

STM

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--max_iterint10010–500Maximum EM iterations

BTM

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--n_iterint10010–500Gibbs sampling iterations (replaces --epochs)
--alphafloat1.0>0Topic distribution Dirichlet prior
--betafloat0.01>0Word distribution Dirichlet prior

ETM

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--embedding_dimint30050–1024Word embedding dimension (Word2Vec)

CTM

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--inference_typestrzeroshotzeroshot / combinedInference mode: SBERT only or SBERT + BOW
--hidden_dimint10032–1024Overrides common default (512 → 100)

DTM

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--embedding_dimint30050–1024Word embedding dimension

Note: DTM does not use --num_layers, --dropout, or --patience.
Data requirement: DTM requires a timestamp column. Run python prepare_data.py --dataset your_data --model dtm before training.

NVDM / GSM / ProdLDA

No additional parameters — all settings covered by common defaults.

Note: --hidden_dim defaults to 256 for these models.

BERTopic

Additional parameters beyond common defaults:

ParameterTypeDefaultRangeDescription
--min_cluster_sizeint102–100HDBSCAN minimum cluster size; controls topic granularity
--min_samplesintNone1–100HDBSCAN min_samples (defaults to min_cluster_size)
--top_n_wordsint101–30Top words displayed per topic
--n_neighborsint152–100UMAP number of neighbors
--n_componentsint52–50UMAP reduced dimensions
--random_stateint42any intUMAP random seed for reproducibility

Note: BERTopic does not use --epochs, --batch_size, --learning_rate, or other neural training parameters.
--num_topics is optional; set to None for auto-detection.


FAQ

Data Requirements

Q: What is the minimum number of documents required?

A: Minimum 5 documents. Topic models need sufficient documents to learn meaningful topic distributions. Recommendations:

  • Small experiments: 50+ documents
  • Formal research: 500+ documents
  • Large-scale analysis: 5000+ documents

Q: What data formats are supported?

A: Supports .txt, .csv, .docx, .pdf. CSV files need a text column (or specify another column via --text_column).


Memory & Performance

Q: What to do about Out of Memory (OOM)?

A: When GPU memory is insufficient, adjust in this order:

StageParameterRecommended Value
Embedding generation--batch_size4–8
THETA/Neural model training--batch_size16–32
Use smaller model--model_size0.6B instead of 4B
# Check GPU usage
nvidia-smi
# Kill zombie processeskill -9 <PID>

Q: Why is BTM training slow?

A: BTM uses Gibbs sampling, with computation proportional to biterm count × iterations. For large datasets, it may take 30–90 minutes. Reduce iterations with --n_iter 50 to speed up.


Model Selection

Q: What's the difference between ETM and DTM?

A:

  • ETM: Static topic model, learns fixed topics across the entire corpus
  • DTM: Dynamic topic model, models topic evolution over time, requires timestamp column

Q: Why was STM skipped?

A: STM requires covariates (document-level metadata). If the dataset doesn't have configured covariates, STM is automatically skipped. Alternatives: use CTM or LDA.

Q: How to choose the number of topics K?

Dataset SizeRecommended K
< 1000 docs5–15
1000–1000010–30
> 1000020–50

You can also use hdp or bertopic to auto-detect topic count as a reference.


Visualization

Q: What does the --language parameter do?

A: Controls the language of visualization charts:

  • chinese or zh: Chinese chart titles and filenames (e.g., 主题网络图.png)
  • english or en: English chart titles and filenames (e.g., topic_network.png)

Only affects visualization, not model training or evaluation.


Other

Q: Is this project only for Qwen?

A: No. Qwen is the default embedding model, but THETA is designed to be model-agnostic. You can adapt other embedding models (e.g., BERT, LLaMA).

Q: How to add a custom dataset?

A:

  1. Place cleaned CSV in data/{dataset}/ directory
  2. Ensure CSV contains a text column
  3. Run: bash scripts/quick_start.sh {dataset} --language english

Citation

If you find THETA useful in your research, please consider citing our paper:

@article{duan2026theta,
title={THETA: A Textual Hybrid Embedding-based Topic Analysis Framework and AI Scientist Agent for Scalable Computational Social Science},
author={Codesoul.co},
journal={TBD},
year={2026},
doi={TBD}
}

Contact

For questions, please contact:


License

Apache-2.0

About

LLM-adaptive embeddings (Zero-shot / LoRA) with Generative Topic Modeling & Agent-based workflow for social science text mining

Topics

Resources

Stars

21 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages