This project explores whether training a language model (LLM) on spelling tasks improves its ability to answer position and count questions about words. The experiment is structured using Taskmaster for rigorous, task-driven development and reproducibility.
The project now features sophisticated handling of multi-word tokens:
For detailed information about the component token extraction process, see docs/token_extraction.md.
enable_thinking=False). Thinking mode is strictly prohibited and enforced in code. Any attempt to use thinking mode will raise an error.data/processed/english_tokens.json (as a dict with a tokens key). The legacy .txt output has been removed. All downstream code and analysis should use the .json file.src/ layout, and a Cursor rule prevents import errors (see .cursor/rules/module_imports.mdc).english_tokens.json) is used for all experiments./docs/analysis.md, /docs/templates.md, /docs/data_format.md, and /docs/token_extraction.md for details.transformers library..cursor/rules/module_imports.mdc for enforced import rules.configs/ — Configuration files including templatesdata/ — Training data and generated examples
processed/ — Generated examples and variationsraw/ — Original word lists and datasplits/ — Train/val/test splitsdocs/ — Project documentation
templates.md — Template system documentationdata_format.md — Data format specificationsresults/ — Analysis results and visualizations
token_analysis/ — Template analysis results
data/ — Raw analysis data in CSV formatfigures/ — Generated plots and visualizationsreports/ — HTML analysis reportsscripts/ — Utility scripts, PRD, and complexity reportssrc/ — Source code
analysis/ — Analysis scripts and utilities
template_analysis.py — Template pattern analysistemplate_performance.py — Performance metrics analysisvisualization_utils.py — Shared plotting utilitiesdata/ — Data processing and example generationevaluation/ — Model evaluation codemodels/ — Model definitionstraining/ — Training utilitiestasks/ — Taskmaster-generated task files and subtasks.env.example — Template for required environment variables.env — Your local environment configuration (not committed)README.md — This documentationMac M1/M2 Users: For a detailed, up-to-date setup guide (including troubleshooting and performance tips), see docs/apple_silicon_setup.md.
Local Quantized Inference: For step-by-step instructions and troubleshooting for Ollama, see docs/ollama_integration.md.
Cloud Training & GPU Workflows: For a complete guide to running this project in the cloud (Colab, Lightning, custom VM), see docs/cloud_workflow.md.
Google Colab Notebooks: For detailed instructions on running project notebooks in Google Colab, see docs/colab.md.
Use uv for Python environment and package management.
curl -fsSL https://astral.sh/uv/install.sh | bash
uv venv .venv
On macOS/Linux:
source .venv/bin/activate
On Windows:
.venv\Scripts\activate
For a new repo, start with the most common tools:
uv pip install black ruff mypy ipython requests torch transformers datasets wandb dspy lightning matplotlib seaborn pandas jupyter notebook ipywidgets
Do NOT install Unsloth or xformers locally. These are for cloud environments only.
uv pip install ollama
uv pip freeze > requirements.txt
Commit requirements.txt to version control.
uv --version
Add the output to your README.md or a setup section for future reference.
Tip:
Whenever you add new packages, always run uv pip freeze > requirements.txt again to keep your requirements up to date.
All fine-tuning, Unsloth, and xformers steps must be performed in a cloud environment.
pip install torch transformers datasets wandb dspy lightning matplotlib seaborn pandas jupyter notebook ipywidgets unsloth xformers
unsloth and xformers in the cloud.| Step | Local (Mac/Apple Silicon) | Cloud (Colab/Lightning/VM) |
|---|---|---|
| Python env setup | uv, .venv | pip, conda, or platform default |
| Install transformers | ✅ | ✅ |
| Install Ollama | ✅ | 🚫 |
| Install Unsloth/xformers | 🚫 | ✅ |
| Data preparation | ✅ | ✅ |
| Token extraction | ✅ | ✅ |
| Fine-tuning/training | 🚫 | ✅ |
| Quantized inference | ✅ (Ollama) | ✅ (if needed) |
| GPU acceleration | 🚫 | ✅ |
Legend: ✅ = Supported, 🚫 = Not supported
uv pip install ollama only on Mac/Apple Silicon for local quantized inference.Local (Mac/Apple Silicon):
uv pip install transformers ollama
python scripts/extract_english_tokens.py
Cloud (Colab):
pip install transformers unsloth xformers
python scripts/train.py --model Qwen3-4B --data data/processed/tokens.json --output results/model/
Copy .env.example to .env:
cp .env.example .env
Fill in all required values (API keys, etc.).
Never commit .env with secrets to version control.
Log in to Weights & Biases:
wandb login
Log in to Hugging Face:
huggingface-cli login
All development is managed via Taskmaster tasks.
To see current tasks:
task-master list --with-subtasks
To see the next actionable task:
task-master next
Tasks are broken down into subtasks for clarity and iterative progress.
Follow the details and test strategies in each task file in tasks/.
The project uses a template-based system to generate diverse training examples. All tokenization and example generation use the Qwen3-4B tokenizer and the English-only token subset.
configs/templates/categories.jsonfrom src.data.example_generator import ExampleGenerator, TemplateConfig
from pathlib import Path
# Configure paths
config = TemplateConfig(
templates_dir=Path("configs/templates"),
output_dir=Path("data/processed/template_variations")
)
generator = ExampleGenerator(config)
# Generate examples
examples = generator.generate_examples(
words=["apple", "banana"],
num_variations=3,
balance_categories=True
)
# Each example will use a different template and separator style.
from src.data.data_loader import TemplateDataLoader, BatchConfig
from pathlib import Path
# Configure batch settings
batch_config = BatchConfig(
batch_size=32,
max_length=512,
similar_length_tolerance=50,
shuffle=True
)
# Initialize data loader
loader = TemplateDataLoader(
data_dir=Path("data/processed/template_variations"),
batch_config=batch_config,
split_ratios=(0.8, 0.1, 0.1) # train/val/test
)
# Get dataset statistics
stats = loader.get_stats()
print(f"Total examples: {stats.total_examples}")
print(f"Average sequence length: {stats.avg_sequence_length:.2f}")
# Iterate over batches
for batch in loader.train_batches():
inputs = batch["inputs"] # List of input sequences
outputs = batch["outputs"] # List of target outputs
template_cats = batch["template_categories"] # Template categories
separator_styles = batch["separator_styles"] # Separator styles used
The data loader provides:
docs/data_format.md for detailed specificationsdata/processed/english_tokens.json (JSON with a tokens key).All analysis scripts use the Qwen3-4B tokenizer and support only non-thinking mode. See /docs/analysis.md for details.
src/analysis/template_analysis.py)Analyzes characteristics and distribution of template variations:
# Run template analysis
python -m src.analysis.template_analysis \
--data-dir data/processed \
--output-dir results/token_analysis \
--batch-size 32
Generates:
src/analysis/template_performance.py)Analyzes how different template variations affect model performance:
# Run performance analysis
python -m src.analysis.template_performance \
--data-dir data/processed \
--output-dir results/token_analysis \
--batch-size 32
Generates:
Both scripts use shared visualization utilities from src/analysis/visualization_utils.py for consistent styling and report generation.
xformers or unsloth during install, ignore them locally and move to the cloud workflow for those steps.Open Google Colab or Lightning.ai.
Upload your code and data, or clone your repo.
In a Colab cell, run:
!pip install unsloth torch transformers datasets wandb dspy lightning matplotlib seaborn pandas jupyter notebook ipywidgets
Proceed with Unsloth-based fine-tuning and training as described in your project tasks.
Download results/models back to your local machine as needed.
If dependencies fail to install, ensure you are using uv and not pip directly.
If you encounter missing environment variables, check .env.example for required keys.
For Taskmaster issues, see the Taskmaster documentation or run task-master --help.
If you see errors about xformers or unsloth on Mac, ignore them and use the cloud workflow for those steps.
If pip or python commands fail, check that you are using the correct virtual environment:
which python
which pip
Both should point to your .venv directory.
configs/templates/ — Template configuration filesdata/processed/template_variations/ — Generated examplesdocs/templates.md — Template system documentationdocs/data_format.md — Data format specificationsresults/token_analysis/ — Analysis results and reportssrc/analysis/ — Analysis scripts and utilitiessrc/data/example_generator.py — Example generation codesrc/data/token_separator.py — Token separation utilitiesscripts/ — Scripts, PRD, complexity reportstasks/ — Task files and subtasks.env.example — Environment variable template.env — Local environment (not committed)README.md — Project documentationThis project uses a task-specific dataset split for all experiments:
spelling_first, word_first, and structured template categories.char_count_question and char_position_question template categories.Run the orchestration script:
PYTHONPATH=. python scripts/generate_dataset_splits.py
This will:
data/processed/english_tokens.jsondata/processed/train_spelling.jsondata/processed/val_char_questions.jsondata/processed/test_char_questions.jsonspelling_first, word_first, structuredchar_count_questionchar_position_questionSee /docs/data_format.md for the JSON structure of each split.
To ensure all generated datasets and token sets are valid and compatible with fine-tuning libraries, use the following tools:
Run the batch validation script to check all datasets in data/processed/:
python scripts/validate_datasets.py
Validate the canonical English token set:
python src/data/validate_alpaca_schema.py data/processed/english_tokens.json
Validate the multi-token word set:
python src/data/validate_alpaca_schema.py data/processed/english_multi_tokens.json
Whenever you generate examples using ExampleGenerator.save_examples, Alpaca schema validation is automatically run on the output file. Warnings are printed if any invalid examples are found.
See also:
All data loading and evaluation pipelines require datasets to conform to the Alpaca format. Validation is enforced automatically in the code, but you can manually validate datasets using:
PYTHONPATH=. python scripts/validate_datasets.py
Note: Always run scripts in the scripts/ directory with the correct import path (use PYTHONPATH=. or python -m scripts.<script_name>) to avoid import errors.
61 commits
Python
79.3%
Jupyter Notebook
17.7%
HTML
3.0%
This project explores whether training a language model (LLM) on spelling tasks improves its ability to answer position and count questions about words. The experiment is structured using Taskmaster for rigorous, task-driven development and reproducibility.
The project now features sophisticated handling of multi-word tokens:
For detailed information about the component token extraction process, see docs/token_extraction.md.
enable_thinking=False). Thinking mode is strictly prohibited and enforced in code. Any attempt to use thinking mode will raise an error.data/processed/english_tokens.json (as a dict with a tokens key). The legacy .txt output has been removed. All downstream code and analysis should use the .json file.src/ layout, and a Cursor rule prevents import errors (see .cursor/rules/module_imports.mdc).english_tokens.json) is used for all experiments./docs/analysis.md, /docs/templates.md, /docs/data_format.md, and /docs/token_extraction.md for details.transformers library..cursor/rules/module_imports.mdc for enforced import rules.configs/ — Configuration files including templatesdata/ — Training data and generated examples
processed/ — Generated examples and variationsraw/ — Original word lists and datasplits/ — Train/val/test splitsdocs/ — Project documentation
templates.md — Template system documentationdata_format.md — Data format specificationsresults/ — Analysis results and visualizations
token_analysis/ — Template analysis results
data/ — Raw analysis data in CSV formatfigures/ — Generated plots and visualizationsreports/ — HTML analysis reportsscripts/ — Utility scripts, PRD, and complexity reportssrc/ — Source code
analysis/ — Analysis scripts and utilities
template_analysis.py — Template pattern analysistemplate_performance.py — Performance metrics analysisvisualization_utils.py — Shared plotting utilitiesdata/ — Data processing and example generationevaluation/ — Model evaluation codemodels/ — Model definitionstraining/ — Training utilitiestasks/ — Taskmaster-generated task files and subtasks.env.example — Template for required environment variables.env — Your local environment configuration (not committed)README.md — This documentationMac M1/M2 Users: For a detailed, up-to-date setup guide (including troubleshooting and performance tips), see docs/apple_silicon_setup.md.
Local Quantized Inference: For step-by-step instructions and troubleshooting for Ollama, see docs/ollama_integration.md.
Cloud Training & GPU Workflows: For a complete guide to running this project in the cloud (Colab, Lightning, custom VM), see docs/cloud_workflow.md.
Google Colab Notebooks: For detailed instructions on running project notebooks in Google Colab, see docs/colab.md.
Use uv for Python environment and package management.
curl -fsSL https://astral.sh/uv/install.sh | bash
uv venv .venv
On macOS/Linux:
source .venv/bin/activate
On Windows:
.venv\Scripts\activate
For a new repo, start with the most common tools:
uv pip install black ruff mypy ipython requests torch transformers datasets wandb dspy lightning matplotlib seaborn pandas jupyter notebook ipywidgets
Do NOT install Unsloth or xformers locally. These are for cloud environments only.
uv pip install ollama
uv pip freeze > requirements.txt
Commit requirements.txt to version control.
uv --version
Add the output to your README.md or a setup section for future reference.
Tip:
Whenever you add new packages, always run uv pip freeze > requirements.txt again to keep your requirements up to date.
All fine-tuning, Unsloth, and xformers steps must be performed in a cloud environment.
pip install torch transformers datasets wandb dspy lightning matplotlib seaborn pandas jupyter notebook ipywidgets unsloth xformers
unsloth and xformers in the cloud.| Step | Local (Mac/Apple Silicon) | Cloud (Colab/Lightning/VM) |
|---|---|---|
| Python env setup | uv, .venv | pip, conda, or platform default |
| Install transformers | ✅ | ✅ |
| Install Ollama | ✅ | 🚫 |
| Install Unsloth/xformers | 🚫 | ✅ |
| Data preparation | ✅ | ✅ |
| Token extraction | ✅ | ✅ |
| Fine-tuning/training | 🚫 | ✅ |
| Quantized inference | ✅ (Ollama) | ✅ (if needed) |
| GPU acceleration | 🚫 | ✅ |
Legend: ✅ = Supported, 🚫 = Not supported
uv pip install ollama only on Mac/Apple Silicon for local quantized inference.Local (Mac/Apple Silicon):
uv pip install transformers ollama
python scripts/extract_english_tokens.py
Cloud (Colab):
pip install transformers unsloth xformers
python scripts/train.py --model Qwen3-4B --data data/processed/tokens.json --output results/model/
Copy .env.example to .env:
cp .env.example .env
Fill in all required values (API keys, etc.).
Never commit .env with secrets to version control.
Log in to Weights & Biases:
wandb login
Log in to Hugging Face:
huggingface-cli login
All development is managed via Taskmaster tasks.
To see current tasks:
task-master list --with-subtasks
To see the next actionable task:
task-master next
Tasks are broken down into subtasks for clarity and iterative progress.
Follow the details and test strategies in each task file in tasks/.
The project uses a template-based system to generate diverse training examples. All tokenization and example generation use the Qwen3-4B tokenizer and the English-only token subset.
configs/templates/categories.jsonfrom src.data.example_generator import ExampleGenerator, TemplateConfig
from pathlib import Path
# Configure paths
config = TemplateConfig(
templates_dir=Path("configs/templates"),
output_dir=Path("data/processed/template_variations")
)
generator = ExampleGenerator(config)
# Generate examples
examples = generator.generate_examples(
words=["apple", "banana"],
num_variations=3,
balance_categories=True
)
# Each example will use a different template and separator style.
from src.data.data_loader import TemplateDataLoader, BatchConfig
from pathlib import Path
# Configure batch settings
batch_config = BatchConfig(
batch_size=32,
max_length=512,
similar_length_tolerance=50,
shuffle=True
)
# Initialize data loader
loader = TemplateDataLoader(
data_dir=Path("data/processed/template_variations"),
batch_config=batch_config,
split_ratios=(0.8, 0.1, 0.1) # train/val/test
)
# Get dataset statistics
stats = loader.get_stats()
print(f"Total examples: {stats.total_examples}")
print(f"Average sequence length: {stats.avg_sequence_length:.2f}")
# Iterate over batches
for batch in loader.train_batches():
inputs = batch["inputs"] # List of input sequences
outputs = batch["outputs"] # List of target outputs
template_cats = batch["template_categories"] # Template categories
separator_styles = batch["separator_styles"] # Separator styles used
The data loader provides:
docs/data_format.md for detailed specificationsdata/processed/english_tokens.json (JSON with a tokens key).All analysis scripts use the Qwen3-4B tokenizer and support only non-thinking mode. See /docs/analysis.md for details.
src/analysis/template_analysis.py)Analyzes characteristics and distribution of template variations:
# Run template analysis
python -m src.analysis.template_analysis \
--data-dir data/processed \
--output-dir results/token_analysis \
--batch-size 32
Generates:
src/analysis/template_performance.py)Analyzes how different template variations affect model performance:
# Run performance analysis
python -m src.analysis.template_performance \
--data-dir data/processed \
--output-dir results/token_analysis \
--batch-size 32
Generates:
Both scripts use shared visualization utilities from src/analysis/visualization_utils.py for consistent styling and report generation.
xformers or unsloth during install, ignore them locally and move to the cloud workflow for those steps.Open Google Colab or Lightning.ai.
Upload your code and data, or clone your repo.
In a Colab cell, run:
!pip install unsloth torch transformers datasets wandb dspy lightning matplotlib seaborn pandas jupyter notebook ipywidgets
Proceed with Unsloth-based fine-tuning and training as described in your project tasks.
Download results/models back to your local machine as needed.
If dependencies fail to install, ensure you are using uv and not pip directly.
If you encounter missing environment variables, check .env.example for required keys.
For Taskmaster issues, see the Taskmaster documentation or run task-master --help.
If you see errors about xformers or unsloth on Mac, ignore them and use the cloud workflow for those steps.
If pip or python commands fail, check that you are using the correct virtual environment:
which python
which pip
Both should point to your .venv directory.
configs/templates/ — Template configuration filesdata/processed/template_variations/ — Generated examplesdocs/templates.md — Template system documentationdocs/data_format.md — Data format specificationsresults/token_analysis/ — Analysis results and reportssrc/analysis/ — Analysis scripts and utilitiessrc/data/example_generator.py — Example generation codesrc/data/token_separator.py — Token separation utilitiesscripts/ — Scripts, PRD, complexity reportstasks/ — Task files and subtasks.env.example — Environment variable template.env — Local environment (not committed)README.md — Project documentationThis project uses a task-specific dataset split for all experiments:
spelling_first, word_first, and structured template categories.char_count_question and char_position_question template categories.Run the orchestration script:
PYTHONPATH=. python scripts/generate_dataset_splits.py
This will:
data/processed/english_tokens.jsondata/processed/train_spelling.jsondata/processed/val_char_questions.jsondata/processed/test_char_questions.jsonspelling_first, word_first, structuredchar_count_questionchar_position_questionSee /docs/data_format.md for the JSON structure of each split.
To ensure all generated datasets and token sets are valid and compatible with fine-tuning libraries, use the following tools:
Run the batch validation script to check all datasets in data/processed/:
python scripts/validate_datasets.py
Validate the canonical English token set:
python src/data/validate_alpaca_schema.py data/processed/english_tokens.json
Validate the multi-token word set:
python src/data/validate_alpaca_schema.py data/processed/english_multi_tokens.json
Whenever you generate examples using ExampleGenerator.save_examples, Alpaca schema validation is automatically run on the output file. Warnings are printed if any invalid examples are found.
See also:
All data loading and evaluation pipelines require datasets to conform to the Alpaca format. Validation is enforced automatically in the code, but you can manually validate datasets using:
PYTHONPATH=. python scripts/validate_datasets.py
Note: Always run scripts in the scripts/ directory with the correct import path (use PYTHONPATH=. or python -m scripts.<script_name>) to avoid import errors.
61 commits
Python
79.3%
Jupyter Notebook
17.7%
HTML
3.0%